Logo

Learning Java

Start Date: 28-Mar-2020
End Date: 27-April-2020(expected)


Casting

Code Output

	package lectures;

	public class Casting {

		public static void main(String[] args) {
			System.out.println("Type Casting in Java");
			
			int myMinIntValue = Integer.MIN_VALUE;
			
			int myTotal = (myMinIntValue / 2);
			
			//trying same with byte
			byte myMinByteValue = Byte.MIN_VALUE;
			byte myNewByteValue = (byte) (myMinByteValue / 2);
			//showing error "Type mismatch: cannot convert from int to byte"
			
			short myMinShortValue = Short.MIN_VALUE;
			short myNewShortValue = (short)(myMinShortValue /2);
		}

	}
		

Type Casting in Java
		

Casting means to treat or convert a number from one type to another. We put the type we want the number to be in parenthesis like below:

(byte)(myMinByteValue/2);

Other languages have casting, this is not just a Java thing.