Chapter 2.1: Programming

Object Oriented Programming with Java
Programming languagesCompilation and interpretationParadigmsSyntax and semantics Kinds of errorsExpressions and precedenceVariables and assignmentStatic and dynamic typing Strings and typesFrom algorithm to program
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Programming languages

Define a programming language; classify languages by abstraction level, application domain, execution model and paradigm.

How Java runs

Explain how source code is compiled by javac into bytecode and run on the JVM.

Syntax and semantics

Distinguish syntax, static semantics and semantics; recognize compile-time, run-time and logic errors.

Expressions

Evaluate an expression using operator precedence, left-to-right evaluation and integer division.

Variables and types

Declare variables, trace an assignment in two steps, and explain static vs. dynamic typing and mixed-type operations.

From algorithm to program

Tell expressions from statements, turn an algorithm into a Java program, and show why statement order matters.

Introduction

Goals of This Chapter

1Building blocksLearn the basic building blocks of a programming language: its syntax and its semantics.
2Translating a recipeUse these building blocks to turn a recipe for solving a problem into a form the computer understands: a program.
3Computational thinkingCombine decomposition, pattern recognition, abstraction and algorithm design techniques to solve a problem.
This chapter introduces the concepts shared by every programming language, with Java examples.

Programming Languages

What Is a Programming Language?

  • A programming language is a notation for expressing the computations a machine can perform: an artificial language.
  • It is used to write programs that control a machine's behavior:
    • algorithms stated clearly and precisely;
    • a means of communication between programmers.
  • It gives computers, phones and embedded devices their functionality.
  • By abstraction level: machine language and assembly are low-level; Java and Python are high-level.
  • The choice of language depends on the project's needs.
  • Examples: C, C++, Java, Python, Prolog, Haskell, Scala…
Problemdescribed in wordsdesignAlgorithmprecise stepscodeProgramcode in, e.g., JavarunMachineruns instructions

Programming Languages

General-Purpose and Domain-Specific

  • By application domain, languages are either general-purpose or domain-specific.

General-purpose

  • A broad core instruction set that supports a wide range of applications.
  • Java, C, C++, Python: desktop, web, mobile, embedded…

Domain-specific

  • Focuses on one kind of application and makes those tasks easy.
  • MATLAB: numerical computing; optimized matrix and vector operations. SQL: database queries.

MATLAB · matrix multiplication

C = A * B;   % one line

Java · same job, loops written by hand

for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        for (int k = 0; k < n; k++)
            C[i][j] += A[i][k] * B[k][j];

Programming Languages

Compiled and Interpreted Languages

By how code is executed, languages are compiled or interpreted.

Compiled language (C, C++, Go, Rust)

Source codeCompilertranslates onceMachine codeexecutable fileRun

Interpreted language (Python, JavaScript)

Source codeInterpreterread a line, run itOutput
CompiledInterpreted
How?The whole source is translated before it runs, into object / machine code.The interpreter reads the source and executes statements one by one, on the fly.
SpeedFast, optimized executionUsually slower
ErrorsMost are caught at compile timeMost surface only when that line runs

Java combines both: javac → bytecode (.class) → JVM (interpreter + JIT).

Programming Languages

Programming Paradigms

A paradigm is the basic approach taken to solve a problem; languages can attack the same problem in different ways.

ImperativeThe programmer tells the machine, step by step, how to change its state. FORTRAN, BASIC, Pascal, C…
xfyFunctionalTreats computation as the evaluation of mathematical functions and avoids changing state. Lisp, Scheme, Haskell…
factrule?LogicDescribes the logic of a computation (facts and rules), not its control flow. Prolog
objectdatamethod()Object-orientedGroups related data and methods into an object; instructions live with the state they work on. C++, Java, C#, Python…
Java is mainly object-oriented and imperative; since Java 8 it also has functional features (lambdas, streams). Languages that support several paradigms are called multi-paradigm.

Programming Languages

Same Problem: Imperative vs. Functional

