Java Basics

A thorough walkthrough of Java's fundamental syntax: comments, data types, variables, type casting, scope, and the var keyword. Master these and every other Java concept becomes easier.

Java Comments

Comments are text in your source code that the Java compiler ignores completely. They exist for human readers: you, your teammates, or whoever maintains the code six months from now. Java supports three kinds of comments, and each serves a different purpose.

Single-line comments

A single-line comment begins with two forward slashes (//). Everything from those slashes to the end of the line is ignored by the compiler. Use these for short explanations directly above or beside a statement.

Multi-line comments

A multi-line (block) comment opens with /* and closes with */. Everything in between, including line breaks, is ignored. These are useful when you need to write a longer explanation or temporarily disable a block of code during debugging.

Javadoc comments

A Javadoc comment starts with /** and ends with */. The javadoc tool reads these comments and generates HTML documentation automatically. They appear directly above classes, methods, and fields, and support special tags like @param, @return, and @throws to document a method's contract precisely.

All Three Comment Types

Java

Single-line, multi-line, and Javadoc comments shown in context.

Statements and Expressions

An expression is a piece of code that evaluates to a value. 3 + 4, x * 2, and "Hello" + name are all expressions. A statement is a complete unit of execution. In Java, most statements end with a semicolon. A statement can contain one or more expressions, but the key distinction is that a statement does something (declares a variable, calls a method, controls flow), while an expression produces a value.

Statements and Expressions

Java

Expressions evaluate to values; statements are complete actions terminated by semicolons.

Whitespace and Formatting

Java is not whitespace-sensitive the way Python is. The compiler strips out all extra spaces, blank lines, and tabs when it parses your source file. That means the following two snippets compile to identical bytecode:

What whitespace means in Java

Java's rules on whitespace are simple but worth knowing explicitly.

  • Between tokens:At least one space is required to separate keywords, identifiers, and literals (e.g., int x not intx). Additional spaces are optional.
  • Inside string literals:Whitespace inside double quotes is significant. "Hello World" and "HelloWorld" are different strings.
  • Line endings:Java does not care where you put line breaks. A statement can span multiple lines as long as it ends with a semicolon.
  • Indentation convention:The standard Java style uses 4 spaces per indentation level. Most teams use a formatter tool (e.g., Google Java Format) to enforce this automatically.

Whitespace Is Flexible

Java

Both styles below compile to the same bytecode. The formatted version is obviously easier to read.

Case Sensitivity

Java is fully case-sensitive. This means System, system, and SYSTEM are three entirely distinct identifiers. The compiler treats them as completely different names with no relation to each other. This applies to everything: class names, method names, variable names, and keywords.

Case sensitivity rules to memorise

Getting the capitalisation wrong produces a compiler error or, worse, a logic error that compiles but behaves incorrectly.

  • Keywords are all lowercase:int, class, if, while, return, for, void. Writing Int or Class is a compiler error.
  • Class names use PascalCase:MyClass, BankAccount, HttpClient. The file name must match exactly.
  • Method and variable names use camelCase:calculateTotal(), firstName, maxRetries.
  • Constants use SCREAMING_SNAKE_CASE:MAX_SIZE, DEFAULT_TIMEOUT, PI.
  • System.out.println is exact:system.out.println() will not compile. The S in System must be uppercase.

Java Keywords

Keywords are reserved words with a fixed meaning in the Java language. You cannot use them as identifiers for your classes, methods, or variables. Java has 67 reserved words. The complete set is listed below, grouped by category for easier reference.

Access modifiers

Control visibility of classes, methods, and fields.

  • public
  • private
  • protected

Class, object, and inheritance

Define and relate types in the object-oriented system.

  • class
  • interface
  • enum
  • record
  • extends
  • implements
  • new
  • this
  • super
  • instanceof
  • sealed
  • permits
  • non-sealed

Primitive types and type control

The eight primitive types plus void.

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean
  • void

Modifiers

Modify the behaviour of classes, methods, and fields.

  • abstract
  • final
  • static
  • native
  • synchronized
  • transient
  • volatile
  • default
  • strictfp

Control flow

Direct the execution path of your program.

  • if
  • else
  • switch
  • case
  • default
  • for
  • while
  • do
  • break
  • continue
  • return
  • yield

Exception handling

Manage runtime errors and clean-up logic.

  • try
  • catch
  • finally
  • throw
  • throws

Package and imports

Organise classes into namespaces and bring them into scope.

  • package
  • import

Other reserved words

Assorted keywords for specific purposes.

  • var:Local variable type inference (Java 10+)
  • assert:Runtime assertion for debugging
  • goto, const:Reserved but not used in Java; they produce a compiler error if written

Naming Identifiers

An identifier is any name you give to a class, method, variable, or constant in your code. Java enforces strict rules on what qualifies as a legal identifier, and the community has adopted consistent naming conventions on top of those rules. Both matter: violating the rules causes a compiler error, while violating conventions makes your code harder to read and maintain.

Identifier rules (enforced by the compiler)

These are not suggestions. Break any of these and the compiler refuses to compile your file.

  • Can contain letters (A-Z, a-z), digits (0-9), underscores (_), and dollar signs ($)
  • Cannot begin with a digit. count2 is valid; 2count is not.
  • Cannot be a reserved Java keyword (int, class, while, etc.)
  • Have no length limit, but the class file format limits names to 65535 bytes in UTF-8
  • Are case-sensitive: totalCost and TotalCost are two different identifiers

Naming conventions (enforced by the community)

These are strong conventions followed by virtually every Java developer and enforced by static analysis tools.

  • Classes:PascalCase. CustomerOrder, DatabaseConnection, HttpClient.
  • Methods and variables:camelCase. calculateTotal(), firstName, maxRetries.
  • Constants:SCREAMING_SNAKE_CASE. MAX_SIZE, DEFAULT_TIMEOUT, PI.
  • Packages:all lowercase, usually reverse domain name. com.example.project.
  • Type parameters (generics):Single uppercase letter. T, E, K, V.

Best practices for choosing names

Good names communicate intent without requiring a comment to explain them.

  • Be descriptive: numberOfStudents is better than n or ns
  • Avoid abbreviations unless they are universally known (id, url, html are fine; crec for currentRecord is not)
  • Keep method names as verbs or verb phrases: calculateTax(), sendEmail(), isValid()
  • Boolean variables should read as a yes/no question: isActive, hasPermission, isEmpty
  • Do not prefix variable types into the name: avoid strName or intCount (this is an old C convention that does not belong in Java)

Identifiers in Practice

Java

Legal and conventional identifier usage across classes, methods, variables, and constants.

Primitive Data Types

Java has eight primitive types. These are the fundamental building blocks of all data in the language. Unlike objects, primitive values are stored directly in memory at the variable's location (on the stack for local variables), which makes them fast and memory-efficient. Each primitive has a fixed size and a well-defined range, regardless of the operating system or hardware your program runs on.

Integer types

Four types for whole numbers, differing only in their size and therefore their maximum value.

  • byte:8 bits. Range: -128 to 127. Use when memory is critically tight, such as when processing binary file data.
  • short:16 bits. Range: -32,768 to 32,767. Rarely used directly; exists mostly for compatibility with legacy protocols.
  • int:32 bits. Range: -2,147,483,648 to 2,147,483,647. The default integer type. Use this for most whole-number calculations.
  • long:64 bits. Range: -9.2 x 10^18 to 9.2 x 10^18. Use when int would overflow. Literals must carry the L suffix: 9_000_000_000L.

Floating-point types

Two types for numbers with decimal components, following the IEEE 754 standard.

  • float:32 bits, roughly 6-7 significant decimal digits of precision. Literals require the f suffix: 3.14f. Use only when memory saving on large arrays justifies the precision loss.
  • double:64 bits, roughly 15-16 significant decimal digits. The default for decimal numbers. All floating-point literals without a suffix are doubles: 3.14 is a double.

Character and boolean types

The remaining two primitives cover text characters and logical conditions.

  • char:16 bits. Stores a single Unicode character (UTF-16 code unit). Literals use single quotes: 'A', '\n', '\u0041'. Range: 0 to 65,535 (unsigned).
  • boolean:Stores either true or false. No numeric equivalent exists in Java. Default value for instance fields: false.

All Eight Primitive Types

Java

Declaration, initialisation, and output for every primitive type.

Non-Primitive Data Types (Overview)

Non-primitive types (also called reference types) are any type that is not one of the eight primitives. A variable of a reference type does not store the data itself; it stores a reference (a memory address) to an object on the heap. The object contains the actual data. This distinction has several practical consequences: reference variables can be null, they can point to the same object, and they use more memory than primitive variables because of object header overhead.

Common non-primitive types

You will work with these constantly throughout any Java project.

  • String:An immutable sequence of characters. The most commonly used class in Java. Unlike char, String is a class, not a primitive.
  • Arrays:Fixed-size ordered collections of elements, all of the same type. Syntax: int[] numbers = new int[5];
  • Classes:Any class you define (e.g., Customer, Order) is a reference type. Variables of class type hold references to objects.
  • Interfaces:Abstract types that define contracts. Variables declared as an interface type can hold any object that implements that interface.
  • Collections (List, Map, Set):Part of the java.util package. Dynamic, resizable data structures for real-world programming.

Non-Primitive Types in Use

Java

String, array, and a custom class used as reference types.

Type Casting (Widening and Narrowing)

Type casting is converting a value from one data type to another. Java distinguishes between two kinds: widening and narrowing. The distinction matters because one is safe and automatic while the other carries risk and requires explicit action from the programmer.

Widening conversion (implicit)

Widening moves from a smaller type to a larger one. There is no risk of data loss, so Java performs this conversion automatically without any syntax from you. The hierarchy from smallest to largest is: byte > short > int > long > float > double.

  • int to long: no data loss, Java converts automatically
  • int to double: no data loss, Java converts automatically
  • float to double: more precision available, always safe

Narrowing conversion (explicit)

Narrowing moves from a larger type to a smaller one. Data loss is possible: a double with a fractional part loses that fraction when cast to int; a long whose value exceeds int's range loses the high-order bits. Java forces you to write the cast explicitly so you must consciously accept the risk.

  • double to int: fractional part is truncated, not rounded
  • long to int: high-order 32 bits are discarded if the value does not fit
  • double to float: precision is reduced to 6-7 significant digits

Widening and Narrowing Casting

Java

Automatic widening versus explicit narrowing, with observable precision loss.

Variable Declaration and Initialisation

A variable is a named storage location in memory. In Java, every variable must be declared before it can be used, and every declaration includes a type. Declaration reserves the memory slot and associates a name with it. Initialisation assigns a value to that slot. You can do both in one line or separately, but you must initialise a local variable before reading it or the compiler refuses to compile.

Declaration, initialisation, and assignment

Three distinct operations that are often performed together.

  • Declaration:int count;, reserves space, no value yet. Instance variables get default values; local variables do not.
  • Initialisation:count = 0;, first assignment of a value.
  • Declaration + initialisation:int count = 0;, the most common form.

Variable Declaration and Initialisation

Java

Declaring separately, initialising later, and the all-in-one form.

Multiple Variable Declaration

Java allows you to declare multiple variables of the same type in a single statement, separated by commas. This can reduce verbosity, but the accepted practice is to keep it on one line only when the variables are closely related. Declaring unrelated variables together makes code harder to read and should be avoided.

Multiple Variables on One Line

Java

Legal syntax and a note on when it actually helps versus when it hurts readability.

Constants (final Keyword)

A constant is a variable whose value cannot be changed after it has been assigned. In Java, you create a constant by adding the final keyword to a variable declaration. Once a final variable has been assigned, any attempt to reassign it produces a compiler error. For class-level constants, you also add static so the value is shared across all instances rather than duplicated per object.

Why constants matter

Constants remove magic numbers from your code and create a single source of truth.

  • A magic number like 0.08 scattered across a tax-calculation codebase is a maintenance nightmare. Change it to final double TAX_RATE = 0.08 defined once, and you update it in exactly one place.
  • The compiler prevents accidental reassignment. If a bug tries to change TAX_RATE, it fails to compile rather than silently producing wrong numbers.
  • Constants communicate intent: a reader who sees MAX_RETRIES immediately understands this is an upper bound, not an arbitrary number.

Using final Constants

Java

Class-level static constants and local final variables.

Literals

A literal is a value written directly in the source code. When you write int x = 42, the 42 is an integer literal. Java recognises five categories of literals, and each has specific syntax rules.

Integer literals

Integer literals can be written in four bases, and underscores can be inserted anywhere for readability (Java 7+).

  • Decimal (base 10):42, 1_000_000 (underscores for readability)
  • Hexadecimal (base 16):0xFF, 0x1A3F (prefix 0x or 0X)
  • Octal (base 8):077 (prefix 0, easy to confuse, use with care)
  • Binary (base 2):0b1010 (prefix 0b or 0B, Java 7+)
  • Long literal:Append L or l. Use uppercase L to avoid confusion with digit 1: 9_000_000_000L

Floating-point literals

All decimal numbers without a suffix are doubles by default.

  • double literal:3.14, 2.5e10 (scientific notation), 1.0 (always include a decimal point)
  • float literal:Append f or F: 3.14f. Without it, 3.14 is a double and assigning it to a float narrows it.

Character and String literals

Characters use single quotes; strings use double quotes.

  • char literal:'A', 'z', '7', '\n' (newline), '\t' (tab), '\'' (escaped single quote), '\\' (backslash)
  • String literal:"Hello", "Java 21", "" (empty string). Strings are objects, not primitives, but their literals look similar to chars.

Boolean literals

The only two boolean literals are the keywords true and false, both lowercase. There is no numeric equivalent in Java: you cannot write if (1) or if (0) as you can in C.

All Literal Types

Java

Integer, float, char, String, and boolean literals with their syntax forms.

Scope of Variables

The scope of a variable is the region of the code where that variable is accessible. In Java, a variable exists from the point of its declaration to the closing brace of the block that contains it. Java has three main scopes: local, instance, and class. Understanding scope prevents bugs where you accidentally access a variable from the wrong context.

Local variables

Declared inside a method, constructor, or block. They exist only for the lifetime of that block. They have no default value: you must initialise them before reading them or the compiler will refuse to compile.

  • Declared inside {}, accessible only within that same {}
  • Not accessible from other methods or classes
  • Destroyed when the method returns or the block exits
  • No default value: the compiler will flag an unread uninitialised local

Instance variables (fields)

Declared inside a class but outside any method. Each instance (object) of the class gets its own copy. Java assigns default values: 0 for numeric types, false for boolean, null for reference types.

  • Accessible through the object reference (e.g., customer.name)
  • Accessible directly within any non-static method of the same class
  • Lifetime is tied to the object; garbage collected when no references remain
  • Default values: int 0, double 0.0, boolean false, reference null

Class variables (static fields)

Declared with the static keyword at the class level. There is exactly one copy shared across all instances. Accessed through the class name (e.g., Counter.total) or, less preferably, through an instance.

  • Shared across all objects of the class
  • Exist for the lifetime of the program (or until the class is unloaded)
  • Typically used for constants (static final) or counters shared across all instances
  • Default values are the same as instance variables

Variable Scope Demonstrated

Java

Local, instance, and class (static) variables in the same program.

The var Keyword (Java 10+)

Java 10 introduced var for local variable type inference. When you use var, the compiler infers the type from the initialiser expression on the right-hand side. This does not make Java dynamically typed. The variable still has a fixed, static type determined at compile time. You simply do not write that type explicitly.

Rules and limitations of var

var is convenient but comes with restrictions by design.

  • var can only be used for local variables: not for fields, method parameters, or return types
  • The variable must be initialised on the same line. var x; is a compiler error.
  • You cannot initialise var with null alone because the compiler cannot infer a type from null
  • var is not a keyword in the traditional sense: it is a reserved type name, so you can still name a variable var (though you should not)

When to use var

var genuinely helps when the type is obvious from context and verbose to write.

  • Good use:var list = new ArrayList();, the type ArrayList is visible on the right.
  • Good use:Iterator patterns in for-each loops for complex generic types.
  • Avoid when:The type is ambiguous or the right-hand side is a method call whose return type is not obvious from its name.
  • Avoid when:It reduces clarity: var x = getValue(); forces the reader to look up what getValue() returns.

var for Local Type Inference

Java

The compiler infers the type from the right-hand side. The variable is still statically typed.

Quiz - Test Your Knowledge

Ten questions covering comments, data types, type casting, variables, scope, and the var keyword. Read each option carefully before selecting your answer.

Knowledge Check

1. Which of the following is the correct syntax for a single-line comment in Java?

2. Which keyword is used to declare a constant in Java?

3. What is the size of a Java int in memory?

4. Which of the following is an example of widening type casting?

5. What is the default value of a boolean instance variable in Java?

6. Which Java version introduced the var keyword for local variable type inference?

7. Which primitive type would you use to store the value 3.14 with high precision?

8. Which of the following is NOT a valid Java identifier?

9. A variable declared inside a method is called a:

10. What does a Javadoc comment start with?