Basic Syntax
First Program
The class name must match the filename for a public class.
public class GreetingApp {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Compile via terminal: javac GreetingApp.java
Execute: java GreetingApp
Comments
Single-line: // comment
Multi-line: /* comment */
public class CommentDemo {
public static void main(String[] args) {
// System.out.println("hidden");
/*
int x = 100;
int y = 50;
*/
}
}
Literals
- Integer:
42,-8 - Floating-point:
3.14,-0.5 - String:
"Greetings","你好" - Character:
'a','你' - Boolean:
true,false - Null:
null
Variables
int count = 20;
byte b = 10;
short s = 20;
long l = 30L;
float price = 19.99F;
double rate = 15.5;
char grade = 'A';
boolean active = true;
String message = "Welcome";
Rules:
- Variables must be declared before use and cannot be redeclared in the same scope.
- Initialization is required before accessing a variable.
Number Systems
- Binary: Prefix
0b(e.g.,0b1010) - Decimal: Default (e.g.,
10) - Octal: Prefix
0(e.g.,012) - Hexadecimal: Prefix
0x(e.g.,0xA)
Keyboard Input
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int value = input.nextInt();
Project Structure
Project → Module → Package → Class
Packages are folders; classes are .java files.
Operators
Arithmetic: +, -, *, /, %
Increment/Decrement: ++, --
Assignment: +=, -=, *=, /=, %=
Logical: && (short-circuit AND), || (OR)
Ternary: int max = (a > b) ? a : b;
String concatenation occurs when + involves a string:
String first = "abc";
String second = "def";
String combined = first + second; // "abcdef"
System.out.println(combined + 123); // "abcdef123"
Character arithmetic uses ASCII values:
char ch = 'c';
System.out.println(ch); // c
ch += 10; // 'c' (99) + 10 = 109 -> 'm'
System.out.println(ch); // m
Type Conversion
Automatic: Smaller types promote to larger types during operations.
Order: byte → short → int → long → float → double
Note: byte, short, and char promote to int for calculations.
Explicit Casting:
double pi = 3.14159;
int approx = (int) pi; // 3
Control Flow
Conditional Statements
import java.util.Scanner;
public class AgeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userAge = sc.nextInt();
if (userAge > 0 && userAge < 18) {
System.out.println("Minor");
} else if (userAge >= 18) {
System.out.println("Adult");
} else {
System.out.println("Invalid input");
}
}
}
Switch Statements
import java.util.Scanner;
public class DayChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter day number (1-7):");
int day = sc.nextInt();
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("Workday");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Invalid day");
}
int choice = sc.nextInt();
switch (choice) {
case 1 -> System.out.println("Option 1");
case 2 -> System.out.println("Option 2");
case 3 -> System.out.println("Option 3");
default -> System.out.println("No such option");
}
}
}
Loops
For loop:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
While loop:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do-while loop:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
Infinite loops:
while (true) { }
for (;;) { }
Control flow:
break: Exits the loop.continue: Skips to the next iteration.
Random Numbers
import java.util.Random;
Random rand = new Random();
int num1 = rand.nextInt(100); // 0 to 99
int num2 = rand.nextInt(1, 10); // 1 to 9
Complex Data Structures
Arrays
int[] values; // Declaration
int[] fixed = {10, 20, 30}; // Static initialization
int[] dynamic = new int[5]; // Dynamic initialization
Get length: array.length
Memory areas:
- Stack: Method execution.
- Heap: Objects/arrays created with
new. - Method Area: Compiled class files.
Two-Dimensional Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Dynamic initialization:
int[][] grid = new int[3][4];
Methods
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public void printSum(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println(sum);
}
}
Method overloading allows multiple methods with the same name but different parameters.
Parameter passing:
- Value types (
int,double, etc.): Pass by value (copy). - Reference types (
String, arrays, objects): Pass by reference (address).
Object-Oriented Programming
Classes and Objects
public class Car {
String model;
int year;
public void start() {
System.out.println(model + " is starting...");
}
}
// Usage
Car myCar = new Car();
myCar.model = "Toyota";
myCar.year = 2022;
myCar.start();
Rules:
- One public class per file; filename must match public class name.
- Class names use PascalCase.
Encapsulation
Private fields with public getters/setters:
public class Employee {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
} else {
System.out.println("Invalid age");
}
}
public int getAge() {
return age;
}
}
This Keyword
this refers to the current instance:
public class Demo {
private int value;
public void show() {
int value = 10;
System.out.println(value); // Local variable (10)
System.out.println(this.value); // Instance variable
}
}
Constructors
public class Person {
private String name;
private int age;
// No-argument constructor
public Person() {}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
String Class
Strings are immutable.
String s1 = "hello";
String s2 = new String("hello");
String s3 = new String(new char[]{'a', 'b'});
// Comparison
System.out.println(s1 == s2); // false (different references)
System.out.println(s1.equals(s2)); // true
System.out.println("AB".equalsIgnoreCase("ab")); // true
StringBuilder and StringJoiner
StringBuilder improves concatenation performance:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 5; i++) {
builder.append("x");
}
String result = builder.toString();
Common methods: append(), reverse(), length(), toString().
StringJoiner simplifies joining with delimiters:
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("A").add("B").add("C");
System.out.println(joiner); // [A, B, C]
ArrayList
ArrayList<String> items = new ArrayList<>();
items.add("Apple");
items.add("Banana");
System.out.println(items.get(0)); // Apple
System.out.println(items.size()); // 2
Supports generic types; primitive types use wrapper classes (Integer, Double, etc.).
Advanced OOP
Static Members
public class Counter {
public static int count = 0; // Shared across instances
public static void increment() { // Static method
count++;
}
}
Rules:
- Static methods can only access static members.
- No
thiskeyword in static methods.
Inheritance
public class Vehicle {
String type;
}
public class Bike extends Vehicle {
public Bike(String type) {
this.type = type;
}
public void ride() {
System.out.println(type + " is being ridden.");
}
}
Java supports single inheritance. All class inherit from Object.
Constructor rules:
- Subclass constructors implicitly call
super()(parent no-arg constructor) first. - Use
super(args)to call parameterized parent constructors.
Polymorphism
Vehicle v1 = new Bike("Mountain Bike");
Vehicle v2 = new Car("Sedan");
// Method calls use subclass implementations (runtime)
// Variable access uses parent class (compile-time)
Packages
package org.example.utils; // Package declaration
import java.util.ArrayList; // Import
Rules:
- No import needed for same package or
java.lang. - Fully qualified names resolve class name conflicts.
Final Keyword
finalvariable: Consatnt (single assignment).finalmethod: Cannot be overridden.finalclass: Cannot be extended.
public final class Constants {
public static final double PI = 3.14159;
}
Access Modifiers
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
private |
✔ | |||
| (default) | ✔ | ✔ | ||
protected |
✔ | ✔ | ✔ | |
public |
✔ | ✔ | ✔ | ✔ |
Code Blocks
- Local: Inside methods to limit variable scope.
- Instance initializer: Runs on object creation (before constructor).
- Static: Runs once when class loads.
public class Config {
static {
System.out.println("Static block executed");
}
}
Abstract Classes and Interfaces
Abstract class:
public abstract class Shape {
public abstract double area();
}
public class Circle extends Shape {
private double radius;
@Override
public double area() {
return Math.PI * radius * radius;
}
}
Interface:
public interface Drivable {
void drive();
}
public class Truck implements Drivable {
@Override
public void drive() {
System.out.println("Truck is driving");
}
}
Interfaces support default and static methods (since Java 8).
Inner Classes
public class Outer {
class Inner { // Member inner class
public void display() {
System.out.println("Inside inner class");
}
}
static class StaticNested { } // Static nested class
public void method() {
class Local { } // Local inner class
}
public void test() {
Drivable obj = new Drivable() { // Anonymous inner class
@Override
public void drive() {
System.out.println("Anonymous drive");
}
};
}
}
Generics
public class Box<T> {
private T content;
public void set(T item) {
this.content = item;
}
public T get() {
return content;
}
}
// Usage
Box<String> stringBox = new Box<>();
stringBox.set("Item");
String item = stringBox.get();
Wildcards:
? extends T: Accepts T or subclasses.? super T: Accepts T or superclasses.
Collection Traversal
Iteartor:
Collection<String> names = Arrays.asList("Alice", "Bob");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Enhanced for-loop:
for (String name : names) {
System.out.println(name);
}
Lambda expression:
names.forEach(name -> System.out.println(name));