Type Casting (Part 6)
Java Type Casting
Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
1. Widening Casting
Widening casting also called as Implicit Casting is done automatically when passing a smaller size type to a larger size type:
Eg:-
public class MyClass {
public static void main(String[] args) {
int myInt = 10;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);
}
}
Output:-
10
10.0
2.Narrowing Casting
Narrowing casting also called as Explicit Casting must be done manually by placing the type in parentheses in front of the value:
eg:-
public class MyClass {
public static void main(String[] args) {
double myDouble = 10.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
}
}
Output:-
10.78
10
Parse( )
Parse( ) is also used to convert a data-type to another.
1. ParseInt( ) is used to convert a String to an integer.
( You will learn about strings in following tutorials , for now just understand that string is used to store text )
2. ParseDouble( ) is used to convert a String to double.
Eg:-
public class
MyClass
{ public static void main(String[] args) { String
str
= "
123
"; int
num
= Integer.parseInt(
str
); double
num1
= Double.parseDouble(
str
); System.out.println("
String in form of int:
" +
num
); System.out.println("
String in form of double:
" +
num1
); } }
Output:-
String in form of int: 123
String in form of double: 123.0