Salta al contenuto
Note per Studenti Java - Language Basics Report

Java - Language Basics

In questa pagina 8

Java is the second language of the course after Python (see Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics → and Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →, and Programming FundamentalsThe CPU only executes machine instructions (opcodes) of its own instruction set; assembly languages give them mnemonic names and an assembler translates them one-to-one, but they are CPU specific; high-level languages are CPU independent and are translated by a compiler (executable code is CPU specific) or run by an interpreter; compiled languages are generally more efficient, interpreted languages more portable, and Java aims at both.Programming Fundamentals → for the general notions). This note covers what Java is, the first program, how it is compiled and run, the two kinds of programming errors, the lexical rules of the language and some control-flow complements. Classes, objects, argument passing and input with Scanner are in Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner →.

1. The Java language

  • Created in 1991 at Sun Microsystems by a group of designers (the same year as Python). Goals: to be simple and CPU-independent (independent of hardware, platform or architecture).
  • The first product of the project was a browser, HotJava (1994), able to download programs called appletssmall Java programs downloaded from a server and run on the user's computer and run them regardless of the user's platform.
  • Why programmers adopt it:
    • simpler than its direct competitor C++;
    • "Write once, run anywhere": write and compile once, run everywhere;
    • a very rich library with a vast set of standard functions, independent of the operating system.
  • The slides show Java second in a 2025 ranking of programming languages (IEEE Spectrum), after Python.
  • Java was not designed for teaching: even a very simple program needs several technical details (unlike Python). In the first lessons some constructs are used without explaining them, and explained later.

2. The first program

Python for comparison:

python
# My first program in Python
print("Hello, world!")

In Java even a print needs a class and a main method, because of Java's structured, compiled design.

java
public class Hello
{
    public static void main(String[] args)
    {
        System.out.println("Hello, World!");
    }
}
  • The text is written with a text editor (it stores only characters, a space is a character too; unlike a word processor, which also stores fonts, sizes, styles) and saved in a file named Hello.java: the public class name must match the file name.
  • Java is case-sensitive: uppercase and lowercase letters are different characters.
  • Free format: spaces and line breaks do not matter except to separate words, so the whole program could be written on one line. Still, legibility matters.

2.1 Anatomy of the program

  • public class Hello is the class header; the class body follows between curly braces.
    • A class is a blueprint for creating objects and also a container of methods. Java is an object-oriented language (OOP). A Java program (application) consists of one or more classes (generally many).
    • Blueprint analogy: from one blueprint of a house you can build many houses; each house is an object (an instance of the class) with its own colour, address and so on, but the same structure.
    • public is an access modifiersays who can use the class or method; public means usable from anywhere. A keyworda reserved word of the language, written exactly as it is and not usable for other purposes is reserved (as def, for, while in Python). class starts a class definition.
    • Each source file can contain only one public class, whose name must match the file name.
  • A method is a named sequence of statements that describes how to perform a specific task (a function or procedure in other languages). In Java every method must be defined inside a class (unlike Python), so classes are the basic unit for organizing a program.
  • public static void main(String[] args) is the method header of the main method; its body follows between curly braces.
    • A Java application must have a main method: it is the entry point, where execution begins (the class is then an executable class).
    • public again means usable by everyone; the keywords static and void are explained later; String[] args is an explicit parameter (methods can have none, one or more).
  • Each statement ends with ;. The statements in the body of a method are executed one after the other, in order.

Syntax of an executable class:

java
public class ClassName
{
    public static void main(String[] args)
    {
        statements
    }
}

Saved in ClassName.java. For now the infrastructure around the statements is to be taken as necessary boilerplate.

2.2 The print statement

java
System.out.println("Hello, World!");
  • System is a class of the Java platform APIApplication Programming Interface: the collection of ready-to-use classes provided together with the Java language. System.out is a field of System holding an object of type PrintStream, another class of the API.
  • To use an object you must say which operation (method) to invoke: println of the out object prints its argument and then moves to a new line. The round brackets contain the arguments.
  • "Hello, World!" is a String: characters in double quotes (in Java strings can only be delimited by double quotes, unlike Python).
  • The dot sometimes means "use a field of a class", other times "use a method of an object": it depends on the context.
  • System.out.print("Hello, World!"); is the same but does not go to a new line.
  • The standard library is documented in HTML (Java platform API specification, online or downloadable), for example for PrintStream.

