Логотип Workflow

Article

Fundamental Programming Structures

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.

Practice after this topic

  1. Write a program that computes average score from an array.
  2. Compare strings using == and equals and observe the difference.
  3. Replace loop concatenation with StringBuilder.

These are foundational skills for conditions, loops, collections, and OOP topics that follow.

Quiz

Check what you learned

Please login to pass quizzes.