DEV Community

Cover image for Java Notes
David Titilayo
David Titilayo

Posted on

Java Notes

Run Java from Terminal

$ javac App.java && java App

Enter fullscreen mode Exit fullscreen mode

Javac command is used to compile the Java code to byte code(App.class) while "&&" is a logical AND connector and "java" command runs the byte code

Hello World

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

Enter fullscreen mode Exit fullscreen mode

Variables

Variables are just like containers that holds some values.

public class Main{
    public static void main(String [] args){
         int age = 10;
         String name = "Davet";
         boolean isCorrect = true;
         float height = 6.4F;
         double weight = 6.0;
         char gender = 'M';
         byte a = 1;
         long number = 2334323423432423L;
    }
}
Enter fullscreen mode Exit fullscreen mode

in the above code, various variables are declared and values were assigned to them.

String Methods

These are methods that can be applied to strings for manipulation or other purposes.

   public class Main{
   public static void main(String [] args){
        String name = "Davet"; 
        name.toLowerCase(); // david
        name.toUpperCase();//  DAVID
        name.trim();               // removes spaces at start & end
        name.replace("a", "b");    // replaces characters
   }
}

Enter fullscreen mode Exit fullscreen mode

Enum

Enum is a like a container used to save some sets of constant value.

 public class Main {
    public static void main(String[] args) {
        GRADE fail = GRADE.F;
        System.out.println(fail);
    }

    enum GRADE {
        A,
        B,
        C,
        D,
        E,
        F
    }
}
Enter fullscreen mode Exit fullscreen mode

While Loop

The while loop is used to continually run some lines of code while a certain condition remains true.

