Java • Syntax and Core Types

Variable Declaration & Assignment — Declare variables with a type and assign values

Learn how Java stores and labels data using typed variables, the building blocks of every program.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Every computer program needs a way to remember information while it runs. Early computers in the 1940s and 1950s required programmers to track raw memory addresses — imagine having to remember that the number 42 lives at memory location 0x7FFF. That approach was tedious and error-prone. The invention of variables — human-readable names that stand in for memory locations — transformed programming from a low-level puzzle into a creative, expressive craft.

Languages evolved different philosophies about variables. Some, like Python and JavaScript, let you store any kind of data in any variable without declaring its type. Java took a different path: it is a statically typed language, meaning you must tell the compiler what kind of data a variable will hold before you use it. This design catches many bugs at compile time, long before your program ever runs.

1957 • FORTRAN Introduces Named Variables

IBM's FORTRAN compiler allowed programmers to use named variables instead of raw memory addresses, making code far more readable and less error-prone.

1970 • Pascal Popularizes Type Declarations

Niklaus Wirth designed Pascal with mandatory type declarations for every variable, emphasizing safety and clarity — a philosophy that influenced many later languages.

1983 • C++ Inherits C's Type System

C++ carried forward the C tradition of typed variables and added object-oriented types, creating a model that Java would later refine.

1995 • Java Launches with Strong Static Typing

James Gosling and the Sun Microsystems team released Java with a strict type system: every variable must be declared with a type before use, preventing entire classes of runtime errors.

2018 • Java 10 Adds Local Variable Type Inference

Java introduced the var keyword, allowing the compiler to infer a local variable's type from the assigned value — while still enforcing strong typing behind the scenes.

Understanding how to declare and assign variables is the foundation of writing any Java program. Before you can compute, compare, or display anything, you need to store your data somewhere. The central question this lesson addresses is: How does Java let you create named containers for data, and what rules govern their types and values?

SECTION 2

Core Principles & Definitions

A variable in Java is a named storage location in memory that holds a value of a specific type. Every variable has three essential properties: a type (what kind of data it stores), a name (how you refer to it in code), and a value (the data it currently holds). Before you can use a variable, you must declare it — telling the compiler its type and name. You then assign a value to it using the equals sign (=), which is called the assignment operator.

1

Declaration

Tells the compiler the variable's type and name. Syntax: int score;. No value is stored yet — just a labeled slot in memory.
2

Assignment

Stores a value into an already-declared variable. Syntax: score = 95;. The = operator copies the right-side value into the left-side variable.
3

Initialization

Combines declaration and assignment in one line. Syntax: int score = 95;. This is the most common pattern you will use.
4

Static Typing

Once you declare a variable as a specific type, you cannot store a different type in it. An int variable can never hold a String.
5

Naming Rules

Variable names must start with a letter, underscore, or dollar sign. They are case-sensitive, cannot be Java keywords (like class or int), and should use camelCase by convention.
✦

KEY TAKEAWAY

Think of a variable like a labeled jar in a kitchen. The type is the shape of the jar (tall for pasta, wide for cookies) — it determines what can fit inside. The name is the label you stick on the jar so you can find it later. The value is whatever you actually put inside. You can swap out the contents (reassign), but you can't stuff pasta into a cookie jar — Java's type system prevents it.

SECTION 3

Visual Explanation — Anatomy of a Variable Statement

Anatomy of a Variable Declaration & Assignmentintscore=95;TYPE(what kind of data)NAME(identifier / label)ASSIGNMENT OPERATOR(copies right side into left side)VALUE(literal data to store)SEMICOLON(ends the statement)Three Patterns:int score;Declaration onlyscore = 95;Assignment onlyint score = 95;Initialization (both)
This diagram breaks down the statement int score = 95; into its four components. The type tells the compiler what kind of data the variable holds. The name is your label for the memory location. The assignment operator copies the value into that memory slot. The semicolon marks the end of the statement.

Notice that the type always comes first, followed by the name. This order is non-negotiable in Java — writing score int = 95; would cause a compile error. When you separate declaration from assignment, you write the type only during declaration. On subsequent lines, you refer to the variable by name alone. Java also lets you declare multiple variables of the same type in one statement, like int x = 1, y = 2, z = 3;, though many style guides prefer one variable per line for readability.