Problem: find the sum of the numbers 1 to 5.

import java.util.stream.IntStream;

public class Paradigm {
    public static void main(String[] args) {
        // Imperative: change state step by step
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum = sum + i;
        }
        System.out.println("Imperative: " + sum);

        // Functional (Java 8+): say what you want
        int result = IntStream.rangeClosed(1, 5).sum();
        System.out.println("Functional: " + result);
    }
}

Output

Imperative: 15
Functional: 15
  • Imperative: sum is updated at every step; you spell out “how”.
  • Functional: “the sum of the range 1..5” is requested; no variable is updated.

Programming Languages · Step-by-step code trace

Imperative vs. Functional: Code Trace

values of i12345sum0

In the imperative version, the sum state variable starts at 0.

values of i12345sum10 + 1 = 1

i = 1: 1 <= 5 is true → sum = 0 + 1 = 1. The state changes on every pass.

values of i12345sum31 + 2 = 3

i = 2: 2 <= 5 is true → sum = 1 + 2 = 3.

values of i12345sum63 + 3 = 6

i = 3: 3 <= 5 is true → sum = 3 + 3 = 6.

values of i12345sum106 + 4 = 10

i = 4: 4 <= 5 is true → sum = 6 + 4 = 10.

values of i12345sum1510 + 5 = 15

i = 5: 5 <= 5 is true → sum = 10 + 5 = 15.

values of i12345sum15

i becomes 6: 6 <= 5 is false → the loop ends.

values of i12345sum15

The result is printed: five passes add up to 15.

values of i12345rangeClosed(1, 5).sum() → 15

Functional: rangeClosed(1, 5) generates the numbers 1…5, sum() adds them up. No variable is updated step by step.

values of i12345rangeClosed(1, 5).sum() → 15

Both give the same result; the difference is whether you write how to do it or what you want.

int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum = sum + i;
}
System.out.println("Imperative: " + sum);

int result = IntStream.rangeClosed(1, 5).sum();
System.out.println("Functional: " + result);

Programming Languages

Logic and Object-Oriented

Logic · Prolog

% facts
parent(ali, ayse).
parent(ayse, can).
% rule
grandparent(X, Z) :- parent(X, Y),
                     parent(Y, Z).
% query
?- grandparent(ali, can).
true.

Only facts and a rule are given; Prolog itself decides how to answer the query (the search order).

A Rectangle object holds both data (width, height) and the method (area()) that works on that data.

Object-oriented · Java

public class Rectangle {
    double width, height;          // data (state)

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    double area() {          // behavior
        return width * height;
    }

    public static void main(String[] args) {
        Rectangle d = new Rectangle(3, 4);
        System.out.println("Area: " + d.area());
    }
}

Output

Area: 12.0

Programming Languages · Step-by-step code trace

Object-Oriented: Code Trace

StackHeapmaind—

main starts. The stack holds a main frame; d does not refer to an object yet.

StackHeapmaind—Rectangle(…)this = •width = 3.0height = 4.0Rectanglewidth = 0.0height = 0.0

new allocates the object on the heap; fields start at the default 0.0. The constructor is called: 3 and 4 are widened to double.

StackHeapmaind—Rectangle(…)this = •width = 3.0height = 4.0Rectanglewidth = 3.0height = 0.0

this.width is the object's field; the width on the right is the parameter. The field becomes 3.0.

StackHeapmaind—Rectangle(…)this = •width = 3.0height = 4.0Rectanglewidth = 3.0height = 4.0

height becomes 4.0. The constructor returns and its frame is popped.

StackHeapmaind•Rectanglewidth = 3.0height = 4.0

new evaluates to the object's reference; d now refers to this object.

StackHeapmaind•area()this = •Rectanglewidth = 3.0height = 4.0

d.area(): this and d refer to the same object. width * height = 3.0 × 4.0 = 12.0 is returned.

StackHeapmaind•Rectanglewidth = 3.0height = 4.0

