As a Java beginner, data type threw me off the window.
Now I realize how JavaScript was generous (or didn't really care what I was doing) when it comes to my "loose" programming skills.
Java has 7 primitive data types:
Byte , Short, Int, Long, Float, Double
(from most narrow to most wide)
Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and Narrowing.
Widening is when converting a lower datatype to a higher datatype.
Casting/conversion is done automatically, AKA "implicit type casting".
Datatypes have to be compatible.
When does the automatic type conversion happens?
either:
Example
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);
}
}
Output
Integer value of the given character: 67
Narrowing is the opposite of widening and in this case, type casting and conversion is not done automatically. It needs to be done by using cast operator "(datatype)". AKA "explicit type casting"
Datatypes can be incompatible.
Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}
Output
Enter an integer value:
67
Character value of the given integer: C
As you can see, in the case of narrowing, int i
got casted into (char)
.
Rules
Still really confused about the data casting, but now I am more sure about what I can do with my data and what I can't do.