Search This Blog

Saturday, July 18, 2020

Casting in Java

Casting in Java:

casting  means to treat or convert a number from one type to another type. We put the type we want the number to be in parenthesis like below Example.

(byte)(myNumber/2);

where int myNumber =100;
 
Note : Casting concept in in other language as well.


Program:


public class CastingInJava {
public static void main(String[] args) {
int actualValue = 100;
int div = (actualValue / 2); // no casting becoz data type of div is int
System.out.println(div);

byte newDivInByte = (byte) (actualValue / 2);// Compile time error saying that Type mismatch: cannot convert
// from int to byte
System.out.println(newDivInByte);

short newDivInShort = (short) (actualValue / 2);
System.out.println("int to short casted value : "+newDivInShort);
}
}


No comments:

Post a Comment