Learn / Programming / Java / Variables and Types

Java · Lesson 2 of 6

Variables and Types

Primitives, Strings, final, and basic operators.

  • Beginner
  • 14 min read
  • 3 objectives

Before this lessonLesson 1: Hello, Java

What you will learn

  • Declare typed variables
  • Use String concatenation
  • Know int vs long vs double

In Java you must declare the type of every variable, and the compiler enforces it. That feels strict compared with Python, but it catches a whole class of mistakes before the program ever runs. A variable declaration has the shape type name = value;.

Every variable has a declared type

In Java you must say what kind of value a variable holds when you create it: int count = 5;. The compiler then refuses anything that does not fit, so you cannot accidentally store text in a number. This feels like extra typing at first, but it turns a whole class of runtime surprises into immediate, clear compile errors. Think of variables as labelled containers with a fixed shape: an int box holds whole numbers, a String box holds text.

Primitive types

Primitives hold raw values directly and are very fast. The ones you will use most:

  • int: 32-bit whole numbers (about ±2.1 billion). long is the 64-bit version.
  • double: 64-bit decimals. float is the less precise 32-bit version.
  • boolean: true or false.
  • char: a single character in single quotes, like 'A'.
int count = 3;
long population = 8_000_000_000L;
double price = 9.99;
boolean active = true;
char grade = 'A';
String name = "stackcone";

System.out.println(name + " has " + count + " items");
Output
stackcone has 3 items

String is not a primitive but a class, written with a capital letter. Strings are immutable: methods like toUpperCase() return a new string instead of changing the original.

Type inference with var

Since Java 10 you can write var for local variables and let the compiler work out the type from the right-hand side. The variable is still statically typed; you are only saving keystrokes.

var total = 42;          // int
var label = "Total";      // String
System.out.println(label + ": " + total);

Casting and integer division

Converting a wider type to a narrower one requires an explicit cast. Beware that dividing two int values gives an int, discarding the fraction.

double d = 9.7;
int truncated = (int) d;      // 9, not rounded

System.out.println(7 / 2);       // 3
System.out.println(7 / 2.0);     // 3.5
System.out.println(truncated);
Output
3
3.5
9

Comparing strings

Use .equals() to compare string contents. The == operator compares whether two references point at the very same object, which is almost never what you want for text.

String a = new String("java");
String b = "java";
System.out.println(a == b);       // false (different objects)
System.out.println(a.equals(b));  // true

The everyday types side by side

public class Main {
    public static void main(String[] args) {
        int age = 28;
        long population = 8_000_000_000L;
        double price = 19.99;
        boolean active = true;
        char grade = 'A';
        String name = "Ada";

        System.out.println(name + " is " + age + ", grade " + grade);
        System.out.println(price * 2);
        System.out.println(population);
        System.out.println(active);
    }
}
Output
Ada is 28, grade A
39.98
8000000000
true

Whole-number division surprises everyone once

public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);          // int / int = int
        System.out.println(7 / 2.0);        // one double makes it double
        System.out.println(7 % 2);          // remainder
        int total = 7, people = 2;
        double each = (double) total / people;
        System.out.println(each);
    }
}
Output
3
3.5
1
3.5

When both operands are int, Java throws away the fraction. Convert one side to double (with a cast) before dividing when you want a decimal answer.

Comparing text: equals, not ==

For objects such as String, == asks "are these the very same object in memory?", not "do they contain the same text?". Always use .equals().

public class Main {
    public static void main(String[] args) {
        String a = "hello";
        String b = new String("hello");
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println("Java".equalsIgnoreCase("JAVA"));
    }
}
Output
false
true
true

Useful String methods

public class Main {
    public static void main(String[] args) {
        String s = "  Hello, World  ";
        System.out.println(s.trim());
        System.out.println(s.trim().toUpperCase());
        System.out.println(s.trim().length());
        System.out.println(s.contains("World"));
        System.out.println(s.trim().substring(0, 5));
        System.out.println(String.join("-", "a", "b", "c"));
    }
}
Output
Hello, World
HELLO, WORLD
12
true
Hello
a-b-c

Key takeaways

  • Declare every variable with a type: int, double, boolean, char, String.
  • Integer division drops the fraction; cast to double for decimals.
  • Compare strings with .equals(), never ==.
  • The compiler catches type mismatches before your program runs.
// Write your solution here
Up next · Lesson 3Control Flowif/else, for, while, and enhanced for-each loops.