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:
# 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.
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 Hellois 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.
publicis 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 (asdef,for,whilein Python).classstarts 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 themainmethod; its body follows between curly braces.- A Java application must have a
mainmethod: it is the entry point, where execution begins (the class is then an executable class). publicagain means usable by everyone; the keywordsstaticandvoidare explained later;String[] argsis an explicit parameter (methods can have none, one or more).
- A Java application must have a
- 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:
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
System.out.println("Hello, World!");Systemis a class of the Java platform APIApplication Programming Interface: the collection of ready-to-use classes provided together with the Java language.System.outis a field ofSystemholding an object of typePrintStream, another class of the API.- To use an object you must say which operation (method) to invoke:
printlnof theoutobject prints its argument and then moves to a new line. The round brackets contain the arguments. "Hello, World!"is aString: 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- loads the bytecode of the program into main memory (from
Hello.class); - starts the program by executing the
mainmethod of that class; - loads the bytecode of other classes needed during execution (for example
System); - translates the bytecode "on the fly" into machine instructions of the real CPU, which executes them (just in time compilation, JIT).
- loads the bytecode of the program into main memory (from
- 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
- Write or modify (edit
Hello.java). - Compile (
javac Hello.java). If there are syntax errors, go back to step 1. - Test (
java Hello), possibly with a debugger (jdb Hello). If there are logic errors, go back to step 1. - 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 |
- Portabilityhow easy it is to run the same program on computers with different CPUs and efficiencyhow fast the execution of a program is strongly depend on whether a language is compiled or interpreted, and are both important when choosing a language.
- Only portability: interpreted languages are the best choice. Only efficiency: compiled languages. Both objectives (as almost always): Java is a good compromise, being a mixed language, compiled and interpreted in different phases.
- In practice Python also uses an internal bytecode (see the interpreter in 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 →).
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 reportserror: cannot find symbolwith the line number, the position in the line (the^marker), the symbol (variable Out) and the location (class System). It is easy to diagnose:Outis undefined because Java is case-sensitive. - Example, a missing closing quote
System.out.println("Hello, World!);: the compiler correctly reportserror: unclosed string literal, pointing where the string begins.- With older compilers (Java 17 or older) further errors may appear:
';' expectedandreached 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.
- With older compilers (Java 17 or older) further errors may appear:
- 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 printsHell, 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
- Keywords: reserved and predefined by the language (
public,class). - Identifiers: strings of alphanumeric characters chosen by the programmer to name classes, methods, variables (
Hello,System,out,println). - Constants or literals: constant values.
- Separators: punctuation characters.
- 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
trueandfalse, the special constantnull.
Literals:
- Integer: decimal (
1,2,100,567,10000000000L, theLsuffix is for long); octal starts with zero (07,0456); hexadecimal starts with0x(0x12,0xAB17F); binary starts with0b(0b0111_0101_1111_1011, underscores allowed as in the slide). See Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information → for the number bases. - Floating point, single precision (about 7 significant digits), ends with
f:3.14f,2.f,.3f,0f,1e1f,6.022137e+23f.1e1means . - Floating point, double precision (about 15 significant digits), no ending:
3.14,3.141592653589793,2.,.3,0.0,1e1,1e-9,1e137. - Boolean:
false,true. - Character: in single quotes:
'a','B','?','7',' '. - String: in double quotes:
"Hello, World!"," ","". - Null literal:
null.
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.
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).
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".
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
doneis 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:
while (true) // condition always true
{
String line = in.next();
if (line.equalsIgnoreCase("Q"))
break;
else
... // processes line
}breakexits the loop; with nested loops it ends the innermost loop in which it is nested.continueends the current iteration and moves on to the next one (in awhileit jumps back to the test of the condition).
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.
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
condition ? value1 : value2;If the condition is true the expression has value value1, otherwise value2. It can be used in assignments:
y = x >= 0 ? x : -x; // y = |x| absolute valueIt 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:
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
charorString). - 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
mainneeded 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.javaproducesHello.class;java Helloruns 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,nullforbidden). - Literal forms: octal with leading
0, hexadecimal0x, binary0b,fsuffix for single precision,Lfor long,'c'for a char,"s"for a string. - Loop ends: use
<, never!=, especially with floating point. - Switch: constant integer,
charorStringcases, and do not forgetbreak.
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
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;
mainis the entry point of an executable class. System.out.println: classSystem, fieldout(aPrintStream), methodprintln(adds a new line).printdoes not. Strings only in double quotes.
From source to running program
javac Hello.javaproducesHello.class: bytecode, the machine code of the Java Virtual Machinethe virtual machine that runs Java bytecode, not of the real CPU.java Helloloads the bytecode, startsmain, 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,falseandnullare not allowed. - Literals: octal with leading
0, hexadecimal0x, binary0b;ffor single precision,Lfor long;'c'for a char,"s"for a string. - Separators:
( ) [ ] { } ; , . constandgotoare reserved keywords even though unused.
Control-flow complements
- Loop end tests use
<, never!=: with negativen, or with floating point, the loop never ends. - Loop and a half: read strings until the sentinel
Q, with a booleandoneflag. Alternatives:while (true)withbreak, or an assignment inside the condition (a side effect, generally discouraged). breakexits the innermost loop;continuemoves to the next iteration (in awhile, back to the test).- Conditional operator:
condition ? value1 : value2, e.g.y = x >= 0 ? x : -x;. switchcompares one integer,charorStringvariable with constant cases; each case ends withbreak, 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.