3. From source to running program

Programming has three phases: write the source code, compile it into executable code, run it.

javac Hello.java      generates Hello.class
java Hello            prints: Hello, World!
  • How the compiler is used depends on the operating system (icons, menus, typing a command, or an IDE, Integrated Development Environment). In the course the terminal commands of the JDK (Java Development Kit) are used.
  • Compiler (javac): translates the source into bytecode, the machine code of the Java Virtual Machine (JVM). The bytecode is not directly executable by the real CPU, because the JVM is not a physical CPU.
  • Interpreter (java): a program running on the user's computer that
    1. loads the bytecode of the program into main memory (from Hello.class);
    2. starts the program by executing the main method of that class;
    3. loads the bytecode of other classes needed during execution (for example System);
    4. translates the bytecode "on the fly" into machine instructions of the real CPU, which executes them (just in time compilation, JIT).
  • JVM = Java interpreter + real CPU: bytecode goes in, machine code goes to the CPU.
  • The Java platform API exists because writing a string to the standard output means interacting with the operating system, a low-level operation needing specialised knowledge. The language authors already programmed it in special classes (for example System), whose bytecode is in the API: you do not need to know their source code.
  • Process of Java programming: editor, source code, compiler, bytecode; the bytecode plus the libraries go to the interpreter, which gives the running program. The JDK contains the compiler, the libraries and the interpreter.
  • Note: classical Java requires compiling the class and then running it on the JVM; modern Java allows running single-file programs without a separate explicit compilation step.

3.1 The modify-compile-test cycle

  1. Write or modify (edit Hello.java).
  2. Compile (javac Hello.java). If there are syntax errors, go back to step 1.
  3. Test (java Hello), possibly with a debugger (jdb Hello). If there are logic errors, go back to step 1.
  4. Otherwise end.

4. Compiled, interpreted and mixed languages

Compiled (Pascal, C, C++) Java Interpreted (Python, BASIC, PERL)
Chain source and libraries, compiler (loader), executable file, program in execution source, compiler, bytecode file; bytecode and libraries go to the interpreter, program in execution source and libraries go to the interpreter, program in execution
Executable file machine code for a specific CPU bytecode none
Portability source only (must recompile for each CPU) source and bytecode ("compile once, run on different interpreters on different CPUs") source
Efficiency generally very efficient: all the translation is done once and for all before execution intermediate: part once (compiler), part at each execution (interpreter) generally inefficient: the whole translation is done at each execution

5. Programming errors

