Image

Java - Core Java - Type Casting

Type Casting

Conversion of one datatype into another datatype is known as type casting.

Java support two type of type casting

1) Implicit type casting

When one type of data assign another type of variable and automatic type conversion is take place. If the following two condition are If two type are compatible The destination type is larger than source type

WAP in java for implicit type casting
  class Pramot
   {
	public static void main(String args[])
  {
    	      byte b=42;
      char c='a';
      short s=1024;
      int  i=50000;
      float f=5.67f;
      double d=.1234;
      double result=(f*b)+(i/c)-(d*s);
      System.out.println((f*b)+"+"+(i/d)+"-"+(d*s));
      System.out.println("result="+result);
   }
}

O/P
g:\java>javac  Pramot .java
g:\java>java Pramot
238.14+405186.3857374392-126.3616
result=626.7784146484375

2) Explicit Type casting

A forcefully conversion of one datatype into another datatype in known as Explicit type casting.

WAP in java for explicit type casting
class Conversion
{
  public static void main(String args[])
  {
     byte b;
     int i=257;
     double d=323.142;
     System.out.println("\n Conversion of int to byte");
     b=(byte) i;
     System.out.println("i and b"+i+" "+b);
     System.out.println("\n Conversion of double to int");
     i=(int) d;
     System.out.println("d and i"+d+" "+i);
     System.out.println("\n Conversion of double to byte");
     b=(byte) d;
     System.out.println("d and b"+d+" "+b);
   }
}

O/P
G:\java>javac  Conversion.java
G:\java>java   conversion
Conversion of   int  to byte
I and b257 1
Conversion   of  double  to int
D and i323.142 323
Conversion   of  double  to  byte
D  and  b323.142  67

WAP in java Demonstrate char data type
class Demo
{
  public static void main(String args[])
  {
   char ch1,ch2;
   ch1=88;
   ch2='y';
   System.out.println("ch1 and ch2");
   System.out.println(ch1+ " " +ch2);
  }
}

O/P
g:\java>javac     Demo.java
g:\java>java     Demo
ch1   and    ch2
X    and    Y

WAP in java Demostrate Boolean value
class Boolean
{
  public static void main(String args[])
	{
	  boolean b;
	  b=false;
	  System.out.println("b is "+b);
                 b=true;
                 System.out.println("b is "+b);
	  if(b);
 	  System.out.println("This is executed");
	  b=false;
	  if(b);
	  System.out.println("This is not executed");
	  System.out.println("10>9 is"+(10>9));
	}
}

O/P
g:\java>javac  Boolean.java
g:\java>java   Boolean
b  is false
b  is  true
This is  executed
This  is  not  executed
10>9 is true