The returned 12.0 is concatenated with the string: Area: 12.0. Data (width, height) and behavior (area) live in the same object.

public class Rectangle {
    double width, height;
    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    double area() {
        return width * height;
    }
    public static void main(String[] args) {
        Rectangle d = new Rectangle(3, 4);
        System.out.println("Area: " + d.area());
    }
}

Syntax and Semantics

Basic Elements and Syntax

Programming languages and natural languages have a lot in common.

English (natural language)Java (programming language)
Basic elementswords, punctuation marksnumbers, strings, simple operators (+ - * /), keywords
Syntax“cat dog boy”: valid words but no sentence structure → invaliddefines which sequences of characters and symbols are well formed

Syntax defines the rules of a language and affects how readable it is. The compiler rejects any sequence of symbols that breaks them:

✓ Valid

int x = 5;

✗ Invalid: wrong order

int = x 5;
Bad.java:3: error: not a statement
        int = x 5;
        ^
...
4 errors

Syntax and Semantics

Static Semantics

  • Static semantics: checks whether a syntactically valid expression is meaningful, before the program runs.
  • English: “I are big” matches the pattern <noun> <verb> <noun>, but “I” is singular and “are” plural → invalid.
  • Java: <value> <operator> <value> is a valid pattern, but dividing a number by a string makes no sense → static semantic error.
double result = 2.3 / "abc";
error: bad operand types for binary operator '/'
  first type:  double
  second type: String
int x = "five";
error: incompatible types:
  String cannot be converted to int
Source codeBad.javaSyntaxint = x 5;Static semanticsint x = "five";Run (semantics)(a + b) / 2
Java is statically typed: the compiler checks the operand types of every operator, so these errors are caught before the program ever runs.

Syntax and Semantics

Semantics

  • Semantics: what a syntactically valid expression means.
  • Natural languages can be ambiguous: “They saw the man with the telescope.”
    • They used the telescope, or
    • the man had the telescope.
  • In a programming language every valid expression has exactly one meaning.
  • But that meaning may not be what the programmer intended: a wrong operation gives an unexpected result.
int a = 7, b = 8;
int avg = (a + b) / 2;
System.out.println(avg);       // expected 7.5
System.out.println(a + b / 2);      // precedence
System.out.println((a + b) / 2.0);  // correct

Output

7
11
7.5

The average of 7 and 8 is 7.5. The first line does integer division; in the second line / is applied before +. The compiler sees no error here.

Syntax and Semantics · Step-by-step code trace

Semantic Error: Code Trace

/+2a7b8

a = 7, b = 8; both are int. The tree shows the structure of (a + b) / 2.

/+152a7b8

Parentheses first: a + b = 15 (int).

/7+152a7b8

15 / 2: both operands are int → integer division, so the fraction is dropped: 7.

/7+152a7b8

7 is printed. The program ran without errors, but the meaning is not what we wanted.

+a7/4b82

No parentheses: / has higher precedence than +. First b / 2 = 4.

+11a7/4b82

Then 7 + 4 = 11 is printed.

/7.5+152.0a7b8

2.0 is a double: 15 is widened to double too, 15 / 2.0 = 7.5.

int a = 7, b = 8;
int avg = (a + b) / 2;
System.out.println(avg);       // not 7.5
System.out.println(a + b / 2);      // precedence
System.out.println((a + b) / 2.0);  // correct

Syntax and Semantics

What Can Go Wrong?

Error typeDetected when?Java exampleSymptom
Syntaxcompile time (compiler)System.out.println("Hello")';' expected
Static semanticscompile time (type check)int x = "five";incompatible types
Run-timewhile the program runsa / b (when b is zero)crash: ArithmeticException
Logicnot by the compiler; only by testing(a + b) / 2 for an averagewrong result, infinite loop
  • Syntax errors break clearly defined rules, like spelling mistakes; the computer finds them easily.
  • Static semantic errors are checked by language-specific rules before the program runs. In languages with weak checks, the errors that slip through make program behavior unpredictable.
  • Even a program that is flawless in syntax and static semantics may not do what you expect: it can crash, loop forever, or give the wrong result.

