Java Programming

Learn Java, a class-based, object-oriented programming language designed for portability and cross-platform development.

What is Java?

Java is a high-level, class-based, object-oriented programming language that was designed to have as few implementation dependencies as possible. It follows the principle of "Write Once, Run Anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

Java was developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle) and was released in 1995. It's one of the most popular programming languages in use today, particularly for client-server web applications.

Where is Java Used?

  • Enterprise Applications: Java is widely used for building large-scale enterprise applications due to its robustness, security, and platform independence.
  • Android Development: Java is the primary language for Android app development.
  • Web Applications: Java technologies like Servlets, JSP, and frameworks like Spring are used to create dynamic web applications.
  • Financial Services: Many banking and financial institutions use Java for their transaction management systems.
  • Big Data Technologies: Tools like Hadoop and Apache Spark are written in Java.
  • Scientific Applications: Java is used in scientific applications for its reliability and performance.
  • Embedded Systems: Java is used in embedded systems like SIM cards, Blu-ray discs, etc.

Basic Java Syntax

Here's a simple "Hello, World!" program in Java:

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

In Java, every application begins with a class name, and the file name must match the class name. The main() method is the entry point of any Java program.

Variables and Data Types

Java is a statically-typed language, which means all variables must be declared before they can be used.

// Primitive data types
int myNum = 5;               // Integer (whole number)
float myFloatNum = 5.99f;    // Floating point number
char myLetter = 'D';         // Character
boolean myBool = true;       // Boolean
String myText = "Hello";     // String (not a primitive type)

// Reference data types
int[] myArray = {1, 2, 3};   // Array
ArrayList<String> list = new ArrayList<String>();  // ArrayList

Control Structures

Java supports the usual logical conditions from mathematics:

// If-else statement
int time = 20;
if (time < 18) {
    System.out.println("Good day.");
} else {
    System.out.println("Good evening.");
}

// Switch statement
int day = 4;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    // ... other cases
    default:
        System.out.println("Weekend");
}

// 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 j = 0;
do {
    System.out.println(j);
    j++;
} while (j < 5);

Object-Oriented Programming

Java is an object-oriented programming language. Everything in Java is associated with classes and objects.

// Class definition
public class Car {
    // Attributes
    String brand;
    String model;
    int year;
    
    // Constructor
    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }
    
    // Method
    public void drive() {
        System.out.println("Driving the " + brand + " " + model);
    }
}

// Creating objects
public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", "Corolla", 2020);
        myCar.drive();  // Outputs: Driving the Toyota Corolla
    }
}

Inheritance

Inheritance is an important pillar of OOP. It allows one class to inherit attributes and methods from another class.

// Parent class
class Vehicle {
    protected String brand = "Ford";
    public void honk() {
        System.out.println("Tuut, tuut!");
    }
}

// Child class
class Car extends Vehicle {
    private String modelName = "Mustang";
    
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.honk();  // Call method from Vehicle class
        System.out.println(myCar.brand + " " + myCar.modelName);
    }
}

Exception Handling

Java provides a robust exception handling mechanism to deal with runtime errors.

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            // Code that might throw an exception
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[10]);  // This will throw an exception
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds!");
        } catch (Exception e) {
            System.out.println("Something went wrong: " + e.getMessage());
        } finally {
            System.out.println("The 'try catch' block is finished.");
        }
    }
}

Collections Framework

Java provides a Collections Framework that consists of interfaces and classes to store and manipulate groups of objects.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class CollectionsExample {
    public static void main(String[] args) {
        // ArrayList
        ArrayList<String> cars = new ArrayList<String>();
        cars.add("Volvo");
        cars.add("BMW");
        cars.add("Ford");
        System.out.println(cars);  // [Volvo, BMW, Ford]
        
        // HashMap
        HashMap<String, String> capitalCities = new HashMap<String, String>();
        capitalCities.put("England", "London");
        capitalCities.put("Germany", "Berlin");
        System.out.println(capitalCities);  // {England=London, Germany=Berlin}
        
        // HashSet
        HashSet<String> names = new HashSet<String>();
        names.add("John");
        names.add("Mary");
        names.add("John");  // Duplicate, will not be added
        System.out.println(names);  // [John, Mary]
    }
}

File Handling

Java provides several classes to read and write files.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileHandlingExample {
    public static void main(String[] args) {
        try {
            // Create a file
            File myFile = new File("filename.txt");
            if (myFile.createNewFile()) {
                System.out.println("File created: " + myFile.getName());
            } else {
                System.out.println("File already exists.");
            }
            
            // Write to a file
            FileWriter myWriter = new FileWriter("filename.txt");
            myWriter.write("Files in Java are awesome!");
            myWriter.close();
            
            // Read from a file
            Scanner myReader = new Scanner(myFile);
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                System.out.println(data);
            }
            myReader.close();
            
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Learning Resources