Dark mode

Java Notes

A popular object-oriented programming language

Introduction to Java

Java is a widely-used object-oriented programming language known for its "write once, run anywhere" capability. It's used for developing everything from mobile apps to enterprise-level applications.

Java Basics

What is Java?

Java is a popular, high-level programming language developed by Sun Microsystems (now owned by Oracle). Since its release in 1995, Java has evolved to become one of the most widely used programming languages in the world.

Key features of Java include:

  • Platform Independence: Java programs run on the Java Virtual Machine (JVM), allowing them to work on any device or operating system that has a JVM installed ("Write Once, Run Anywhere")
  • Object-Oriented: Java is designed around objects that contain both data and methods
  • Simple and Familiar: Java's syntax is similar to C/C++ but removes complex features like pointers
  • Robust and Secure: Strong memory management, compile-time checking, and runtime checking make Java programs reliable
  • Multithreaded: Java supports concurrent programming for developing efficient applications
Example
// Your first Java program
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Setting Up Java

To start programming in Java, you need to set up the Java Development Kit (JDK). The JDK includes everything you need to develop and run Java applications, including the Java Runtime Environment (JRE) and development tools.

Step 1: Download and Install the JDK

Visit the Oracle website or use an open-source alternative like Adoptium (formerly AdoptOpenJDK) to download the appropriate JDK for your operating system.

Step 2: Set Up Environment Variables

Configure your system's environment variables to include Java:

  • Set JAVA_HOME to point to your JDK installation directory
  • Add the JDK's bin directory to your system PATH

Step 3: Verify Installation

Open a terminal or command prompt and type:

Example
// Check the Java version
java -version

// Check the Java compiler version
javac -version

Basic Syntax

Java has a C-like syntax with some important rules and conventions:

File Structure

  • Each Java file should contain one public class
  • The file name must match the public class name (e.g., HelloWorld.java contains public class HelloWorld)
  • Each statement ends with a semicolon (;)

Main Method

The main method is the entry point for Java applications:

  • It must be declared as public static void main(String[] args)
  • The program execution begins at this method

Case Sensitivity

Java is case-sensitive, meaning Hello, hello, and HELLO are all different identifiers.

Comments

Java supports single-line and multi-line comments:

Example
// This is a single-line comment

/* This is a 
   multi-line comment */

/**
 * This is a documentation comment (Javadoc)
 * @author Your Name
 */

public class SyntaxExample {
    public static void main(String[] args) {
        // Print a message to the console
        System.out.println("Java syntax example");
        
        // Variable declaration and assignment
        int number = 10;
        String message = "Hello, Java!";
        
        // Print variables
        System.out.println(message);
        System.out.println("The number is: " + number);
    }
}

Variables and Data Types

Variables in Java are containers that hold values used in a program. Every variable has a data type that determines what kind of values it can store.

Declaring Variables

The basic syntax for declaring a variable is:

dataType variableName = value;

Primitive Data Types

Java has eight primitive data types:

  • byte: 8-bit integer (-128 to 127)
  • short: 16-bit integer (-32,768 to 32,767)
  • int: 32-bit integer (-231 to 231-1)
  • long: 64-bit integer (with 'L' suffix, e.g., 100L)
  • float: 32-bit floating-point (with 'f' suffix, e.g., 3.14f)
  • double: 64-bit floating-point (default for decimal values)
  • boolean: true or false
  • char: Single 16-bit Unicode character ('A', '1', etc.)

Reference Data Types

Reference types store references to objects:

  • String: Sequence of characters
  • Arrays
  • Classes
  • Interfaces

Variable Naming Rules

  • Names can contain letters, digits, underscore (_), and dollar sign ($)
  • Names must begin with a letter, underscore, or dollar sign
  • Names cannot be Java keywords
  • Names are case-sensitive
Example
// Primitive data types
byte smallNumber = 127;
short mediumNumber = 32767;
int standardNumber = 2147483647;
long largeNumber = 9223372036854775807L;
float decimalNumber = 3.14f;
double preciseNumber = 3.141592653589793;
boolean isJavaFun = true;
char singleCharacter = 'A';

// Reference data types
String message = "Hello, Java!";
int[] numbers = {1, 2, 3, 4, 5};

// Constants (final variables)
final double PI = 3.14159;

// Printing variables
System.out.println("byte: " + smallNumber);
System.out.println("short: " + mediumNumber);
System.out.println("int: " + standardNumber);
System.out.println("long: " + largeNumber);
System.out.println("float: " + decimalNumber);
System.out.println("double: " + preciseNumber);
System.out.println("boolean: " + isJavaFun);
System.out.println("char: " + singleCharacter);
System.out.println("String: " + message);
System.out.println("First element in array: " + numbers[0]);
Result
byte: 127
short: 32767
int: 2147483647
long: 9223372036854775807
float: 3.14
double: 3.141592653589793
boolean: true
char: A
String: Hello, Java!
First element in array: 1

Control Flow

Conditional Statements

Conditional statements allow your program to make decisions based on certain conditions. Java provides several types of conditional statements:

if Statement

The if statement executes a block of code if a specified condition is true.

if-else Statement

The if-else statement executes one block of code if a condition is true and another block if the condition is false.

if-else-if Statement

The if-else-if statement chain allows you to check multiple conditions in sequence.

switch Statement

The switch statement selects one of many code blocks to be executed based on the value of an expression.

Example
// if statement
int age = 20;
if (age >= 18) {
    System.out.println("You are an adult.");
}

// if-else statement
int time = 22;
if (time < 12) {
    System.out.println("Good morning.");
} else {
    System.out.println("Good day.");
}