SECTION 4

How It Works — Memory and the Java Type System

When you declare a variable like int score = 95;, Java performs two behind-the-scenes operations. First, it reserves a block of memory large enough to hold the specified type. An int always occupies 4 bytes (32 bits) of memory, regardless of the value stored. Second, it writes the binary representation of 95 into those 4 bytes. From that point on, whenever your code references score, the Java Virtual Machine (JVM) knows exactly where to look and how many bytes to read.

Primitive Types and Their Sizes

Java has eight primitive types — built-in types that store simple values directly in memory. Each type has a fixed size and a specific range of values it can represent. Understanding these sizes matters because choosing the wrong type can waste memory or, worse, cause values to overflow.

TypeSizeWhat It StoresExample
byte1 byteWhole numbers from −128 to 127byte age = 17;
short2 bytesWhole numbers from −32,768 to 32,767short year = 2025;
int4 bytesWhole numbers up to ≈ 2.1 billionint score = 95;
long8 bytesVery large whole numberslong pop = 8000000000L;
float4 bytesDecimal numbers (≈ 7 digits precision)float gpa = 3.8f;
double8 bytesDecimal numbers (≈ 15 digits precision)double pi = 3.14159;
char2 bytesA single Unicode characterchar grade = 'A';
boolean1 bit*true or false onlyboolean passed = true;

Java's eight primitive types. *JVM implementations typically use 1 byte for boolean.

Reference Types

Beyond primitives, Java has reference types — variables that store the memory address of an object rather than the object itself. The most common reference type you will encounter early on is String. When you write String name = "Alice";, the variable name does not contain the characters directly; it holds a reference (like a pointer) to the location in memory where "Alice" actually lives. Reference type names always start with an uppercase letter, while primitive type names are all lowercase.

⚠

Common Mistake

Java requires you to initialize local variables before using them. Writing int x; and then immediately using System.out.println(x); will cause a compile error: "variable x might not have been initialized." Always assign a value before you read from a local variable.

SECTION 5

Detailed Breakdown — Choosing the Right Type

Choosing the correct type for a variable is one of the first design decisions you make as a Java programmer. Picking a type that's too small can cause data loss; picking one that's too large wastes memory (though on modern machines this is rarely a concern for simple programs). More importantly, the type determines which operations are legal. You can divide two int values, but you cannot divide two boolean values — the compiler simply won't allow it.

Java Variable Types — Decision FlowchartWhat data do you need?Whole Number?Decimal Number?Text / Logic / Character?intMost commonlongVery largedoubleMost commonfloatLess precisionStringTextbooleantrue / falsecharSingle charQuick-Reference Examplesint age = 17;double price = 9.99;String name = "Alice";boolean enrolled = true;char initial = 'A';long worldPop = 8000000000L;Tip: Use int for most whole numbers, double for most decimals, and String for text.
This flowchart helps you choose the right type based on the kind of data you need to store. In most high school programs, you will use int, double, String, and boolean most often.

Naming Conventions in Practice

Java's naming rules are strict: variable names must begin with a letter, an underscore, or a dollar sign, and they are case-sensitive (score and Score are different variables). By convention, Java developers use camelCase for variable names — the first word is lowercase, and each subsequent word starts with an uppercase letter. For example, totalScore, playerName, and isGameOver all follow camelCase. Choosing descriptive names like studentAge instead of x makes your code dramatically easier to read and maintain.

  • ✓ Good: int numberOfStudents = 30; — descriptive and clear
  • ✓ Acceptable: int n = 30; — fine for short loops or math formulas
  • ✓ Bad: int 2ndPlace = 30; — starts with a digit, won't compile
  • ✓ Bad: int class = 5; — class is a reserved keyword

SECTION 6

Worked Example — Building a Student Grade Tracker

Let's put everything together by writing a short program that declares variables for a student's information, assigns values, and prints a summary. We will use several different types and show how each variable is declared, assigned, and used.

