In this post we will discuss about one of the basic java interview question and question is that Can we cast an int value into byte type variable? what if the value of int is larger than byte?
Yes, we can cast but int is 32 bit long while byte is 8 bit long in java so when you cast an int to byte higher 24 bits are lost and a byte can only hold a value between -128 to 127
Let’s understand above concept using an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kkjavatutorials.client; /** * @author KKJavaTutorials *Can we cast an int value into byte type variable? what *if the value of int is larger than byte? */ public class CastIntIntoByteTest { public static void main(String[] args) { int x1 = 125; byte b1 = (byte)x1; //Explicit casting is required because we are storing int in byte System.out.println(b1); int x2 = 1250; byte b2 = (byte)x2; //Explicit casting is required because we are storing int in byte System.out.println(b2); } } |
Sample output
125
-30
You may also like:
History of Java
What are JVM, JRE and JDK in Java?
Differences between Java EE and Java SE
That’s all about Can we cast an int value into byte type variable? what if the value of int is larger than byte?
If you have any feedback or suggestion please feel free to drop in blow comment box.