Computer Science, asked by Harshi666, 1 year ago

Explain the term "type casting" with reference to java.


Harshi666: How was ur day??
Harshi666: why so??
Harshi666: mine was as usual...
Harshi666: oh

Answers

Answered by HarikaIndugu
3
Type Casting

Assigning a value of one type to a variable of another type is known as Type Casting.

Example :

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

In Java, type casting is classified into two types,

Widening Casting(Implicit)



Narrowing Casting(Explicitly done)



Widening or Automatic type converion

Automatic Type casting take place when,

the two types are compatiblethe target type is larger than the source type

Example :

public class Test { public static void main(String[] args) { int i = 100; long l = i; //no explicit type casting required float f = l; //no explicit type casting required System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); } }

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) { double d = 100.04; long l = (long)d; //explicit type casting required int i = (int)l; //explicit type casting required System.out.println("Double value "+d); System.out.println("Long value "+l); System.out.println("Int value "+i); } }

Double value 100.04 Long value 100 Int value 100


HarikaIndugu: Thanks for marking my answer as the Brainliest
Harshi666: wlcm
Answered by deepakkumar9254
3

Type Conversion/ Casting :-

Conversion of one data type into another data type is called Type Casting.

Type :-

There are two types of type casting.

1. Implicit Casting (Automatic/ Widening)

2. Explicit Casting (Narrowing)

1. Implicit Casting - Conversion of one data type into another data type automatically done by machine itself is called Implicit Casting.

e.g. int a=10;

       double b = a;

       System.out.println(b);

Output -  10.0

Here, the value of int a changes automatically by the computer into double type of value.

2. Implicit Casting - Conversion of one data type into another data type forcefully done by user is called Explicit Casting.

e.g. char x='a';

       int y = int x;

       System.out.println(y);

Output -  97

Here, the value of char x is changed by the user forcefully into int type of value and the output is the ASCII code of a (i.e. 97).

Similar questions