Syntax and Semantics

Reading Error Messages

Compile error

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}
Hello.java:3: error: ';' expected
        System.out.println("Hello")
                                   ^
1 error
  • Hello.java:3: file and line number
  • error: ';' expected: what was expected
  • ^ mark: the error's position
  • If there is an error, no .class file is produced; the program never runs.

Run-time error (exception)

public class Divide {
    public static void main(String[] args) {
        int a = 10, b = 0;
        System.out.println(a / b);
    }
}
Exception in thread "main"
java.lang.ArithmeticException: / by zero
	at Divide.main(Divide.java:4)
  • The code compiles, but at run time an exception is thrown.
  • / by zero: an integer cannot be divided by zero.
  • (Divide.java:4): the line where it happened.
  • If the exception is not caught with try-catch, the program stops at this line.

When several errors are listed, start with the first one; the rest are often side effects of it.

Expressions and Variables · Step by step

Evaluating an Expression Step by Step

The computer does not evaluate an expression in one go; it simplifies it step by step by precedence rules.

(72 - 32) / 9 * 5

First the parentheses: 72 − 32 = 40.

40 / 9 * 5

/ and * have the same precedence → left to right: 40 / 9 first.

4 * 5 (40 / 9 = 4, remainder 4 dropped)

Both operands are int → integer division: 4, not 4.44….

20

Result 20. The mathematically expected value was 22.22…: a semantic (logic) error.

(72.0 - 32) / 9 * 5

With 72.0, in double − int the int is widened to double first; the result is 40.0.

40.0 / 9 * 5

40.0 / 9 is now real division: 4.444444444444445.

4.444444444444445 * 5

Multiplication: double × int → double.

22.22222222222222

Correct result. If you need a fractional result, at least one operand must be a double.

×/5−972321.2.3.

Expression tree: lower operations run first; numbers give the order.

Expressions and Variables

Dynamic and Static Typing

Dynamically typed languages (Python, JavaScript)

  • A variable's type is not declared in advance; it is set when a value is assigned.
  • The type can change at run time.
  • Flexible, but errors show up only while running.