Student Grade Tracker Program

  1. 1

    Step 1 — Declare and initialize student info

    We start by declaring variables for the student's name, age, and grade level. Each variable is initialized on one line with the appropriate type. String studentName = "Maria"; int age = 16; int gradeLevel = 11;
    Three variables created: a String and two int values.
  2. 2

    Step 2 — Declare and initialize test scores as doubles

    We use double for test scores because they might include decimal points. double test1 = 92.5; double test2 = 88.0; double test3 = 95.75;
    Three double variables hold decimal test scores.
  3. 3

    Step 3 — Compute the average and store it in a new variable

    We declare a new double variable and assign it the computed average. The right side of the assignment operator is an expression that Java evaluates before storing the result. double average = (test1 + test2 + test3) / 3;
    The variable average now holds 92.08333... — the result of (92.5 + 88.0 + 95.75) / 3.
  4. 4

    Step 4 — Determine pass/fail using a boolean

    A boolean variable stores the result of a comparison. Here, we check if the average is at least 70. boolean passed = (average >= 70.0);
    Since 92.08 ≥ 70.0 is true, passed is assigned the value true.
  5. 5

    Step 5 — Assign a letter grade using char

    We use a char variable with single quotes to store a single character representing the letter grade. char letterGrade = 'A';
    The char variable letterGrade holds the single character 'A'.
  6. 6

    Step 6 — Print the results

    We use System.out.println() to output the values. Notice we can use the + operator to concatenate strings with variable values. System.out.println(studentName + " — Grade " + gradeLevel); System.out.println("Average: " + average); System.out.println("Passed: " + passed); System.out.println("Letter Grade: " + letterGrade);
    Output: Maria — Grade 11 Average: 92.08333333333333 Passed: true Letter Grade: A
💡

Pro Tip

You can reassign a variable at any time after declaration, as long as the new value matches the type. For example, writing letterGrade = 'B'; later in the program is perfectly valid. The old value 'A' is overwritten and lost.

SECTION 7

Common Pitfalls & Best Practices

Now that you know the syntax, let's examine the most common mistakes students make when declaring and assigning variables. Understanding these pitfalls early will save you hours of debugging.

MistakeWhat HappensFix
Using a variable before declaring itCompiler error: "cannot find symbol"Always declare the variable above the line where you first use it.
Forgetting the semicolonCompiler error on the current or next line, often confusingEvery statement in Java ends with ;.
Assigning wrong type, e.g., int x = "hello";Compiler error: "incompatible types"Match the value to the declared type, or change the type.
Re-declaring a variable in the same scopeCompiler error: "variable already defined"Use just the name (no type) for reassignment: x = 10;
Integer division surprise: int result = 7 / 2;Result is 3, not 3.5 — the decimal part is droppedUse double result = 7.0 / 2; if you need a decimal answer.
Using " for char instead of 'Compiler error: "incompatible types"Single quotes for char ('A'), double quotes for String ("A").

Common variable declaration and assignment mistakes in Java

✦

KEY TAKEAWAY

Think of Java's type system like a school supply list. If the list says you need a 3-ring binder, you can't show up with a spiral notebook and expect it to work in the same way. The compiler is like a strict teacher who checks your supplies on the first day — if the types don't match, you get sent back to fix the problem before class begins (compile time), not in the middle of a test (runtime).

SECTION 8

Connection to Advanced Concepts

Variable declaration and assignment are the entry point to much deeper topics in Java. As you progress, you will encounter concepts that build directly on what you learned today. Here is a preview of how basic variables connect to more advanced features.

What You Know NowWhat Comes NextWhy It Matters
int x = 5;final int MAX = 100; — constantsThe final keyword prevents reassignment, creating a read-only variable.
Single variables: int scoreArrays: int[] scores = new int[30];Arrays let you store many values of the same type under one name.
Primitive types: int, doubleObject types: Scanner, ArrayListObjects bundle data and behavior together, building on the same declaration syntax.
Local variables (inside a method)Instance variables (inside a class)Instance variables define an object's state and have different scope and default-value rules.
Explicit type: String s = "hi";Type inference: var s = "hi";Java 10+ lets the compiler infer the type from the assigned value, reducing boilerplate.

