s
![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions | |
The process of converting one data type value to another data type value is called casting
. Type casting is useful when we want to convert one value into another like string 123 into integer 123.
Type casting refers to changing a type
of one data type into another. If you store an int value into a byte variable directly, this will be given as illegal operation.
type variable1 = (new_type) variable2;
int x = 20; byte b = (byte) x;
In above example, the variable x is a type of integer variable and we have converted it into the byte variable using type casting
Casting of large data type into smaller type may result in a loss
of data. It is always better to cast smaller type into larger.
Example of loss of data
int x = 130; byte b = (byte) x;
In above example the integer variable x having range 2,147,483,647
for storing a value. but the byte variable have only 127
.
130-127 = 3 data is lost in the conversion.
There is no loss of data from below conversion
Type | Converted into |
---|---|
byte | short,char,int,float,double |
short | int,float,double,long |
char | int,float,double,long |
int | float,double,long |
long | float,double |
float | double |
The process of assigning a larger
type to a smaller
type is known as narrowing, which causes loss of data.
class Narrowing { public static void main(String args[]) { int int_value = 32569; byte byte_value; byte_value = (byte ) int_value; System.out.println("Integer : "+int_value); System.out.println("Byte : "+byte_value); } }
Process of assigning smaller
data type value to larger
data type is known as widening. The data will not loss in widening.
Example
class Widening { public static void main(String args[]) { short old_salary = 30000; short salary_increased = 15000; int new_salary = (int) (old_salary + salary_increased)); System.out.println("old salary : "+old_salary); System.out.println("salary increased by : "+salary_increased); System.out.println("new salary is : "+new_salary); } }
For assigning one type of data values to another type of data variables, casting is required. But java also provides without casting conversion known as automatic type conversion
.
If data type is large enough to hold value of source value, then type casting is not required.
class AutotypeConversion { public static void main(String args[]) { short machine_cost = 9000; byte offer_given = 120; int new_price = machine_cost - offer_given ; System.out.println("Machine cost : "+machine_cost); System.out.println("New Machine cost : "+new_price); } }