Statically typed languages (Java, C, C#)

  • A variable's type is declared explicitly and never changes.
  • Incompatible operations, such as string with integer, are reported at compile time.
  • Safer, and the compiler can generate faster code.

Python

x = 5          # x is an int now
x = "five"      # now a str: no problem
print(x + 1)   # at run time:
# TypeError: can only concatenate
#   str (not "int") to str

Java

int x = 5;
x = "five";     // does not compile:
// error: incompatible types:
//   String cannot be converted to int

Java 10+: var count = 3; declares a variable without writing its type, but the type is still fixed at compile time (as int); Java stays statically typed.

Strings and Types

Don't Compare Different Types

  • Comparing different data types directly causes errors: you cannot compare an integer with a string.
  • Languages define rules and type conversions for comparing types.

✗ Direct comparison

int num = 5;
String text = "5";
boolean b = num == text;
error: bad operand types for binary operator '=='
  first type:  int
  second type: String

✓ Convert to one type first

int num = 5;
String text = "5";
System.out.println(Integer.parseInt(text) == num);
System.out.println(text.equals(String.valueOf(num)));
System.out.println(text.equals(num));
true
true
false

text.equals(num) compiles but always returns false: a String is never equal to an Integer. Compare strings with equals, not ==.

Strings and Types

Operations on Different Types

Operations behave differently on different types: on strings, + means concatenation, not addition.

ExpressionJava resultTypeExplanation
3.0 + 4.07.0doubletwo floating-point numbers
3 + 47inttwo integers
3 + 4.07.0doubleint → double widening (automatic)
"3" + "4""34"Stringconcatenation
3 + "4""34"Stringif one side is a string, the other is converted to a string. Not an error (Python raises TypeError)
3 + truedoes not compile—bad operand types for binary operator '+'
'a' + 198intchar is a numeric code ('a' = 97)

Mixing types without knowing the language's rules leads to unexpected results or errors. Java's rules are precise, and the compiler enforces them.

Program and Algorithm · Step-by-step code trace

What Is a Program? Order Matters

A program is a sequence of instructions; the computer executes them one at a time and in order, so getting the order right matters.

a3b5

Goal: take a and b and swap their values.

a5b5

a = b: 5 is written to a. Its old value 3 is lost!

a5b5

b = a: b gets a's current value (5).

a5b5

Output 5 5: the swap failed. The order of statements decides the result.

c3d5temp?

The right way: a third, temporary variable.

c3d5temp3

First, c's value goes into temp and is saved.

c5d5temp3

Now c can be overwritten: c = 5.

c5d3temp3

d gets the saved old value of c (3).

c5d3temp3

Output 5 3: the swap worked.

int a = 3, b = 5;
a = b;
b = a;
System.out.println(a + " " + b);

int c = 3, d = 5;
int temp = c;
c = d;
d = temp;
System.out.println(c + " " + d);

Program and Algorithm

Expressions, Statements and Programs

Expression → valueComputes a value and returns it: 3 + 4 evaluates to 7.
Statement → effectHas an effect: pi = 3.14159; assigns a value to a variable, System.out.println(pi); prints to the screen. In Java, statements end with ;.
Expressions can nestAn expression can appear inside other expressions and statements: double area = pi * r * r;
Program = a sequence of statementsA program is many statements executed in order.

A statement cannot appear inside an expression. println prints (an effect) but returns no value (void):

double d = 3 + System.out.println(pi);
error: 'void' type not allowed here
3 + 4;      // value, no effect
error: not a statement

In Java, assignment also produces a value: int y = (x = 4) + 1; → x = 4, y = 5. It compiles, but it is hard to read, so avoid it.

Popular Languages

Popular Programming Languages

  • Programming languages offer different strengths for different tasks.
  • Programmers choose the best-fitting language for the project's needs.
  • Language popularity is ranked every year by surveys and indexes (Stack Overflow survey, TIOBE, IEEE Spectrum).
  • The table shows some of the leading languages in 2023.
LanguageWhere it shines
Pythondata analysis, AI, web development
Javalarge-scale enterprise applications, Android
JavaScriptweb browsers, web development
C#Windows applications, game development
C++games, systems programming, performance-critical software
Rustsafe and fast systems programming
Swiftapp development for Apple platforms
KotlinAndroid app development (runs on the JVM)
Go (Golang)simple and efficient; network and cloud applications

Summary

Summary

TopicKey points
Kinds of languageslow / high level; general-purpose / domain-specific; compiled / interpreted
Javajavac → bytecode (.class) → JVM (interpreter + JIT); “write once, run anywhere”
Paradigmsimperative, functional, logic, object-oriented; Java: object-oriented + imperative
Syntax / semanticssyntax: form; static semantics: type checks at compile time; semantics: one precise meaning, but maybe not the one you intended
Kinds of errorssyntax and static semantics (compile time), run time (exceptions), logic (wrong result)
Expressionsparentheses → * / % → + -, left to right; int / int is integer division; for powers use Math.pow
Variables and assignmenttype + name; the right side is evaluated first, then stored; = is assignment, == is comparison
TypesJava is statically typed; int + double → double; string + anything → concatenation
Programalgorithm first, then code; expressions produce values, statements have effects; statements run in order

Summary

Common Mistakes

Forgetting the semicolonSystem.out.println("Hello") → ';' expected. javac's ^ marks the end of the line missing the ;.
Mixing up = and ==if (x = 100) → int cannot be converted to boolean. Comparison is ==.
Integer division(a + b) / 2 gives 7 as the average of 7 and 8. Real division needs / 2.0.
** or ^ for powers2 ** 3 → illegal start of expression; 2 ^ 3 compiles but is XOR (1). Use Math.pow(2, 3).
String + number order"Total: " + 2 + 3 → Total: 23. To add first: "Total: " + (2 + 3).
Upper/lower caseNum declared, then num used → cannot find symbol. Java is case-sensitive.
Using a variable before assigning itint s; System.out.println(s); → variable s might not have been initialized.
Decimal separatorOn a computer with a Turkish locale, nextDouble() expects input like 7,5; typing 7.5 throws InputMismatchException.

Summary

Practice Problems

  1. Evaluate: (a) 10 + 6 / 4 * 2 (b) (10 + 6) / 4 * 2 (c) 10 + 6 / 4.0 * 2
  2. What do these print? System.out.println("Total: " + 2 + 3); and System.out.println(2 + 3 + " total");
  3. After this code runs, what are a and b? int a = 4; int b = a * 3; a = b - a; b = b / a;
  4. Name the error type: (a) int n = 4.5; (b) System.out.println("Hello"; (c) for the area of a circle area = 2 * pi * r;
  5. double c = (f - 32) * 5 / 9; — what is the result for f = 100? What if you declare f and c int instead?
Show answers
  1. (a) 6 / 4 = 1, 1 * 2 = 2 → 12 (b) 16 / 4 = 4, 4 * 2 → 8 (c) 6 / 4.0 = 1.5, × 2 = 3.0 → 13.0
  2. Total: 23 (left-to-right concatenation) and 5 total (the two int values are added first).
  3. b = 12, a = 12 − 4 = 8, b = 12 / 8 = 1 (integer division) → a = 8, b = 1.
  4. (a) static semantics: possible lossy conversion from double to int (b) syntax: ')' or ',' expected (c) logic error: it compiles but computes the circumference; the correct formula is pi * r * r.
  5. 68 × 5 / 9 = 37.77777777777778. int version: 340 / 9 = 37 (fraction dropped).

Summary

Exercises

  1. Give the value and type of: 7 % 3, -7 / 2, 1 / 3 * 3, 1.0 / 3 * 3, Math.pow(2, 10).
  2. Which of these are valid variable names? total2, 2total, _counter, student count, $price, int, averageGrade
  3. Write the algorithm, then the Java code, for a program that reads a Fahrenheit value from the user and converts it to Celsius.
  4. Classify each as an expression or a statement: x * 2, x = 5;, x > 3, System.out.println(x);
  5. 5 / 9 * (f - 32) with int f = 100 gives 0 — why? Fix it in two different ways.
Answers / hints
  1. 1 (int), -3 (int, truncated toward zero), 0 (int: 1 / 3 = 0), 1.0 (double), 1024.0 (double).
  2. Valid: total2, _counter, $price, averageGrade. Invalid: 2total (starts with a digit), student count (space), int (keyword).
  3. Read → c = (f - 32) * 5 / 9 → print; double f = in.nextDouble();. 100 → 37.77777777777778.
  4. Expressions: x * 2, x > 3 (produce values). Statements: x = 5;, System.out.println(x); (have effects).
  5. With integer division 5 / 9 is 0, and 0 × 68 = 0. Fix: 5.0 / 9 * (f - 32) or (f - 32) * 5 / 9 (multiply first: 37).

Summary

References

  • Oracle, The Java Tutorials: “Language Basics” (variables, operators, expressions, statements and blocks).
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (Chapter 3: Lexical Structure, Chapter 15: Expressions).
  • P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapters 1–2).
  • A. B. Downey and C. Mayfield, Think Java: How to Think Like a Computer Scientist, 2nd ed., O'Reilly, 2019 (Chapters 1–2).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022 (Chapters 2–3).
  • J. Guttag, Introduction to Computation and Programming Using Python, 3rd ed., MIT Press, 2021 (Chapter 2: syntax, static semantics and semantics).

The End

Chapter 2.1: Programming
Previous: Chapter 1.4: Flowcharts · Next: Chapter 2.2: Syntax Rules
1 / 1 Sercan KÜLCÜ. All rights reserved.