How today's concepts connect to future Java topics

Every Java program — from a simple calculator to a complex Android app — relies on variables to store and manipulate data. Mastering declaration and assignment now gives you a rock-solid foundation. When you encounter arrays, objects, and generics later, you will recognize the same fundamental pattern: state the type, give it a name, and assign a value.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain the difference between declaring a variable and initializing a variable. Why might you want to separate these two steps in certain situations?
Show answer
Declaring a variable means telling the compiler the variable's type and name (e.g., int count;), which reserves a memory location but does not store a specific value. Initializing means assigning a value for the first time (e.g., count = 0;). You might separate them when the value depends on a condition that hasn't been evaluated yet — for instance, you could declare int result; at the top of a method and assign different values inside an if-else block. This pattern keeps the variable accessible throughout the entire method scope.

Question 2: BASIC CALCULATION

Write Java code that declares a double variable named celsius and assigns it the value 37.0. Then declare a second double variable named fahrenheit and assign it the converted temperature using the formula F = C × 9/5 + 32. What value will fahrenheit hold?
Show answer
The code is: double celsius = 37.0; followed by double fahrenheit = celsius * 9.0 / 5 + 32;. Substituting values: 37.0 × 9.0 / 5 + 32 = 333.0 / 5 + 32 = 66.6 + 32 = 98.6. The variable fahrenheit will hold 98.6. Notice we wrote 9.0 instead of 9 to ensure the division is performed as floating-point arithmetic rather than integer division.

Question 3: INTERMEDIATE

The following code has three errors. Identify each one and explain how to fix it. int temperature = 72.5; String city = 'New York'; boolean isHot = temperature > 80
Show answer
Error 1: int temperature = 72.5; — you cannot assign a decimal value to an int. Fix by changing the type to double or rounding to 73. Error 2: String city = 'New York'; — single quotes are for char values (single characters). Strings must use double quotes: "New York". Error 3: boolean isHot = temperature > 80 — missing the semicolon at the end of the statement. Add ; at the end to fix the syntax error.

Question 4: APPLIED

You are building a simple inventory system for a school bookstore. Declare appropriate variables (with correct types) to store: the title of a book, its price, the number of copies in stock, and whether it is currently on sale. Then write one line that creates a new variable salePrice that is 20% off the original price. Show the complete code.
Show answer
A well-typed solution would be: String title = "Java Basics"; double price = 24.99; int copiesInStock = 45; boolean onSale = true; double salePrice = price * 0.80; We use String for text, double for money (since prices have decimals), int for a whole-number count, and boolean for a true/false flag. The sale price is calculated by multiplying price by 0.80 (keeping 80% of the original), yielding 19.992 — which Java stores as a double.

Question 5: CRITICAL THINKING

Consider the following code: int a = 5; int b = a; a = 10; System.out.println(b); What value is printed, and why? How does this behavior differ from what you might expect if variables were like shared labels pointing to the same sticky note? Relate your answer to Java's treatment of primitive types.
Show answer
The printed value is 5. When you write int b = a;, Java copies the current value of a (which is 5) into b. After this point, a and b are completely independent — they occupy separate memory locations. Changing a to 10 does not affect b. This is called pass-by-value behavior and applies to all primitive types in Java. If variables were like shared labels on one sticky note, changing a would also change b — but that is not how Java primitives work. This distinction becomes important when you later study reference types, where the behavior is slightly different.

SUMMARY

Lesson Summary

Summary

In Java, a variable is a named storage location with a specific type. You declare a variable by writing its type followed by its name (e.g., int score;), and you assign a value using the = operator (e.g., score = 95;). You can combine both into a single initialization statement: int score = 95;. Java's eight primitive types — byte, short, int, long, float, double, char, and boolean — store simple values directly, while reference types like String store addresses pointing to objects in memory.

Remember the core rules: every statement ends with a semicolon, the type always comes first in a declaration, and you cannot store a value of the wrong type. Use camelCase for naming, choose descriptive names, and always initialize local variables before using them. These habits will serve you well as you move on to arrays, objects, and more complex data structures.

Varsity Tutors • Java • Variable Declaration & Assignment