What is Java?
Java is a powerful, object-oriented programming language developed by Sun Microsystems (now Oracle). It is platform-independent via the Java Virtual Machine (JVM) and used for web applications, Android apps, desktop software, and enterprise systems.
Java emphasizes simplicity, security, portability and 'write once, run anywhere' (WORA).
Example
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Welcome to Maazster Tech!");
}
}Output
Welcome to Maazster Tech!Which Java edition & version?
Java has multiple editions for different development needs: Java SE (Standard), Java EE (Enterprise), Java ME (Micro), and JavaFX for modern desktop UIs.
Different Java releases add language and platform features; LTS releases (e.g., Java 17, Java 21) are common stability targets.
Java SE Example
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java SE!");
}
}Java EE Example (JSP snippet)
<%@ page language="java" %>
<html>
<body>
<h2>Hello from Java EE!</h2>
</body>
</html>Java ME Example (snippet)
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloME extends MIDlet {
public void startApp() {
Form form = new Form("Java ME");
form.append("Hello from Java ME!");
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
}JavaFX Example
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class HelloFX extends Application {
public void start(Stage stage) {
Label label = new Label("Hello from JavaFX!");
stage.setScene(new Scene(label, 250, 100));
stage.show();
}
}Setup — install JDK & configure environment
Install the Java Development Kit (JDK), set JAVA_HOME to the JDK path and add the JDK's bin to your PATH so `java` and `javac` run from terminal/command prompt.
After installation, verify using the command `java -version`.
Verify Java Command
java -versionSample Output
java version "21.0.2" 2025-01-15 LTS
Java(TM) SE Runtime Environment (build 21.0.2+13)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13, mixed mode)First program — Hello World
The Hello World program demonstrates Java syntax (class definition and the main method) and verifies the environment.
Example
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Output
Hello, World!Basic Java syntax
Java programs are organized into classes and methods. Statements end with a semicolon and blocks are delimited by curly braces.
Comments: `//` for single-line and `/* ... */` for multi-line.
Sample Program
// This is a simple Java program
public class SyntaxExample {
public static void main(String[] args) {
int age = 22; // declaring an integer variable
String name = "Umair"; // declaring a String variable
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}Output
Name: Umair
Age: 22Data types & variables
Java has primitive data types (int, long, float, double, boolean, char, byte, short) and non-primitive types like String and arrays.
Variables must be declared with a type and can be assigned values when declared or later.
Example
public class VariablesExample {
public static void main(String[] args) {
int age = 22;
double height = 5.9;
char grade = 'A';
boolean isStudent = true;
String name = "Umair";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Grade: " + grade);
System.out.println("Is Student? " + isStudent);
}
}Output
Name: Umair
Age: 22
Height: 5.9
Grade: A
Is Student? trueOperators & expressions
Operators perform operations on variables and values: arithmetic, relational, logical, assignment and unary operators.
Expressions combine variables and operators to produce new values.
Example
public class OperatorsExample {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a > b? " + (a > b));
boolean result = (a > b) && (b > 0);
System.out.println("Logical AND result: " + result);
}
}Output
a + b = 15
a - b = 5
a * b = 50
a / b = 2
a > b? true
Logical AND result: trueControl flow
Control flow statements determine the execution order: `if/else`, `switch`, `for`, `while`, `do-while`.
Use loops for repetition and conditionals to branch logic.
Example
public class ControlFlowExample {
public static void main(String[] args) {
int marks = 75;
if (marks >= 50) System.out.println("You passed!"); else System.out.println("Try again!");
System.out.println("Counting 1 to 5:");
for (int i = 1; i <= 5; i++) System.out.println(i);
}
}Output
You passed!
Counting 1 to 5:
1
2
3
4
5Arrays & Strings
Arrays hold multiple items of the same type accessed by index. Strings are immutable sequences of characters and support concatenation and utility methods.
Use for-each (`for (T x : arr)`) to iterate arrays cleanly.
Example
public class ArraysStringsExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("First number: " + numbers[0]);
String name = "Umair";
System.out.println("Hello, " + name + "!");
System.out.println("All numbers:");
for (int num : numbers) System.out.println(num);
}
}Output
First number: 10
Hello, Umair!
All numbers:
10
20
30
40
50Methods & parameter passing
Methods group reusable code. Java uses pass-by-value for primitives and object references are passed by value (meaning the reference is copied).
Methods can return values and accept parameters.
Example
public class MethodsExample {
static int addNumbers(int a, int b) { return a + b; }
static void greet(String name) { System.out.println("Hello, " + name + "!"); }
public static void main(String[] args) {
int result = addNumbers(10, 20);
System.out.println("Sum: " + result);
greet("Umair");
}
}Output
Sum: 30
Hello, Umair!Object-Oriented Programming (OOP) — core concepts
OOP organizes code around objects and classes. Core concepts are: Class & Object, Inheritance, Encapsulation, Polymorphism, Abstraction.
OOP promotes modularity, reuse and maintainability.
Example
class Student {
String name; int age;
Student(String name, int age){ this.name = name; this.age = age; }
void displayInfo(){ System.out.println("Name: " + name + ", Age: " + age); }
}
public class OOPExample {
public static void main(String[] args){
Student s1 = new Student("Umair", 22);
Student s2 = new Student("Aisha", 20);
s1.displayInfo(); s2.displayInfo();
}
}Output
Name: Umair, Age: 22
Name: Aisha, Age: 20Encapsulation & access modifiers
Encapsulation hides internal state by using private fields and public getters/setters, enabling validation and controlled access.
Access modifiers: `private`, `protected`, `public`, and package-private (no modifier).
Example
class Student {
private String name; private int age;
public String getName(){ return name; }
public void setName(String name){ this.name = name; }
public int getAge(){ return age; }
public void setAge(int age){ if(age > 0) this.age = age; }
}
public class EncapsulationExample {
public static void main(String[] args){
Student s = new Student(); s.setName("Umair"); s.setAge(22);
System.out.println("Name: " + s.getName()); System.out.println("Age: " + s.getAge());
}
}Output
Name: Umair
Age: 22Inheritance & polymorphism
Inheritance allows a subclass to extend a superclass. Polymorphism allows objects to be treated as instances of their parent type while using overridden methods at runtime.
Use interfaces and abstract classes to design flexible hierarchies.
Example
class Animal { void sound(){ System.out.println("Animal makes a sound"); } }
class Dog extends Animal { void sound(){ System.out.println("Dog barks"); } }
public class InheritancePolymorphismExample {
public static void main(String[] args){
Animal a = new Animal(); a.sound();
Dog d = new Dog(); d.sound();
Animal pet = new Dog(); pet.sound();
}
}Output
Animal makes a sound
Dog barks
Dog barksAbstraction & interfaces
Abstraction hides implementation details using abstract classes and interfaces. Interfaces define contracts which classes implement.
Abstract classes can provide some default behavior while leaving some methods abstract.
Example
abstract class Vehicle { abstract void start(); }
class Car extends Vehicle { void start(){ System.out.println("Car starts with a key"); } }
interface Electric { void charge(); }
class Tesla implements Electric { public void charge(){ System.out.println("Tesla is charging"); } }
public class AbstractionInterfaceExample {
public static void main(String[] args){
Vehicle myCar = new Car(); myCar.start();
Tesla t = new Tesla(); t.charge();
}
}Output
Car starts with a key
Tesla is chargingException handling
Use `try`, `catch`, `finally`, `throw`, and `throws` to manage runtime errors and keep programs from crashing unexpectedly.
Always catch specific exceptions when possible and use finally or try-with-resources to release resources.
Example
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}
}
}Output
Error: Cannot divide by zero!
Execution completed.File Handling
Use FileReader/FileWriter and BufferedReader/BufferedWriter for classic I/O. Use NIO (Path, Files) for efficient file operations.
Try-with-resources ensures streams are closed automatically.
Example
import java.io.*;
public class FileHandlingExample {
public static void main(String[] args) {
String filename = "example.txt";
try (FileWriter writer = new FileWriter(filename)) {
writer.write("Hello, Java File Handling!");
} catch (IOException e) { System.out.println("Error writing to file: " + e.getMessage()); }
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) System.out.println(line);
} catch (IOException e) { System.out.println("Error reading from file: " + e.getMessage()); }
}
}Output
Hello, Java File Handling!Collections framework
Java Collections Framework provides List, Set, Map and other collection types for storing and manipulating groups of objects.
Choose the collection type based on ordering and duplication requirements (List allows duplicates, Set does not).
Example
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple"); fruits.add("Banana"); fruits.add("Apple");
System.out.println("List: " + fruits);
Set<String> uniqueFruits = new HashSet<>(fruits);
System.out.println("Set: " + uniqueFruits);
Map<String,Integer> fruitCount = new HashMap<>();
fruitCount.put("Apple",2); fruitCount.put("Banana",1);
System.out.println("Map: " + fruitCount);
}
}Output
List: [Apple, Banana, Apple]
Set: [Banana, Apple]
Map: {Apple=2, Banana=1}Generics
Generics enable classes, interfaces and methods to operate on typed parameters, providing compile-time type safety and eliminating many casts.
Use generics with collections to ensure type safety: `List<String>`.
Example
import java.util.*;
public class GenericsExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana");
for (String fruit : fruits) System.out.println(fruit);
printArray(fruits.toArray(new String[0]));
}
public static <T> void printArray(T[] array) { for (T element : array) System.out.println("Element: " + element); }
}Output
Apple
Banana
Element: Apple
Element: BananaStreams & Lambda expressions (Java 8+)
Lambda expressions provide compact syntax for functional interfaces. Streams enable expressive, pipeline-style processing of collections.
Use map, filter, collect, and forEach to transform and consume data.
Example
import java.util.*;
import java.util.stream.*;
public class StreamsLambdaExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple","Banana","Orange","Mango");
fruits.forEach(fruit -> System.out.println(fruit));
List<String> filtered = fruits.stream().filter(f -> f.startsWith("A")).collect(Collectors.toList());
System.out.println("Fruits starting with A: " + filtered);
}
}Output
All fruits:
Apple
Banana
Orange
Mango
Fruits starting with A: [Apple]Multithreading & Concurrency basics
Java supports multithreading via Thread class and Runnable interface; java.util.concurrent APIs provide higher-level concurrency utilities.
Manage shared state carefully using synchronization, locks, or concurrent collections to avoid race conditions.
Example
class MyThread extends Thread {
public void run() {
for(int i = 1; i <= 5; i++) System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
}
public class MultithreadingExample {
public static void main(String[] args) {
MyThread t1 = new MyThread(); MyThread t2 = new MyThread();
t1.setName("Thread-1"); t2.setName("Thread-2");
t1.start(); t2.start();
}
}Sample Output
Thread-1 is running: 1
Thread-2 is running: 1
Thread-1 is running: 2
...I/O & NIO (Files)
Classic I/O uses streams/readers/writers. NIO (New I/O) provides Path, Files and ByteBuffer for efficient and scalable I/O operations.
Prefer NIO for file operations and when you need non-blocking or high-performance file handling.
Example (IO & NIO)
import java.io.*;
import java.nio.file.*;
import java.util.List;
public class IO_NIO_Example {
public static void main(String[] args) {
String filename = "nio_example.txt"; String content = "Hello, Java I/O and NIO!";
try (FileWriter writer = new FileWriter(filename)) { writer.write(content); }
catch (IOException e) { System.out.println("Error writing file: " + e.getMessage()); }
try { Path path = Paths.get(filename); List<String> lines = Files.readAllLines(path); lines.forEach(System.out::println); }
catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); }
}
}Output
Hello, Java I/O and NIO!Networking basics
Java networking APIs (java.net) include classes like Socket, ServerSocket, URL, and HttpURLConnection for building networked applications.
You can build simple client-server programs using ServerSocket and Socket over TCP.
Server Example
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5000);
System.out.println("Server started, waiting for client...");
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Client says: " + in.readLine());
client.close(); server.close();
}
}Client Example
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, Server!"); socket.close();
}
}Server Output
Server started, waiting for client...
Client says: Hello, Server!Database access (JDBC)
JDBC (Java Database Connectivity) provides standard APIs to connect and operate on relational databases (MySQL, PostgreSQL, Oracle).
Use DriverManager or a datasource, create Statements or PreparedStatements, execute queries, and iterate ResultSet for results.
Example (JDBC)
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; String user = "root"; String password = "password";
try { Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name FROM students");
while (rs.next()) System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
rs.close(); stmt.close(); conn.close();
} catch (Exception e) { e.printStackTrace(); }
}
}Sample Output
ID: 1, Name: Umair
ID: 2, Name: AishaJSON & Serialization
Java supports object serialization (java.io.Serializable) to persist object state. For JSON, libraries like Gson or Jackson are commonly used to serialize/deserialize objects.
Maven dependency (Gson)
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>Build tools & dependency management
Maven and Gradle are popular build tools that manage compilation, testing, packaging and dependencies. They simplify project setup and reproducible builds.
Maven pom.xml snippet
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
</project>Gradle snippet
plugins { id 'java' }
repositories { mavenCentral() }
dependencies { implementation 'com.google.code.gson:gson:2.10.1' }Testing
Testing ensures correctness. JUnit (and TestNG) are standard frameworks for unit testing Java code. Use assertions and test lifecycle annotations.
JUnit 5 Example
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class Calculator { int add(int a,int b) { return a+b; } }
public class CalculatorTest {
@Test
void testAddition() {
Calculator calc = new Calculator();
assertEquals(30, calc.add(10,20), "Addition should be 30");
}
}Logging
Logging records application events and errors. Java provides java.util.logging, while Log4j and SLF4J are popular third-party frameworks with richer configuration options.
Example (java.util.logging)
import java.util.logging.Logger; import java.util.logging.Level;
public class LoggingExample {
private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());
public static void main(String[] args) {
logger.info("Application started");
try { int result = 10/0; } catch (ArithmeticException e) { logger.log(Level.SEVERE, "An error occurred: Division by zero", e); }
logger.info("Application finished");
}
}Sample Output (console)
INFO: Application started
SEVERE: An error occurred: Division by zero
java.lang.ArithmeticException: / by zero
INFO: Application finishedPackaging & deployment
Package Java applications into JAR (or WAR for web apps). Use `jar` to bundle compiled classes and resources, and `java -jar` to run an executable JAR.
Use build tools (Maven/Gradle) to produce artifacts and manage deployment lifecycles.
Commands
javac MyApp.java
jar cvf MyApp.jar MyApp.class
java -jar MyApp.jarPerformance & JVM internals (intro)
Understanding JVM internals helps optimize performance: the heap and stack memory areas, garbage collection, JIT compilation and class loading are key JVM concepts.
Tune GC and understand object allocation patterns to reduce pauses and memory overhead.
Security basics
Java provides security primitives: access modifiers, exception handling, Java Security Manager (legacy), cryptography APIs and secure communications (SSL/TLS).
Follow secure coding practices, validate inputs, handle sensitive data carefully, and use up-to-date cryptography libraries.
Design patterns — common ones
Design patterns are reusable solutions to common design problems. Common Java patterns include Singleton, Factory, Observer, Strategy.
Singleton Example
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
public void showMessage() { System.out.println("Singleton instance works!"); }
}
public class SingletonDemo { public static void main(String[] args){ Singleton obj = Singleton.getInstance(); obj.showMessage(); } }Factory Example (sketch)
interface Shape { void draw(); }
class Circle implements Shape { public void draw(){ System.out.println("Drawing Circle"); } }
class Rectangle implements Shape { public void draw(){ System.out.println("Drawing Rectangle"); } }
class ShapeFactory { public Shape getShape(String shapeType){ if(shapeType.equalsIgnoreCase("CIRCLE")) return new Circle(); else if(shapeType.equalsIgnoreCase("RECTANGLE")) return new Rectangle(); return null; } }Best practices & coding conventions
Follow descriptive naming, modular design, single responsibility per method, proper exception handling, and Javadoc for public APIs.
Keep code readable with consistent indentation and limit method sizes for maintainability.
Example (naming)
// Bad: int x = 5; // Good: int numberOfStudents = 5;Example (modular code)
public void startProcess() { initialize(); executeTask(); finish(); }
private void initialize() { /* ... */ }
private void executeTask() { /* ... */ }
private void finish() { /* ... */ }Mini-projects & hands-on tutorials
Suggested mini-projects: a CLI contact manager (file I/O & collections), a simple chat server/client (networking & threads), a small web app (Servlets/JSP or Spring Boot) and unit tests for core functions.
Hands-on practice helps consolidate concepts from basics to advanced topics.
Common errors & troubleshooting tips
Common issues: syntax errors (missing semicolons), runtime exceptions (NullPointerException, ArrayIndexOutOfBoundsException), logical errors (wrong operators).
Troubleshooting: read stack traces, use debugger, write unit tests, and isolate problems by making code modular.
Examples of Errors & Fixes
// Syntax error: int num = 10 // Fix: int num = 10;
// Runtime: System.out.println(arr[5]); // Fix: ensure index within bounds
// NullPointer: if(str != null) System.out.println(str.length());Exercises / quiz (with answers)
Exercise examples: write a method to reverse a string, implement a simple ArrayList-backed stack, create unit tests for basic arithmetic methods, and use streams to filter and map collections.
Provide answers as separate unit tests or small runnable programs for verification.
Optional, Streams, and Date/Time API
Optional helps prevent nulls, Streams provide functional collection processing, and java.time (LocalDate/LocalTime/LocalDateTime) replaces old Date/Calendar APIs with immutable, thread-safe types.
Optional Example
import java.util.Optional;
public class OptionalExample { public static void main(String[] args) { Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default Name")); } }Streams Example
import java.util.*; import java.util.stream.*;
public class StreamExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1,2,3,4,5); int sum = numbers.stream().filter(n->n%2==0).mapToInt(Integer::intValue).sum(); System.out.println("Sum of even numbers: " + sum); } }Date/Time Example
import java.time.LocalDate; import java.time.format.DateTimeFormatter;
public class DateTimeExample { public static void main(String[] args) { LocalDate today = LocalDate.now(); System.out.println("Today: " + today); LocalDate birthday = LocalDate.parse("2000-05-10", DateTimeFormatter.ISO_DATE); System.out.println("Birthday: " + birthday); } }References
This JS book was generated from the uploaded source document. For the original full content and exact examples, see the source file. :contentReference[oaicite:1]{index=1}
If you want this exported as a .js/.json/.yaml file or want the content split/filtered differently (for example, include or exclude SEO meta), tell me and I will produce it.