[go: up one dir, main page]

0% found this document useful (0 votes)
80 views9 pages

1 - Java Type Casting - 5

The document explains Java type casting, which is the conversion of one data type to another, categorized into widening (implicit) and narrowing (explicit) type casting. It details the differences between type casting and type conversion, provides examples of both types of casting, and discusses casting between object references, including upcasting and downcasting. The document also emphasizes the importance of checking types during downcasting to avoid runtime exceptions.

Uploaded by

Mani Baluchamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views9 pages

1 - Java Type Casting - 5

The document explains Java type casting, which is the conversion of one data type to another, categorized into widening (implicit) and narrowing (explicit) type casting. It details the differences between type casting and type conversion, provides examples of both types of casting, and discusses casting between object references, including upcasting and downcasting. The document also emphasizes the importance of checking types during downcasting to avoid runtime exceptions.

Uploaded by

Mani Baluchamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Type Casting

The process of converting the value of one data type (int, float, double, etc.) to another data
type is known as typecasting. In Java, there are 13 types of type conversion.

1. Widening Type Casting 2. Narrowing Type Casting

Widening Type Casting

In Widening Type Casting, Java automatically converts one data type to another data type.

The lower data type (having smaller size) is


converted into the higher data type (having larger size).
Hence there is no loss in data.

This is also known as Implicit Type Casting.

Converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double

Narrowing Type Casting

In Narrowing Type Casting, we manually convert one data type into another using the
parenthesis.

The higher data types (having larger size) are


converted into lower data types (having smaller size).
Hence there is the loss of data.
This is why this type of conversion does not happen automatically.

This is also known as Explicit Type Casting.

Converting a larger type to a smaller size type

double -> float -> long -> int -> char -> short -> byte
Difference Between Type Casting and Type Conversion in Java

Type Conversion Type Casting


Involves changing the representation or Involves changing the data type of a variable.
format of a value.
Can involve conversion Performs conversion
between incompatible data types as well. between compatible data types.
Can be done implicitly by the Java compiler. Requires explicit instructions using casting
syntax.
Can involve manipulation or transformation of Can result in loss of data or precision if
data without necessarily changing the data type. narrowing conversion is performed.
Example: Integer.toString(num) converts Example: (double) num converts
num to a string without changing its data type. num from an integer to a double explicitly.

Example : Explicit - Converting from int to String ---> String.valueOf()

class Main {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);

// converts int to string type


String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}

Output

The integer value is: 10


The string value is: 10

Example : Explicit - Converting from String to int ----------> Integer.parseInt()

class Main {
public static void main(String[] args) {
// create string type variable
String data = "10";
System.out.println("The string value is: " + data);

// convert string variable to int


int num = Integer.parseInt(data);
System.out.println("The integer value is: " + num);
}
}
Output

The string value is: 10


The integer value is: 10

Example : Implicit - Converting Int to Double

class Main {
public static void main(String[] args) {

// create int type variable

int num = 50;


System.out.println("The integer value: " + num);

// convert into double type

double data = num;


System.out.println("The double value: " + data);

Output:

Integer value: 50
Double value: 50.0

Example : Converting Double into an Int

class Main {
public static void main(String[] args) {

// create double type variable

double num = 50.55;


System.out.println("The double value: " + num);

// convert into int type

int data = (int)num;


System.out.println("The integer value: " + data);
}
}

Output:
Double value: 50.55
Integer value: 50
Example : Implicit - converting from int to long, float

public class WideningTypeCastingExample


{
public static void main(String[] args)
{
int x = 7;

//automatically converts the integer type into long type


long y = x;

//automatically converts the long type into float type


float z = y;

System.out.println("Before conversion, int value "+x);


System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}

Output :

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

Example : byte --> int, short ---> int, int ---> double

public class HelloWorld{


public static void main(String []args){
// Byte promoted to int
byte i = 10;
int x = i + 5;
System.out.println("byte converted int -> "+x);

// Short promoted to int


short short_num = 15;
int Big = short_num + 115;
System.out.println("short converted int -> "+Big);

// int promoted to double


int num = 5;
double Big_num = num + 15.5;
System.out.println("int converted double -> "+Big_num);
}
}
Output :

byte converted int -> 15


short converted int -> 130
int converted double -> 20.5

NarrowingTypeCasting -

22 types of primitive conversion are possible in narrowing type casting

short to byte, short to char

short input = 65 ;
byte b = (byte) input ;
char c = (char) input ; //

char to byte, char to short

char input = 65 ;
byte b = (byte) input ;
short s = (short) input ;

int to byte, int to short, int to char

int input = 12 ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input

long to byte, long to short, long to char, long to int

long input = 12 ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;

float to byte, float to short, float to char, float to int, float to long

float input = 12.0f ;


byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;

double to byte, double to short, double to char, double to int, double to long, double to float

double input = 65.25 ;


byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;
long l = (long) input ;
float f = (float) input ;

Example : double ---> long, double ---> int

public class NarrowingTypeCastingExample


{
public static void main(String args[])
{
double d = 166.66;

//converting double data type into long data type


long l = (long)d;

//converting long data type into int data type


int i = (int)l;
System.out.println("Before conversion: "+d);

//fractional part lost


System.out.println("After conversion into long type: "+l);

//fractional part lost


System.out.println("After conversion into int type: "+i);
}
}

Output :
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

Example : double to float , char to int

public class HelloWorld{


public static void main(String []args){
// Cast double to float
double num = 10.51;
float res = (float) num;
System.out.println("double casted to float -> "+res);

// Cast char to int


char ch = 'z';
int number = (int) ch;
System.out.println("char casted to int -> "+number);
}
}

Output:

double casted to float -> 10.51


char casted to int -> 122
Example : float to short , float to byte, float to char, float to int

public class TypeCasting {

public static void main(String[] args)


{
float input = 65.0f ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;
System.out.printIn("Examples of Narrowing primitive Type casting...!!");
System.out.printIn("float to short : "+b);
System.out.printIn("float to byte : "+s);
System.out.printIn("float to char : "+c);
System.out.printIn("float to int : "+i);

}
}

Output :

float to short: 65
float to byte: 65
float to char: A
float to int: 65

Type Casting Between Object Reference

Type casting between object references in Java involves converting an object of one type
into another. This process is essential when dealing with inheritance and interfaces in Java. Type
casting between object references can be categorized into two types:

Upcasting Downcasting
Upcasting

Converting a subclass reference to a superclass reference. This type of casting is always safe
and implicit (automatic). Upcasting is generally used when you wish to treat a subclass object as an
instance of its superclass, which is usually done to take advantage of polymorphism.

class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Bark");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = dog; // Upcasting: Dog to Animal
animal.makeSound();
}
}

Output : Bark

Downcasting

It is the method of converting a superclass reference back to a subclass reference. This type
of casting must be done explicitly and can be unsafe, potentially leading to a ClassCastException at
runtime. Downcasting is used when you need to access subclass-specific methods or fields that are
not available in the superclass.
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Bark");
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog) animal; // Downcasting
dog.bark();
}
}

Output : Bark

Note: To avoid 'ClassCastException', it's a good practice to check the type before downcasting
using the 'instanceof' operator.

class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Bark");
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting

if (animal instanceof Dog) {


Dog dog = (Dog) animal; // Safe downcasting
dog.bark();
} else {
System.out.println("Not a Dog");
}
}
}
Output : Bark

You might also like