Java Type Conversion

In Java, type conversion refers to converting data from one type to another. 

Implicit Type Conversion (Widening or Automatic Type Casting):

  • The conversion happens automatically when a smaller data type is converted to a larger data type.
  • Example: int to long.
Example
int num = 10;
long longNum = num; // int to long (widening)
float floatNum = num; // int to float (widening)

Try it yourself


Explicit Type Conversion (Narrowing)

  • Must be specified explicitly using a cast operator.
  • Converts data from a larger size to a smaller size, which might result in data loss.
  • Syntax: (targetType) value
Example
double num = 10.5;
int intNum = (int) num; // double to int (narrowing)
int aa=600;
byte byteNum=(byte)aa;

Try it yourself


Type Conversion Between Strings and Primitives:

  • Primitive to String: Use String.valueOf() or concatenation.
  • String to Primitive: Use wrapper classes like Integer.parseInt() or Double.parseDouble().
Example
int num = 10;
String str = String.valueOf(num); // "10"
String str2 = "25";
int num2 = Integer.parseInt(str2); // 25

Try it yourself


Automatic Type Promotion in Expressions:

In expressions, smaller types (byte, short, char) are automatically promoted to int.

Example
byte a = 10;
byte b = 20;
int result = a + b; // Automatically promoted to int
System.out.println("Result: " + result);

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.