Java Programming

Java is a powerful, object-oriented programming language used for building enterprise-scale applications, Android apps, web services, and more. Master Java with our comprehensive guide.

Why Learn Java?

  • Platform independence with "Write Once, Run Anywhere"
  • Strongly typed, object-oriented language
  • High demand in enterprise and Android development
  • Vast ecosystem with mature frameworks
  • Excellent performance with JVM optimizations

Getting Started with Java

Java is a class-based, object-oriented programming language designed to have as few implementation dependencies as possible.

Installation

Java Development Kit (JDK) is required to develop Java applications:

Windows/macOS/Linux

  1. Download JDK from Oracle or Eclipse Temurin
  2. Run the installer
  3. Set JAVA_HOME environment variable
  4. Add Java to your PATH

Verify Installation

Check Java version in terminal:

$ java -version
$ javac -version

First Program

Create a file named HelloWorld.java with this content:

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}

Compile and run it from your terminal:

$ javac HelloWorld.java
$ java HelloWorld

Java Basics

Variables & Data Types

// Primitive data types
int age = 30; // Integer
double height = 5.9; // Double
boolean isStudent = true; // Boolean
char grade = 'A'; // Character

// Reference types
String name = "Alice"; // String object

Basic Operations

// Arithmetic operations
int x = 10 + 5; // Addition
int y = 10 * 5; // Multiplication

// String operations
String greeting = "Hello" + " " + "World";
int length = greeting.length();

Java Topics

Comprehensive coverage of Java programming concepts from beginner to advanced levels

Variables & Data Types

Learn about Java's static typing system with primitive types and object references.

// Primitive and reference types
int count = 10;
double price = 19.99;
String name = "Alice";
boolean isValid = true;

Control Flow

Master if-else statements, switch, loops (for, while, do-while) in Java.

// If-else example
if (age >= 18) {
  System.out.println("Adult");
} else {
  System.out.println("Minor");
}

Methods

Learn to define methods, work with parameters, return values, and method overloading.

// Method definition
public static int add(int a, int b) {
  return a + b;
}

// Method call
int result = add(5, 3);

Arrays & Collections

Work with Java's arrays and Collections Framework (List, Set, Map).

// Array and ArrayList examples
int[] numbers = {1, 2, 3};
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);

Loops & Iteration

Master for, while, do-while loops and enhanced for loops in Java.

// For loop example
for (int i = 0; i < 10; i++) {
  System.out.println(i);
}

// Enhanced for loop
for (String name : names) {
  System.out.println(name);
}

File I/O

Learn to read from and write to files using Java's I/O classes.

// Writing to a file
try (BufferedWriter writer = new BufferedWriter(
  new FileWriter("file.txt"))) {
  writer.write("Hello, World!");
}

// Reading from a file
try (BufferedReader reader = new BufferedReader(
  new FileReader("file.txt"))) {
  String line = reader.readLine();
}

Exception Handling

Understand Java's exception handling mechanism using try-catch-finally blocks.

// Try-catch example
try {
  int result = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Cannot divide by zero!");
} finally {
  System.out.println("Cleanup code");
}

Packages

Organize your code into packages and learn to use Java's standard library.

// Importing packages
import java.util.ArrayList;
import java.time.LocalDate;

// Using imported classes
LocalDate today = LocalDate.now();
ArrayList<String> list = new ArrayList<>();

OOP Concepts

Learn classes, objects, inheritance, polymorphism, and other OOP concepts.

// Class definition
public class Person {
  private String name;
  private int age;

  // Constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

Generics

Understand Java Generics for type-safe collections and methods.

// Generic class example
public class Box<T> {
  private T content;

  public void set(T content) {
    this.content = content;
  }

