Topic 3. Fundamental Programming Structures in Java

This topic covers the building blocks used in almost every Java program: program structure, comments, data types, variables, operators, strings, and arrays.

A Simple Java Program

Start with a small example and read it step by step.

public class Demo {
    public static void main(String[] args) {
        System.out.println("Start");

        int x = 10;
        int y = 5;
        int sum = x + y;

        System.out.println(sum);
    }
}

What happens:

  1. JVM calls main as the entry point.
  2. Variables x and y are created.
  3. sum is computed.
  4. Result is printed.

Comments

Comments should explain intent and constraints. Java has 3 comment types.

1. Single-line comment

// Use UTC to avoid timezone-dependent behavior
Instant now = Instant.now();

2. Multi-line comment

/*
 Legacy constraint:
 id must contain exactly 8 characters
*/
boolean valid = id.length() == 8;

3. Documentation comment (Javadoc)

/**
 * Returns price after discount.
 * @param amount original amount
 * @param percent discount in percent
 * @return final amount after discount
 */
public double applyDiscount(double amount, double percent) {
    return amount - amount * percent / 100.0;
}

Good rule:

  • Add comments when “why” is not obvious.
  • Do not comment obvious syntax.

Data Types

Java is strongly typed: every value has a type checked at compile time.

  • Primitive types: int, long, double, boolean, char.
  • Reference types: String, arrays, classes, interfaces.
int age = 20;
String name = "Alex";

age stores a value directly; name stores a reference to an object.

Variables, Assignments and Initializations

A variable is a named storage slot.

  • Initialization: first value assignment.
  • Assignment: later value update.

Variable box

int balance = 100;       // initialization
balance = balance + 50;  // assignment
System.out.println(balance);

Output:

150

Operators

Main operator groups:

  • Arithmetic: +, -, *, /, %.
  • Comparison: ==, !=, >, <, >=, <=.
  • Logical: &&, ||, !.
int age = 20;
boolean canBuy = age >= 18 && age < 65;
System.out.println(canBuy);

String

String in Java is a data type for text: user names, emails, messages, URLs, file paths, and any sequence of characters.

A string is an ordered sequence of characters. Example:

String name = "Alex";
String city = "Prague";
String message = "Hello, world!";

Most application input/output is text-based: form fields, JSON payloads, query params, logs, and error messages.

String is also immutable in Java. Once created, a specific string object cannot be changed; operations create a new string object.

What to understand early

  1. Methods like toUpperCase() return a new string.
  2. Use equals for content comparison, not ==.
  3. For repeated concatenation in loops, prefer StringBuilder.

Example 1. Immutability

String s = "java";
String upper = s.toUpperCase();

System.out.println(s);     // java
System.out.println(upper); // JAVA

Example 2. String comparison

String a = "test";
String b = new String("test");

System.out.println(a == b);      // false (reference comparison)
System.out.println(a.equals(b)); // true  (content comparison)

Example 3. Concatenation in loops

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    sb.append(i).append(" ");
}
String result = sb.toString();
System.out.println(result); // 1 2 3

Arrays

An array is a fixed-size sequence of elements of the same type.

  • Single element type.
  • Size is fixed at creation time.
  • Zero-based indexing.

Array memory

Create an array

int[] scores = {90, 75, 88};

Read an element

System.out.println(scores[1]);

Output:

75

Update an element

scores[1] = 80;
System.out.println(scores[1]);

Output:

80

Safe iteration

for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

Out-of-range access throws ArrayIndexOutOfBoundsException.

Glossary
bytecode
Platform-independent compiled code that the JVM can execute.
class
A blueprint that defines fields and methods for objects in object-oriented programming.
object
A runtime instance of a class with its own state and behavior.
method
A named block of behavior that belongs to a class or object and can be called by code.
field
A variable stored inside a class or object that represents part of its state.
constructor
A special method-like block used to create and initialize a new object.
package
A namespace that groups related Java classes and helps organize code.
interface
A contract that defines methods a class can implement without prescribing all internal details.
generics
A language feature that lets code work with types as parameters while preserving type safety.
type erasure
The Java compiler process that removes most generic type details from runtime bytecode.
collection
A data structure that stores a group of elements and provides operations over them.
list
An ordered collection where elements have positions and duplicates are allowed.
set
A collection that stores unique elements and is commonly used for membership checks.
map
A key-value data structure where each key points to a value.
queue
A collection designed for processing elements in a defined order, often first-in-first-out.
lambda
A compact function-like expression used to pass behavior as data.
functional interface
An interface with one abstract method, suitable for lambdas and method references.
stream
A Java API for processing data sequences with operations such as map, filter, and reduce.
optional
A container object that represents a value that may or may not be present.
thread
An independent path of execution inside a running program.
synchronization
Coordination that protects shared data when multiple threads access it.
heap
The runtime memory area where Java objects are allocated.
stack
The runtime memory area that stores method calls, local variables, and call frames.
garbage collector
A JVM component that automatically frees memory occupied by objects no longer reachable.
memory leak
A situation where memory remains occupied because objects are still referenced but no longer useful.