THINK FIRST·CODE LATER

← Java Programming
Chapter 3 · Week 3

Java Basics: Class Structure, Variables, and Data Types

Before You Start: What You Must Be Able to Do

Before the questions, make sure you can: identify every part of a minimal Java class; declare, initialise and assign variables correctly; name the eight primitive types with their sizes and typical ranges; write integer, floating-point, character and boolean literals (including the L and f suffixes); explain why a local variable must be initialised before use while an instance variable need not; declare a named constant with final; and determine the scope of a variable from the braces that surround it.

The anatomy of a class

public class Payroll {               // 1  class heading
    public static void main(String[] args) {   // 2  method heading
        int hours = 38;              // 3  declaration with initialisation
        double rate = 21.5;          // 4
        double pay = hours * rate;   // 5  expression, assignment
        System.out.println("Pay: " + pay);     // 6  output statement
    }                                // 7  end of method body
}                                    // 8  end of class body

Line 1 names the class; the file must be Payroll.java. Line 2 is the entry point. Braces open and close each body, and each statement ends with a semicolon. Comments (//, /* */, /** */) are for the reader; they do not change execution, but readability — indentation, blank lines between logical groups, meaningful names — is part of the mark in this course.

Variables

A variable is a named location in memory with a type. Three distinct operations:

int count;            // declaration: creates the variable, no value yet
count = 0;            // assignment: stores a value
int total = 0;        // initialisation: declaration + assignment in one statement
int a = 1, b = 2, c;  // several variables of the same type in one declaration

Local variables — declared inside a method — have no default value. Reading one before assigning it is a compile-time error (variable might not have been initialized, in the compiler's words). Instance and class variables — declared inside the class but outside any method — are given defaults automatically: 0 for numeric types, '\u0000' for char, false for boolean, null for reference types.

The eight primitive types

Type Size Default Range / notes
byte 8 bits 0 −128 to 127
short 16 bits 0 −32,768 to 32,767
int 32 bits 0 about ± 2.1 billion; the default for integer literals
long 64 bits 0L very large integers; literals need the L suffix
float 32 bits 0.0f about 7 significant digits; literals need the f suffix
double 64 bits 0.0 about 15 significant digits; the default for decimal literals
char 16 bits '\u0000' one Unicode character, written in single quotes
boolean (1 bit) false only true or false; never 0 or 1

Everything else — String, arrays, Scanner, your own classes — is a reference type, and its variables hold a reference to an object, not the object itself. String is a class, written with a capital S; it is not a primitive.

Literals

int    i = 42;          long   big  = 10000000000L;   // without L: too large for int
double d = 3.14;        float  f    = 3.14f;          // without f: "possible lossy conversion"
char   c = 'A';         boolean ok  = true;           // 'A' single quotes, "A" is a String
int    hex = 0x1F;      int    bin  = 0b1010;         int million = 1_000_000;

Named constants

final double TAX_RATE = 0.06;    // assigned exactly once; cannot be reassigned
public static final int MAX_STUDENTS = 40;   // class-level constant

Convention: constants are written in upper case with underscores. Using a named constant instead of a literal sprinkled through the code is both a readability and a maintenance argument, and it is regularly examined.

Scope

The scope of a local variable runs from its declaration to the closing brace of the block that contains it. This does not compile:

if (tree.equals("pine")) {
    int height = 55;         // scope starts here
}                            // scope ends here
System.out.print(height);    // compile error: height is not visible

A local variable may also shadow a field of the same name: inside the method, the name refers to the local, and the field is reached with this.name (or the class name, for a static field). Two locals with the same name cannot coexist in overlapping scopes.

Remember
  • Local variables have no default; fields do.
  • An integer literal is an int and a decimal literal is a double unless you add L or f.
  • 'A' is a char; "A" is a String.
  • boolean holds only true or false.
  • A variable declared inside braces dies at the matching closing brace.
  • final means assign once; a final variable must be definitely assigned before it is used.
Common Pitfalls
  • int x = 3.5; does not compile — narrowing needs an explicit cast.
  • float f = 3.5; does not compile — the literal is a double.
  • Declaring a variable inside a loop body and expecting it to keep its value between iterations.
  • Using a variable outside the block in which it was declared.

Ready? Close the notes and practise.

38 questions. Predict the output before you check — that is the skill the exam measures.