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.

TypeHolds
intWhole numbers, about ยฑ2.1 billion
longLarger whole numbers. Write 5L
doubleDecimal numbers
booleantrue or false
charOne character, in single quotes
StringText, 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
โ† Getting started with JavaStrings โ†’