Syntax (compilation) errors: found by the compiler at compile time. Logical (semantic) errors: show up as wrong behaviour at run time.

  • Example of a syntax error, System.Out.println("Hello, World!");: the compiler reports error: cannot find symbol with the line number, the position in the line (the ^ marker), the symbol (variable Out) and the location (class System). It is easy to diagnose: Out is undefined because Java is case-sensitive.
  • Example, a missing closing quote System.out.println("Hello, World!);: the compiler correctly reports error: unclosed string literal, pointing where the string begins.
    • With older compilers (Java 17 or older) further errors may appear: ';' expected and reached end of file while parsing (the string was extended to the end of the line, swallowing the closing bracket).
    • One mistake can produce several messages: correct only the first error (the one at the top) and compile again. Knowing the compiler messages is needed to learn Java and pass the programming test.
  • Example of a logical error, System.out.println("Hell, World!"); (a missing character): the compiler does not flag it, because it does not care what the programmer wants to print. Compilation succeeds and the program prints Hell, World!, different from what was expected.
  • Semantic errors are much more insidious: the program compiles but does not do what it should. Fixing them requires patience in running the program and observing the results; programs must be tested like any engineering product. Specific programs (debuggers) help find logical errors (bugs).

6. Java grammar

Java is a formal language defined by a formal grammar (nearly context-free), split in two parts:

  • lexical rules: which words can be used;
  • syntax: how to build syntactically correct units that can be compiled (the rules for combining words into sentences).

Lexically, a program is made of lines (strings of characters ending with a new line), which are composed of elementary units called tokens (or lexemes, the "words"). Tokens must be separated by spaces and/or comments unless a separator or operator marks the end of the token: in System.out.println(...) the dot is a separator.

6.1 The five token types

  1. Keywords: reserved and predefined by the language (public, class).
  2. Identifiers: strings of alphanumeric characters chosen by the programmer to name classes, methods, variables (Hello, System, out, println).
  3. Constants or literals: constant values.
  4. Separators: punctuation characters.
  5. Operators: symbols that indicate an operation between variables and/or constants.

Keywords (slide list): abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while. const and goto are reserved (marked with an asterisk). Highlighted on the slide, because already used: class, public, static, void.

Identifiers: sequences of letters and digits of arbitrary length; the first character must be alphabetic or the underscore _.

  • Valid: Hello, main, _name. Not valid: 7Wonder, ?Why.
  • Cannot be used as identifiers: Java keywords, the boolean constants true and false, the special constant null.

Literals:

Separators (9 characters): ( ) [ ] { } ; , . (round, square and curly brackets or braces, semicolon, comma, dot).

Operators (37 characters or tokens), as listed on the slide:

  • = > < ! ~ ? :
  • == <= >= != && || ++ --
  • + - * / & | ^ % << >> >>>
  • += -= *= /= &= |= ^= %= <<= >>= >>>=

7. Control-flow complements

7.1 Testing the end of a range

Never use != to test the end of a range in a loop: if n is negative the loop never ends. Use <, which works even with negative values of n.

java
for (int i = 0; i != n; i++)   // what if n is negative? never ending loop!
{
    ...
}

for (int i = 0; i < n; i++)    // works, even with negative values of n
{
    ...
}

With floating point numbers it is even worse: because of the approximation of floating point arithmetic the loop below never ends (Math.PI is the constant pi).

java
for (double alfa=0; alfa != Math.PI; alfa += Math.PI/16)   // never ends
{...}

for (double alfa=0; alfa < Math.PI; alfa += Math.PI/16)    // works well
{...}

7.2 Sentinel values and the loop and a half

Many problems need to read a sequence of data without knowing how many items the user will provide (for example the sum of integers), using java.util.Scanner (details in Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner →). The end of the data is signalled by a sentinel value, here the character Q (quit). An integer cannot be the sentinel, because any integer is part of the possible data; so the data must be acquired as strings, and the input set is the integers plus the strings "Q" and "q".

java
Scanner in = new Scanner(System.in);
int sum = 0;
boolean done = false;
while (!done)
{   String line = in.nextLine();
    if (line.equalsIgnoreCase("Q"))
        done = true;
    else
        sum += Integer.parseInt(line);
}
  • The auxiliary boolean done is needed because the exit condition can only be computed halfway through the loop.
  • This structure, "do something, check a condition, do something else and repeat if the condition was true", has no predefined control structure in Java and is implemented with a trick: a boolean loop control variable. It is called the loop and a half or redundant loop.

Alternative 1, break with a never-ending while (true) loop:

java
while (true)  // condition always true
{
  String line = in.next();
  if (line.equalsIgnoreCase("Q"))
      break;
  else
      ... // processes line
}
  • break exits the loop; with nested loops it ends the innermost loop in which it is nested.
  • continue ends the current iteration and moves on to the next one (in a while it jumps back to the test of the condition).
java
while (condition1)            while (condition1)
{                             {
   statement1                    statement1
   if (condition2)               if (condition2)
      break;                        continue;
   statement2                    statement2
}                             }
...

Alternative 2, a statement with a side effect: the condition of the while also contains an assignment to line.

java
String line; // it must be defined outside the loop
while (!(line = in.nextLine()).equalsIgnoreCase("Q"))
{
      ... // processes line
}

Statements with side effects are generally not good because they make the code hard to read, but here the solution is "very attractive".

7.3 Conditional operator

java
condition ? value1 : value2;

If the condition is true the expression has value value1, otherwise value2. It can be used in assignments:

java
y = x >= 0 ? x : -x;   // y = |x| absolute value

It is a shortcut for if (x >= 0) y = x; else y = -x;.

7.4 Switch

A sequence of if / else if comparing a single integer variable with several constant alternatives can be written as a switch:

java
int x;
int y;
...
switch (x)
{   case 1: y = 1;  break;
    case 2: y = 4;  break;
    case 4: y = 16; break;
    default: y = 0; break;
}

equivalent to if (x == 1) y = 1; else if (x == 2) y = 4; else if (x == 4) y = 16; else y = 0;. Java also allows char and String control variables.

  • Advantage: the name of the variable to compare is not repeated.
  • Disadvantage: cannot be used if the compared variable is not an integer (or char or String).
  • Disadvantage: cannot be used if one of the values compared is not constant.
  • Disadvantage: each case must end with break, otherwise the body of the next case is also executed: the source of many errors.

8. Exam checklist

  • Java vs Python: classes and main needed even for a print; strings only in double quotes; statements end with ;, blocks use braces (free format); compiled to bytecode and then interpreted.
  • The public class name must equal the file name (Hello.java); javac Hello.java produces Hello.class; java Hello runs it.
  • Bytecode is machine code of the JVM, not of the real CPU; the interpreter translates it on the fly (JIT).
  • Java is portable at source and bytecode level, with intermediate efficiency; compiled languages are very efficient but portable only as source; interpreted languages are portable but generally inefficient.
  • Syntax errors are caught by the compiler (fix the first error first); logical errors are not and show up at run time (use tests and a debugger).
  • Five token types; identifier rules (first character a letter or _; keywords, true, false, null forbidden).
  • Literal forms: octal with leading 0, hexadecimal 0x, binary 0b, f suffix for single precision, L for long, 'c' for a char, "s" for a string.
  • Loop ends: use <, never !=, especially with floating point.
  • Switch: constant integer, char or String cases, and do not forget break.

Versione ripasso

Java (1991, Sun Microsystems): simple, CPU-independent, "write once, run anywhere", with a large standard library. Not designed for teaching, so even a print needs a class.

First program

java
public class Hello
{
    public static void main(String[] args)
    {
        System.out.println("Hello, World!");
    }
}
  • Saved as Hello.java: the public class name must match the file name. Java is case-sensitive, free format, every statement ends with ;.
  • Every method lives inside a class; main is the entry point of an executable class.
  • System.out.println: class System, field out (a PrintStream), method println (adds a new line). print does not. Strings only in double quotes.

From source to running program

  • javac Hello.java produces Hello.class: bytecode, the machine code of the Java Virtual Machinethe virtual machine that runs Java bytecode, not of the real CPU.
  • java Hello loads the bytecode, starts main, loads the other classes it needs, and translates to CPU instructions on the fly (JIT).
  • JDK = compiler + libraries + interpreter.
  • Cycle: syntax error goes back to editing; logic error found by testing goes back to editing.

Compiled, interpreted, mixed: compiled languages are very efficient but portable only as source; interpreted ones are portable but generally inefficient; Java is intermediate in both.

Errors: syntax errors are caught by the compiler (fix the first message, then recompile). Logic errors compile fine and show up at run time: use tests and debuggers.

Grammar: lexical rules (tokens) plus syntax. Five token types: keywords, identifiers, literals, separators, operators.

  • Identifiers start with a letter or _; keywords, true, false and null are not allowed.
  • Literals: octal with leading 0, hexadecimal 0x, binary 0b; f for single precision, L for long; 'c' for a char, "s" for a string.
  • Separators: ( ) [ ] { } ; , .
  • const and goto are reserved keywords even though unused.

Control-flow complements

  • Loop end tests use <, never !=: with negative n, or with floating point, the loop never ends.
  • Loop and a half: read strings until the sentinel Q, with a boolean done flag. Alternatives: while (true) with break, or an assignment inside the condition (a side effect, generally discouraged).
  • break exits the innermost loop; continue moves to the next iteration (in a while, back to the test).
  • Conditional operator: condition ? value1 : value2, e.g. y = x >= 0 ? x : -x;.
  • switch compares one integer, char or String variable with constant cases; each case ends with break, otherwise the next case also runs.

Common mistakes: forgetting break in a switch; using != as a loop end test; expecting a print without a class; a single missing character producing several compiler messages (fix only the first); assuming the compiler catches logic errors.

Teoria collegata