Java Tutorial

Java Variables

A variable has a type, a name, and a value — and in Java the type comes first and stays fixed. Declare int count = 3; and count is an integer for life.

Declare the type first

A variable is a named box in memory. Java is statically typed: you state the type before the name, and the compiler holds you to it. This is the opposite of Python, where a name simply appears when you assign to it. The upside is that whole classes of mistakes are caught before the program ever runs.

Example

public class Main {
  public static void main(String[] args) {
    int count = 3;
    double price = 9.5;
    String name = "Latte";
    System.out.println(count);
    System.out.println(price);
    System.out.println(name);
  }
}

int is the type, count is the name, 3 is the value, and the semicolon ends the statement. Every statement in Java ends with a semicolon.

Assignment changes the value

After a variable exists, = stores a new value of a compatible type. You can declare a variable without a value and assign later — but you must assign before you read it, or javac refuses to compile with a "variable might not have been initialized" error.

Example

public class Main {
  public static void main(String[] args) {
    int score = 0;
    score = 10;
    score = score + 5;
    System.out.println(score);   // 15
  }
}

A local variable has no default value. Reading one before you assign it is a compile error, not a silent zero — Java is protecting you from a classic bug.

The type stays put

Once a name is an int, it is an int forever. You cannot later store text in it. This is where Java and Python part ways — the compiler rejects the mismatch instead of discovering it at runtime.

Example — this does not compile

int count = 3;
count = "three";   // error: incompatible types: String cannot be converted to int

Let the compiler infer the type with var

Since Java 10 you can write var for a local variable and let the compiler work out the type from the value on the right. The variable is still strongly typed — var is shorthand, not "any type".

Example

public class Main {
  public static void main(String[] args) {
    var count = 3;          // inferred as int
    var price = 9.5;        // inferred as double
    var name = "Latte";     // inferred as String
    System.out.println(count + " " + price + " " + name);
  }
}

var only works where the type is obvious from the value, and only for local variables — not for fields or method parameters. Use it to cut noise (var list = new ArrayList<String>();), not to hide what a value is.

Naming: rules and convention

Names must start with a letter, $, or _, then may contain letters and digits. They are case-sensitive, and keywords like int or class are off limits. Beyond the rules, Java has a strong convention: camelCase for variables.

KindConventionExample
Variable / methodcamelCaseitemCount, totalPrice
Constant (static final)UPPER_SNAKE_CASEMAX_USERS
ClassPascalCaseShoppingCart

Java convention is itemCount, not item_count. The code compiles either way, but snake_case reads as "not written by a Java programmer" and will stand out in review.

Constants: final

Mark a variable final when it must never change after its first assignment. Try to reassign it and the compiler stops you — useful for values like tax rates or limits that should stay fixed.

Example

public class Main {
  public static void main(String[] args) {
    final double TAX_RATE = 0.2;
    double price = 50.0;
    System.out.println(price * (1 + TAX_RATE));   // 60.0
    // TAX_RATE = 0.25;   // error: cannot assign a value to final variable
  }
}

Try It Yourself

Exercise: Declare an int for a number of tickets and a double for the price each, then print the total cost. Which one holds the fraction?

Show solution
int tickets = 3;
double priceEach = 12.5;
double total = tickets * priceEach;
System.out.println(total);   // 37.5

The double holds the fraction. Multiplying an int by a double promotes the result to double, so total keeps the .5.

Key Takeaways

  • Declare the type before the name; the type is fixed for the variable's life.
  • Local variables must be assigned before they are read — the compiler enforces it.
  • var infers the type of a local variable but keeps it strongly typed.
  • Use camelCase for variables and final for values that must not change.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Chemistry

Named sample mass

A mass without a name is a number on a scrap of paper. int and double give that number a type so later lines can reuse it.

m in grams

Example

public class Main {
  public static void main(String[] args) {
    double massG = 12.4;
    System.out.println("m = " + massG + " g");
  }
}

FAQ: Java Variables

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java variables examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java variables in this Java Java lesson (Java Variables).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.