Hi everyone,
Today, I am giving you some information about casting. so What is casting !!!
Casting is taking the same value of variable into other variable. e.g if we assume that "int i = 456123789;" and "byte b = 100;" than if we want to store the value of byte in integer i than we will write "int i1 = (int)b;" now "int i1 = 100;" too. This is called widening.
And on opposite side if we call int value in bye than we will write "byte b1 = (byte) i;" This is called narrowing.
But narrowing always cause the loss of information. Because you already know the reason, this is same as "We try to keep a book in a pencil box where we can only keep the pencil because pencil box is very small". Same thing is happening here.
Now we see the Java code of above variable and try to see the difference.
____________________________________________________
public class Casting {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 456123789;
byte b = 100;
System.out.println("Normal value");
System.out.println(" ");
System.out.println("i = "+i);
System.out.println("b = "+b);
System.out.println(" ");
System.out.println("Now after using Narrowing");
byte b1 = (byte) i;
System.out.println("b1 = "+b1);
System.out.println(" ");
System.out.println("After using widening");
int i1 = (int)b;
System.out.println("i1 ="+i1);
}
}
____________________________________________________
OUTPUT:
Normal value
i = 456123789
b = 100
Now after using Narrowing
b1 = -115
After using widening
i1 =100
________________________________________________________________________
We got b1 = -115 which is value of integer and real value of integer is 456123789, now you can see that, it is the loss of data.
If we put integer value in byte than the value going to change but if we use byte in integer than we get same value that is 100.
You can check this for your self by using different variables and enter different values.
No comments:
Post a Comment