// if-else-if statement
int score = 85;
if (score >= 90) {
    System.out.println("Grade: A");
} else if (score >= 80) {
    System.out.println("Grade: B");
} else if (score >= 70) {
    System.out.println("Grade: C");
} else if (score >= 60) {
    System.out.println("Grade: D");
} else {
    System.out.println("Grade: F");
}

// switch statement
int day = 4;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 7:
        System.out.println("Sunday");
        break;
    default:
        System.out.println("Invalid day");
}
Result
You are an adult.
Good day.
Grade: B
Thursday

Loops

Loops allow you to execute a block of code repeatedly. Java provides several types of loops:

for Loop

The for loop repeats a block of code a specified number of times. It consists of an initialization, a condition, and an increment/decrement part.

while Loop

The while loop repeats a block of code as long as a specified condition is true. The condition is checked before executing the loop body.

do-while Loop

The do-while loop is similar to the while loop, but it checks the condition after executing the loop body, ensuring the loop runs at least once.

for-each Loop

The enhanced for loop (also known as the for-each loop) is used to iterate through elements in an array or collection.

Example
// for loop
System.out.println("For loop:");
for (int i = 0; i < 5; i++) {
    System.out.println("Count: " + i);
}

// while loop
System.out.println("\nWhile loop:");
int j = 0;
while (j < 5) {
    System.out.println("Count: " + j);
    j++;
}

// do-while loop
System.out.println("\nDo-while loop:");
int k = 0;
do {
    System.out.println("Count: " + k);
    k++;
} while (k < 5);

// for-each loop
System.out.println("\nFor-each loop:");
String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
for (String fruit : fruits) {
    System.out.println("Fruit: " + fruit);
}

// break statement
System.out.println("\nBreak example:");
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exit the loop when i equals 5
    }
    System.out.println("Count: " + i);
}

// continue statement
System.out.println("\nContinue example:");
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.println("Odd number: " + i);
}
Result
For loop:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

While loop:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Do-while loop:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

For-each loop:
Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
Fruit: Elderberry

Break example:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Continue example:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

Object-Oriented Programming

Classes and Objects

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. In Java, everything is associated with classes and objects.

Classes

A class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that objects of that type will have.

Objects

An object is an instance of a class. When a class is defined, no memory is allocated until an object is instantiated using the new keyword.

Constructors

Constructors are special methods used to initialize objects. They have the same name as the class and are called when a new object is created.

Access Modifiers

Access modifiers control the visibility of classes, methods, and fields:

  • public: Accessible from any class
  • private: Accessible only within the same class
  • protected: Accessible within the same package and by subclasses
  • Default (no modifier): Accessible only within the same package
Example
// Define a class
public class Person {
    // Fields (attributes)
    private String name;
    private int age;
    
    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Default constructor
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }
    
    // Methods (behaviors)
    public void sayHello() {
        System.out.println("Hello, my name is " + name + ".\nI am " + age + " years old.");
    }
    
    // Getters and setters
    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;
        }
    }
}

// Using the class
public class Main {
    public static void main(String[] args) {
        // Create objects
        Person person1 = new Person("John", 25);
        Person person2 = new Person();
        
        // Call methods
        person1.sayHello();
        
        // Use getters and setters
        person2.setName("Jane");
        person2.setAge(30);
        System.out.println(person2.getName() + " is " + person2.getAge() + " years old.");
    }
}
Result
Hello, my name is John.
I am 25 years old.
Jane is 30 years old.

Inheritance

Inheritance is a mechanism in which one class acquires the properties and behaviors of another class. It's one of the key concepts in object-oriented programming.

Base Class (Parent or Superclass)

The class whose features are inherited is called the base class.

Derived Class (Child or Subclass)

The class that inherits the features of another class is called the derived class.

Extending Classes

In Java, you use the extends keyword to implement inheritance.

Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass.

super Keyword

The super keyword refers to the parent class and is used to call the parent class's methods or constructors.

Example
// Parent class
public class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void eat() {
        System.out.println(name + " is eating.");
    }
    
    public void sleep() {
        System.out.println(name + " is sleeping.");
    }
    
    public String getName() {
        return name;
    }
}

// Child class inheriting from Animal
public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // Call the parent constructor
        this.breed = breed;
    }
    
    // Method overriding
    @Override
    public void eat() {
        System.out.println(getName() + " the " + breed + " is eating dog food.");
    }
    
    // New method specific to Dog
    public void bark() {
        System.out.println(getName() + " says: Woof! Woof!");
    }
    
    public String getBreed() {
        return breed;
    }
}

// Using inheritance
public class Main {
    public static void main(String[] args) {
        // Create an Animal object
        Animal animal = new Animal("Generic Animal");
        animal.eat();
        animal.sleep();
        
        // Create a Dog object
        Dog dog = new Dog("Buddy", "Golden Retriever");
        dog.eat();  // Calls the overridden method
        dog.sleep();  // Calls the inherited method
        dog.bark();  // Calls the specific method
        
        // Polymorphism (treating a Dog as an Animal)
        Animal pet = new Dog("Max", "German Shepherd");
        pet.eat();  // Calls Dog's eat() method
        pet.sleep();  // Calls Animal's sleep() method
        // pet.bark();  // Error: Animal doesn't have bark() method
    }
}
Result
Generic Animal is eating.
Generic Animal is sleeping.
Buddy the Golden Retriever is eating dog food.
Buddy is sleeping.
Buddy says: Woof! Woof!
Max the German Shepherd is eating dog food.
Max is sleeping.