  public T get() {
    return content;
  }
}

Interfaces

Understand Java interfaces and their role in abstraction and polymorphism.

// Interface definition
public interface Drawable {
  void draw();
}

// Class implementing interface
public class Circle implements Drawable {
  public void draw() {
    System.out.println("Drawing a circle");
  }
}

Lambda Expressions

Learn about Java 8's lambda expressions and functional programming features.

// Lambda expression example
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Using lambda with forEach
names.forEach(name -> System.out.println(name));

// Using method reference
names.forEach(System.out::println);

Streams API

Master Java 8's Streams API for functional-style operations on collections.

// Stream operations example
List<String> filtered = names.stream()
  .filter(name -> name.startsWith("A"))
  .map(String::toUpperCase)
  .collect(Collectors.toList());

// Parallel stream
long count = names.parallelStream()
  .filter(name -> name.length() > 3)
  .count();

Multithreading

Introduction to concurrent programming in Java with threads and executors.

// Thread example
public class MyThread extends Thread {
  public void run() {
    System.out.println("Thread running");
  }
}

// Using ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task running"));

JUnit Testing

Learn to write unit tests for your Java code using JUnit framework.

// Simple JUnit test
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {
  @Test
  public void testAdd() {
    Calculator calc = new Calculator();
    assertEquals(5, calc.add(2, 3));
  }
}

What Can You Build with Java?

Java's versatility makes it suitable for a wide range of applications across different domains

Enterprise Applications

Build robust enterprise systems using frameworks like:

  • Spring Framework (Spring Boot)
  • Jakarta EE (formerly Java EE)
  • Hibernate (ORM)
// Simple Spring Boot controller
@RestController
public class HelloController {
  @GetMapping("/hello")
  public String hello() {
    return "Hello, World!";
  }
}

Android Apps

Java is one of the primary languages for Android development:

  • Native Android apps
  • Android SDK
  • Jetpack components
// Simple Android Activity
public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = findViewById(R.id.myButton);
    button.setOnClickListener(v -> {
      Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show();
    });
  }
}

Web Services

Build RESTful APIs and microservices with Java:

  • Spring Boot REST
  • JAX-RS (Jakarta REST)
  • gRPC
// Spring Boot REST controller
@RestController
@RequestMapping("/api/users")
public class UserController {
  @GetMapping
  public List<User> getAllUsers() {
    return userService.findAll();
  }

  @PostMapping
  public User createUser(@RequestBody User user) {
    return userService.save(user);
  }
}

Big Data

Java powers many big data technologies:

  • Apache Hadoop
  • Apache Spark
  • Apache Kafka
// Simple Spark job in Java
SparkConf conf = new SparkConf().setAppName("WordCount");
JavaSparkContext sc = new JavaSparkContext(conf);

JavaRDD<String> textFile = sc.textFile("hdfs://...");
JavaPairRDD<String, Integer> counts = textFile
  .flatMap(line -> Arrays.asList(line.split(" ")).iterator())
  .mapToPair(word -> new Tuple2<>(word, 1))
  .reduceByKey((a, b) -> a + b);

Desktop Applications

Build cross-platform desktop apps with Java:

  • JavaFX (Modern UI)
  • Swing (Legacy)
  • AWT (Basic)
// Simple JavaFX application
public class HelloFX extends Application {
  public void start(Stage stage) {
    Button btn = new Button("Click me!");
    btn.setOnAction(e -> System.out.println("Clicked!"));

    Scene scene = new Scene(new StackPane(btn), 300, 200);
    stage.setScene(scene);
    stage.show();
  }
}

Game Development

Create games with Java libraries and frameworks:

  • LibGDX (Cross-platform)
  • jMonkeyEngine (3D)
  • LWJGL (OpenGL bindings)
// Simple LibGDX game setup
public class MyGame extends ApplicationAdapter {
  SpriteBatch batch;
  Texture img;

  public void create() {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
  }

  public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(img, 0, 0);
    batch.end();
  }
}

Java Learning Path

A structured approach to mastering Java programming

1 Beginner Level

  • Java Syntax and Basics

    Variables, data types, operators, and basic I/O

  • Control Flow

    Conditionals, loops, and exception handling

  • Methods

    Defining methods, parameters, return values

  • Arrays & Strings

    Working with arrays and String class

2 Intermediate Level

  • Object-Oriented Programming

    Classes, objects, inheritance, polymorphism

  • Collections Framework

    List, Set, Map and their implementations

  • File I/O

    Reading and writing files

  • Generics

    Type-safe collections and methods

3 Advanced Level

  • Lambda Expressions

    Functional programming in Java

  • Streams API

    Functional-style operations on collections

  • Multithreading

    Concurrent programming with threads

  • JVM Internals

    Memory management, garbage collection

Ready to Master Java?

Join our Java Mastery course and get access to interactive exercises, real-world projects, and expert support to accelerate your learning.