Java Type Casting

Type Casting is nothing but to assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. Java performs automatic type conversion if one of the following conditions are met:
  1. The two types are compatible.
  2. The destination type is larger than the source type.
To create a conversion between two incompatible types, you must use an explicit type conversion. It has this general form:
(target-type) value
The following program demonstrate how to use type casting in Java.

PROGRAM
class TypeCasting {

 public static void main(String[] args) {
  
  byte b;
  int val = 263;
  double d = 9563.25;
  long l = 56322145;
  System.out.println("int val = "+val);
  System.out.println("double d = "+d);
  System.out.println("long l = "+l);
  System.out.println("\nint to byte ");
  b = (byte) val;
  System.out.println(val+" to "+b);
  System.out.println("\ndouble to int ");
  System.out.println(d+" to "+(int)d);
  System.out.println("\nlong to double ");
  System.out.println(l+" to "+(double)l);
  System.out.println("\nlong to short ");
  System.out.println(l+" to "+(short)l);
  System.out.println("\ndouble to byte ");
  System.out.println(d+" to "+(byte)d);
 }
}
The output is given below:

OUTPUT
C:\>javac TypeCasting.java
C:\>java TypeCasting
int val = 263
double d = 9563.25
long l = 56322145

int to byte 
263 to 7

double to int 
9563.25 to 9563

long to double 
56322145 to 5.6322145E7

long to short 
56322145 to 26721

double to byte 
9563.25 to 91

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet