Type Casting

 Core java



Type Casting


Primitive


implicit                        Explicit

lower -> higher            higher -> lower

byte -> int                    int -> byte


reference

implicit                        Explicit

child -> parent            parent -> child


Implicit type casting example:->


 public class ImplicitCast {

     public static void main(String[] args) {
 
	 byte b = 100;

	 int i = b;

 	System.out.println(i);

 	long l = i;

 	char ch ='A';

 	int x = ch;

 	System.out.println(x);

     }

}
  

Output:-

100

65

Explicit type casting example:->

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

     int i = 100;

     byte b = (byte) i;

     int x = 97;

     char ch = (char) x;

     System.out.println(ch);

     int y = 130;

     byte z=(byte)y;

     System.out.println(z);

     int m = 612;

     byte n = (byte)m;

     char o = (char)n;

     System.out.println(o);
 }
 
}


Output:-

a

-126

d

Type Casting

1. Type Casting happens automatically when we convert a higher data type to a lower data type

a. true

b. false

Ans:- b.

2. Which of the following data type holds true and false values

a. int 

b. double

c. String

d. boolean

Ans:- d.

3. To assign a byte to an int type we should use explicit typecasting

a. true

b. false

Ans:- b.

4. Which of the following is not an integer type

a. int 

b. double

c. long

d. byte

Ans:- b.

5. A float type should be explicitly cast to a double type

a. true

b. false

Ans:- b.

6. We can use keywords for identifier names?

a. true

b. false

Ans:- b.


Static Members and Non-Static Members



Comments