Java Basics

Download the appropriate installer from Oracle. After installation add the folder C:\Program Files\Java\jdk-22\bin to your Path. Let's start with a simple code. Save it as FirstExample.java. Then compile the class with command javac FirstExample.java and run it with java FirstExample. For simple code like this you can also just run the code directly with java FirstExample.java.

public class FirstExample {

    public static void main(String[] args) {
        // This is a single-line comment

        /* This is
         * a multi-line
         * comment */
        System.out.println("Hello, World!");
    }
}

The keyword public is an access modifier that controls the level of access to this code from other parts of a program. Everything in Java program lives inside a class. After the keyword class there is the name of the class. The name of the class must match the file name exactly (in this case - FirstExample.java). Java always starts execution of compiled code with the main method of the class. The main method must be declared public. Curly braces mark the beginning and end of a class or a method. Every statement in Java must end with a semicolon. Strings are denoted with double quotes.

Data types

Java is a strongly typed language. There are four integer types: int (4 bytes), short (2 bytes), long (8 bytes), and byte (1 byte). The ranges of the integer types do not depend on the machine (unlike C and C++). Long integers have a suffix of L or l. You can add underscore to number literals for ease of reading. There no unsigned integers in Java. Hexadecimal integers have a prefix 0x or 0X. Octal integers have a prefix 0, and binary integers have a prefix of 0b or 0B.

Floating-point types include float (4 bytes) and double (8 bytes). float type literals have a suffix of f or F. double type has an optional suffix of d or D. The constants Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN (and corresponding Float constants) represent positive infinity, negative infinity, and not a number. To check if a variable is not a number, use Double.isNan() method.

The char type is used to single character values enclosed in single quotes ''.

The boolean type has two values, true and false.

You declare a variable by placing the type first, followed by the name of the variable. Avoid using names that start with dollar sign $ because such names are used by the Java compiler. Java can infer data type when you replace the type with var keyword.

double salary;
salary = 65_000.0;
int vacationDays = 12;
long earthPopulation = 8_019_876_189l;
boolean done = false;
var greeting = "Hello!";

Constants are declared with the final keyword. Class constants are available to multiple methods inside a single class. Such constants appear inside a class but outside of any method. Class constants are declared with static final keyword. The constant can be accessible by other classes if declared with the public keyword.

public class Constants {
    public static final double CM_PER_INCH = 2.54;

    public static void main(String[] args) {
        final double paperWidth = 8.5;
        final double paperHeight = 11;
        System.out.println("Paper size in centimeters: "
                + paperWidth * CM_PER_INCH + " by "
                + paperHeight * CM_PER_INCH);
    }

}

An enumerated type has a finite number of named values or null to indicate that the variable is not set.

enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
Size s = Size.MEDIUM;

Operators

Java has the usual arithmetic operators addition +, subtraction -, multiplication *, division /, and modulus %. The division operator / denotes integer division if both operands are integers, and floating-point division otherwise. For reproducible results among various platforms, strictfp keyword is added to a function declaration to truncate intermediate computational results. Integer division by zero raises an exception, while floating-point division by zero results in -Infinity, Infinity, or NaN value.

double salary;
salary = 65_000.0;
int vacationDays = 12;
long earthPopulation = 8_019_876_189l;
boolean done = false;
var greeting = "Hello!";
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
Size s = Size.MEDIUM;

There is a variety of math functions available through the Math class.

double result;
result = 5.0/0; // => Infinity
result = -5.0/0; // => -Infinity
result = 0.0/0; // => NaN
result = Math.PI/2; // => 1.5707963267948966
result = Math.E; // => 2.718281828459045
result = Math.sqrt(9); // => 3.0
result = Math.sin(Math.PI/2); // => 1.0
result = Math.cos(Math.PI/3); // => 0.5000000000000001
result = Math.tan(Math.PI/4); // => 0.9999999999999999
result = Math.atan(Double.POSITIVE_INFINITY); // => 1.5707963267948966
result = Math.atan2(Math.tan(0.5), 1); // => 0.5
result = Math.exp(1); // => 2.718281828459045
result = Math.log(1); // => 0.0
result = Math.log10(100); // => 2.0
System.out.println(result);

Increment ++ and decrement -- operators behave differently in the prefix and postfix forms.

int m = 5;
int n = 5;
int a = 2 * ++m; // => 12
int b = 2 * n++; // => 10

Logical AND && and logical OR || operators short-circuit the evaluation result: the second argument is not evaluated if the first argument already determines the value.

int x = 0;
if (x != 0 && 1.0 / x > 0) {
    // Perform operations that require x to be non-zero
} else {
    // Handle the case when x is 0 or the division result is non-positive
}

Bitwise operators

Ternary operators

Numeric conversion

Conversions in which loss of information is possible are done by means of casts. You cannot cast between boolean values and any numeric type directly. For binary operators, such as +=, *=, if the operator evaluates to a value whose type is different from that of the left-hand-side, then it is coerced to fit.

double x = 9.997;
int nx = (int) x; // discard the fractional part
int mx = (int) Math.round(x); // round to nearest integer

int n = 300;
byte bn = (byte) n; // => 44: truncated value

boolean b = true;
int i = b ? 1 : 0; // => 1: cast boolean to int

int num = 1;
num += 3.5; // => 4: (int) (num + 3.5)