public class Main {
    public static void main(String[] args) {
        boolean isCorrect = true;
        int count = 0;
        while (count < 10){
            System.out.println("The answer you picked is correct");
            count++;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Function

A function is a set of code that is used to perform a particular function. A function usually needs to be invoked before it can be used.

public class Main {
    public static void main(String[] args) {
        introduce();

    }


    public static void introduce() {
        String name = "David";
        String jobDescription = "Backend Developer";
        System.out.printf("I am %s, a %s", name, jobDescription);
    }
}
Enter fullscreen mode Exit fullscreen mode

Atomicity

Atomicity is a concept that explains either all operations are carried out successfully or was not carried out at all.

import java.util.concurrent.AtomicInteger;
public class Main {
    static int count = 1;

    synchronized static void increment() {
        count++;
    }

    public static void main(String[] args) {
        increment();
        System.out.println(count); //prints 2
         //Using Atomic Integer
         AtomicInteger atomicint = new AtomicInteger(1); // Create a new instance of Atomic integer and initialise it with 1.
         System.out.println(atomicInt.getAndIncrement()); // prints 1
         System.out.println(atomicInt.Incrementandget()); // prints 3
         System.out.println(atomicInt.get()); prints 3


    }


}
Enter fullscreen mode Exit fullscreen mode

Array

Array is like a container to save data of same data types

public class Main{
    public static void main(String[] args){
         int[] myFavNums = {1, 3, 5, 7, 9, 8};
         for( int i: myFavNums){
          System.out.print(i);
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

Class and Object

A class is a blueprint(template) of an object. An object is an instance of a class.

public class Main{
    public static void main(String[] args){
        Person person1 = new Person("Grace", 12);
        person1.introduce();

    }

}
class Person{
    String name;
    int age;

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

    void introduce(){
        System.out.println("My name is " + name + " and I am " + age + " old");
    }

}
Enter fullscreen mode Exit fullscreen mode

Inheritance

Inheritance is one of the core pillars of Object-Oriented Programming that lets a child class inherit the properties and methods of its parent class.

public class Main {
    public static void main(String[] args) {

        Person personOne = new Person("joe", 78);
        personOne.heartBeats();

        Baby babyOne = new Baby("baby Joe", 1);
        babyOne.heartbeats();
    }
}

class Person {
    private String name;
    private int age;

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

    void heartBeats() {
        System.out.println("My heart is functioning");
    }
}

class Baby extends Person {
    private String name;
    private int age;

    public Baby(String name, int age) {
        super(name, age); // call parent constructor
        this.name = name;
        this.age = age;
    }

    void heartbeats() {
        System.out.println("Name is " + name + " and age is " + age);
        super.heartBeats();
    }
}

Enter fullscreen mode Exit fullscreen mode

Interface

An interface is a reference type in Java, similar to a class, that can contain abstract methods.

public class Main {
    public static void main(String[] args) {

        Person personOne = new Person("David");
        personOne.scream();
    }

}

interface Shout {
    void scream();
}

class Person implements Shout {

    private final String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public void scream() {
        System.out.println(name + " screamed, Ahhhhh!!!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Static Method

A static method belongs to the class itself, not to any specific object created from the class.

public class Main {
    public static void main(String [] args){
        StaticDisplay.myName("David");
    }



}

class StaticDisplay{
    static void myName(String name){
        System.out.println("My name is " + name) ;
    }


}
Enter fullscreen mode Exit fullscreen mode

This Keyword

The this keyword refers to the current object of a class.

class Student {
    String name;
    int age;

    // Constructor
    Student(String name, int age) {
        this.name = name; // 'this.name' refers to instance variable
        this.age = age;   // 'this.age' refers to instance variable
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("David", 20);
        s1.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Constructor Overloading

Constructor overloading is a concept in Java where a class has more than one constructor with different parameter lists.

class Student {
    String name;
    int age;

    // Constructor 1
    Student(String name, int age) {
        this.name = name; // 'this.name' refers to instance variable
        this.age = age;   // 'this.age' refers to instance variable
    }
   // Constructor 2
   Student(String name) {
        this.name = name; // 'this.name' refers to instance variable
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("David", 20);
        s1.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Polymorphism(Method Overriding)

Polymorphism is an OOP concept where the same method name can perform different actions based on the object calling it.
Method overriding is a type of polymorphism where a child class provides its own implementation of a method defined in the parent class.

class Animal {

    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {

    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {

        Animal a = new Dog(); // Polymorphism
        a.sound();           // Calls Dog's version
    }
}
Enter fullscreen mode Exit fullscreen mode

Abstraction
Abstraction is an OOP concept that focuses on showing only essential features while hiding implementation details. Abstract class cannot be instanciated, it has to be inherited by a child class to implement it. Abstract methods don't have body.

abstract class Animal {

    abstract void sound();
}

class Dog extends Animal {


    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {

        Animal a = new Dog(); // Polymorphism
        a.sound();           // Calls Dog's version
    }
}
Enter fullscreen mode Exit fullscreen mode

Super() Keyword

The super keywod refers to the parent class.

class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

class Dog extends Animal {
    void eat() {
        System.out.println("Dog eats bones");
    }

    void showEat() {
        eat();         // Calls Dog's eat()
        super.eat();   // Calls Animal's eat()
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.showEat();
    }
}
Enter fullscreen mode Exit fullscreen mode

Wrapper Classes

Wrapper classes convert primitive data types into Reference data types.

Primitive Wrapper
int Integer
double Double
char Character
boolean Boolean
Integer age = 20;
Enter fullscreen mode Exit fullscreen mode

String Builder

StringBuilder is mutable, allowing efficient modification of text using methods like append, insert, delete, replace, and reverse.
In contrast, String is immutable, so any change creates a new object, making StringBuilder faster for repeated string operations.

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");

        sb.append(" World");       // Hello World
        sb.insert(6, "Java ");     // Hello Java World
        sb.replace(6, 10, "C++");  // Hello C++ World
        sb.delete(5, 9);           // HelloWorld
        sb.reverse();              // dlroWolleH

        System.out.println(sb.toString());
    }
}
Enter fullscreen mode Exit fullscreen mode

Null Pointer

A null pointer occurs when a reference variable does not point to any object, i.e., it has the value null.

public class Main {
    public static void main(String[] args) {
        String str = null;  // str points to nothing

        // This will cause NullPointerException
        // System.out.println(str.length());

        if (str != null) {
            System.out.println(str.length()); // Safe check
        } else {
            System.out.println("String is null");
        }
        System.out.println(str.length()); //💥 NullPointerException
    }
}
Enter fullscreen mode Exit fullscreen mode

List

A List in Java is an ordered collection, meaning elements are stored in the order they are inserted, and it allows duplicate elements.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();

        // Adding elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple"); // duplicate allowed

        // Accessing elements
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Hash Map

Hash Map is an ordered collection that stores key-value pairs.
Keys must be unique, but values can be duplicated.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();

        // Adding key-value pairs
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Orange");
        map.put(4, "Apple");  // duplicate value allowed

        // Accessing elements
        System.out.println("Value for key 2: " + map.get(2));

        // Iterating over HashMap
        for (Integer key : map.keySet()) {
            System.out.println(key + " -> " + map.get(key));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

LinkedMap

LinkedHashMap is like a HashMap, but it maintains the insertion order of keys.

import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();

        map.put(3, "Orange");
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(4, "Apple"); // duplicate value allowed

        for (Integer key : map.keySet()) {
            System.out.println(key + " -> " + map.get(key));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Stream

A Stream is a sequence of elements from a data source (like a collection, array, or generator) that allows you to perform some operations.

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Apple", "Banana", "Orange", "Apple");

        // Stream example: filter and print unique fruits
        fruits.stream()
              .distinct()                // remove duplicates
              .filter(f -> f.startsWith("A")) // filter fruits starting with 'A'
              .forEach(System.out::println);  // print result
    }
}

Enter fullscreen mode Exit fullscreen mode

Exception

An Exception in Java is an event that occurs during the execution of a program that disrupts the normal flow of instructions. it’s an error that happens while the program is running.

public class Main {
    public static void main(String[] args) {

        try {
            int response = 10 / 0;
            System.out.println(response);
        }catch (ArithmeticException e){
            System.out.println("Oops!, Error");
        }
    }

}


Enter fullscreen mode Exit fullscreen mode

I/O

IO (Input/Output) in Java refers to the process of reading data from a source (input) and writing data to a destination (output).
Sources and destinations can be files, keyboards, memory, networks, etc.

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\CAPTAIN ENJOY\\Downloads\\JavaNote\\src\\text.txt";

        // Reading the file
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
        }

        // Appending to the file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { // 'true' = append mode
            writer.newLine(); // optional: start on a new line
            writer.write("ner");
        } catch (IOException e) {
            System.out.println("Write error: " + e.getMessage());
        }
    }
}



Enter fullscreen mode Exit fullscreen mode

Lambda

It's more like an arrow function in javaScript. it's an anonymous function.

(int a, int b) -> a + b       // returns sum
x -> x * 2                    // multiplies by 2
() -> System.out.println("Hi") // no parameters

Enter fullscreen mode Exit fullscreen mode

Constants

The "final" keyword is used to declare constants.

public class Main {
    public static void main(String[] args) {

        final int MAX_ATTEMPTS = 909090;
        // MAX_ATTEMPTS = 200; // ❌ Will cause error
        System.out.println(MAX_ATTEMPTS);
    }
}
Enter fullscreen mode Exit fullscreen mode

SOLID

SOLID is an acronym for five key principles of object-oriented design that make software more maintainable, flexible, and scalable.

S – Single Responsibility Principle (SRP)

A class should have only one reason to change, i.e., it should do one thing only.

Example:

Invoice class → only handles invoice data.

InvoicePrinter class → only handles printing invoices.

class UserService {
    void registerUser(User user) { /* ... */ }
}

class EmailService {
    void sendWelcomeEmail(User user) { /* ... */ }
}


Enter fullscreen mode Exit fullscreen mode

Open/Closed Principle (OCP)

Software entities (classes, methods, modules) should be open for extension but closed for modification.

  • Open for extension → You should be able to add new functionality without changing existing code.

  • Closed for modification → You should not modify existing, tested code, because that risks introducing bugs.

// Payment interface (abstraction)
interface Payment {
    void pay(double amount);
}

// Existing class
class CreditCardPayment implements Payment {
    public void pay(double amount) {
        System.out.println("Paid " + amount + " with Credit Card");
    }
}

// Adding a new functionality: PayPal
class PayPalPayment implements Payment {
    public void pay(double amount) {
        System.out.println("Paid " + amount + " via PayPal");
    }
}

// Checkout class depends on abstraction
class Checkout {
    Payment payment;
    Checkout(Payment payment) { this.payment = payment; }
    void process(double amount) { payment.pay(amount); }
}

public class Main {
    public static void main(String[] args) {
        Checkout checkout1 = new Checkout(new CreditCardPayment());
        checkout1.process(100);

        Checkout checkout2 = new Checkout(new PayPalPayment()); // new payment type added WITHOUT changing existing Checkout class
        checkout2.process(200);
    }
}

### L - Liskov Substition Principle
Subtypes should replace base types without breaking the program.

Enter fullscreen mode Exit fullscreen mode


java
class Bird { void fly() {} }
class Sparrow extends Bird {}
class Penguin extends Bird {} // Penguins cannot fly

Bird bird = new Sparrow(); // Works fine
Bird bird = new Penguin(); // Violates LSP if fly() is called


### I - Interface Segregation Principle
Don’t force classes to implement unnecessary methods.
Bad:
Enter fullscreen mode Exit fullscreen mode


java
interface Animal{
void fly(); //Animal can't fly
}
interface Bird { void fly(); } //Good Interface



### D — Dependency Inversion Principle (DIP)
Depends on Abstraction not concrete class

Enter fullscreen mode Exit fullscreen mode


java
interface Payment { void pay(); }

class CreditCardPayment implements Payment {
public void pay() { System.out.println("Paid with Credit Card"); }
}

class Checkout {
Payment payment;
Checkout(Payment payment) { this.payment = payment; }
void process() { payment.pay(); }
}

public class Main {
public static void main(String[] args) {
Checkout c = new Checkout(new CreditCardPayment());
c.process();
}
}




Enter fullscreen mode Exit fullscreen mode

Top comments (0)