Sharing notes from my ongoing learning journey — what I build, break and understand along the way.
Java Basics – Part 1: Structure, Data Types, and Operators
Java Basics – Part 1
1 Structure and Hello World
Every Java program needs at least one class and one main() method.
Code blocks use curly braces { } instead of indentation.
public class HelloWorld {
// Entry point of every Java program
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Key points
- File name = class name (
HelloWorld.java) - Each statement ends with
; System.out.println()prints text followed by a newline.
UseSystem.out.print()if you don’t want a newline.
2 Strong Typing and Variables
Java is strongly typed:
you must declare each variable’s data type once and cannot later change it.
int number = 7;
double pi = 3.14;
boolean isJavaFun = true;
char letter = 'A';
String text = "Hello Java!";
Extra notes:
var(since Java 10) can infer the type:var city = "Berlin"; // automatically a String- Use
finalfor constants (cannot be reassigned):final double TAX_RATE = 0.19;
3 Basic Operators
Arithmetic:
System.out.println(21 / 3); // 7
System.out.println(23 / 3); // 7 (integer division)
System.out.println(23.0 / 3); // 7.666...
Increment / Decrement:
int x = 7;
x++; // post-increment
++x; // pre-increment
x--; // decrement
Logical operators:
System.out.println(true && false); // false
System.out.println(true || false); // true
System.out.println(!true); // false
Comparison operators: ==, !=, <, >, <=, >=.
4 Random Numbers
Two common ways:
// 0.0 ≤ value < 1.0
double r1 = Math.random();
// 1–6 (dice)
int dice = (int)(Math.random() * 6) + 1;
Or with the Random class:
import java.util.Random;
Random rnd = new Random();
int dice2 = rnd.nextInt(1, 7); // from 1 (inclusive) to 7 (exclusive)
5 Type Casting
Convert between numeric types manually:
int a = 5;
double b = a; // implicit widening
int c = (int)3.9; // explicit cast → 3
6 Comments
// single-line comment
/* multi-line
comment */
/** Javadoc comment for API documentation */
Summary
- Java uses braces for code blocks.
- Data types:
int,double,boolean,char,String. System.out.println()for output.- Operators: arithmetic, logical, increment/decrement.
- Random numbers via
Math.random()orRandom. - Strong typing + explicit casting.
