Variables and data types
Primitive types, String, and casting.
Java is statically typed: every variable has a type that is fixed when you declare it, and the compiler checks it before the program runs.
| Type | Holds |
|---|---|
int | Whole numbers, about ยฑ2.1 billion |
long | Larger whole numbers. Write 5L |
double | Decimal numbers |
boolean | true or false |
char | One character, in single quotes |
String | Text, in double quotes. A class, not a primitive |
Java
public class Main {
public static void main(String[] args) {
int age = 20;
double cgpa = 8.4;
boolean placed = false;
char grade = 'A';
String name = "Kavin";
System.out.println(name + " " + age + " " + cgpa + " " + grade + " " + placed);
}
}Output
Kavin 20 8.4 A false
Casting and integer division
Dividing two ints drops the decimals, which is a classic exam trap. Cast one side to double to keep them.
Java
public class Main {
public static void main(String[] args) {
int a = 7, b = 2;
System.out.println(a / b);
System.out.println((double) a / b);
System.out.println(a % b);
}
}Output
3 3.5 1