Showing posts with label Type Casting in java with Example. Show all posts
Showing posts with label Type Casting in java with Example. Show all posts

Sunday, 25 November 2018

Type Casting in java with Example | Online Help

              Assigning a value of one type to another type is known as Type Casting. Whenever we assign a value to a variable using the assignment operator, The java compiler checks the uniformity and hence the data types at both sides should be the same. If the data types are not the same, then we should convert the types to become the same at both sides. To convert the data type, we use the cast operator. cast operator means writing the data type between simple braces, before a variable or method whose value is to be converted. Type casting refers to the type conversion that is performed explicitly.


The syntax for type casting is as follow:

                             data type variable1=(data_type) variable2;

where,
data_type is the data type
variable1 is the target variable
variable2 is the source variable

guys to see what is data types in detail click this link:
https://beingcomputeracy.blogspot.com/2018/11/data-types-in-java-java-programming.html

Example
int x=10;
byte y=(byte)x;

In this statements, type casting is performed to convert int data type to byte data type.

Following point should be kept in mind while typecasting:
1. All integers data type can be cast to any other data type except boolean.
2. Casting into small data type may lead to loss of data.
3. Casting a floating point value to an integer type may result in truncation of the fractional point.

Types of type casting:

In Java, type casting is classified into two types:
1.widening casting(Implicit type conversion)/Automatic type conversion.
2.Narrowing casting or Explicit type conversion.

Widening or automatic type conversion:

when one type of data is assigned to another type of variable, an automatic type conversion will takes place if the following two conditions are met: Automatic type casting takes place when,
1. The two types are compatible.
2. The target type is larger than the source type.

example:
public class test
{
public static void main(String args[])
{
int i=100;
long l=i;
float f=l;
system.out.println("int value:"+i);
system.out.println("long value:"+l);
system.out.println("float value:"+f);
}
}

output:
int value:100
long value:100
float value:100.0

Narrowing or Explicit type conversion:

When you are assigning a larger type value to a variable of smaller type,then you need to perform explicit type casting.
example:
public class test
{
public static void main(String args[])
{
float f=100;
long l=f; //Explicit type casting required
int i=l; //Explicit type casting is required
system.out.println("float value:"+f);
system.out.println("long value:"+l);
system.out.println("int value:"+i);
}
}

output:
float value:100.0
long value:100
int value:100