Skip to content
Shop

CommunityJoin Our PatreonDonate

Sponsored Ads

Sponsored Ads

Java Syntax

Syntax of the Java programming language

Comparison Operators

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int x = 1;
        int y = 1;
        System.out.println(x == y);
        System.out.println(x != y);
        System.out.println(x > y);
        System.out.println(x >= y);
        System.out.println(x < y);
        System.out.println(x <= y);
    }
}

Logical Operators

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int temperature = 22;
        boolean isWarm = temperature > 20 && temperature < 30;
        System.out.println(isWarm);
        temperature = 12;
        isWarm = temperature > 20 && temperature < 30;
        System.out.println(isWarm);
    }
}
java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        // OR & NOT
        boolean hasHighIncome = true;
        boolean hasGoodCredit = true;
        boolean hasCriminalRecord = false;
        boolean isEligible = (hasHighIncome || hasGoodCredit) && !hasCriminalRecord;
    }
}

Conditional Statements

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int temp = 31;
        // if(temp > 30)
        //     System.out.println("It's a hot day");
        if(temp > 30){
            System.out.println("It's a hot day");
            System.out.println("Drink Water");
        } 
        else if(temp > 20)
            System.out.println("Beautiful day");
        else
            System.out.println("Cold day");
    }
}

Note

Braces are not required when we have a single statement.

Simplify Conditional Statements

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        if (income > 100_000){
            boolean hasHighIncome = true
        }
    }
}

Note

You can only declare variables inside code blocks, so the braces are required. hasHighIncome will be scoped to the if block, can't access outside

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        boolean hasHighIncome;
        if (income > 100_000)
            hasHighIncome = true
        else
            hasHighIncome = false
    }
}

Improve

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        boolean hasHighIncome = false;
        if (income > 100_000)
            hasHighIncome = true;
    }
}

Improve

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        boolean hasHighIncome = (income > 100_000);
        System.out.println(hasHighIncome);
    }
}

Ternary Operator

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        String className;
        if(income > 100_000)
            className = "First"
        else
            className = "Economy";
}
java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        String className = 'Economy';
        if(income > 100_000)
            className = "First"
}

Better

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int income = 120_000;
        String className = income > 100_000 ? "Economy" : "First";
        System.out.println(className);
    }
}

Inheritance

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

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

Interfaces

Any class that implements an interface MUST follow the convention of the interface.

Example 1

java
package com.example;
import com.example.Cat;

public class Main {
    public static void main(String[] args) {
        Cat myCat = new Cat();
        printThing(myCat);
    }

    static void printThing(Printable thing){
        thing.print();
    }
}
java
package com.example;

public interface Printable {
    void print();
    
}
java
package com.example;

public class Cat implements Printable{
    public String name;
    public int age;
    public Cat(){};
    public void print(){
        System.out.println("MEOW");
    }
}

Example 2

java
// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Example 3

java

class Animal{

}

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck extends Animal implements Flyable, Swimmable {
    public void fly() {
        System.out.println("Duck flying");
    }

    public void swim() {
        System.out.println("Duck swimming");
    }
}
java
public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        
        // Call the methods
        duck.fly();  // Outputs: Duck flying
        duck.swim(); // Outputs: Duck swimming
    }
}
java
public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        
        // Call methods
        duck.fly();  // Outputs: Duck flying
        duck.swim(); // Outputs: Duck swimming

        // Demonstrating polymorphism
        Animal animal = new Duck(); // Duck is an Animal
        Flyable flyable = new Duck(); // Duck is Flyable
        Swimmable swimmable = new Duck(); // Duck is Swimmable

        flyable.fly(); // Outputs: Duck flying
        swimmable.swim(); // Outputs: Duck swimming
    }
}

Lambda Expressions

Enums (Enumerations)

Note: Instantiating an enum doesn't require the new keyword

Example 1

java
import com.example.DaysEnum;
import com.example.DirectionsEnum;
public class Main {
    public static void main(String[] args) {
        DaysEnum day = DaysEnum.SUNDAY;

        // Get all possible values of the enum
        DaysEnum.values();

        // You can loop through the values
        for (DaysEnum myDay: DaysEnum.values()){
            System.out.println(myDay);
        }

        if (day == DaysEnum.SUNDAY){
            System.out.println("YES!");
        }

        System.out.println(DirectionsEnum.NORTH.description);
        System.out.println(DirectionsEnum.EAST.numeric);

    }
}
java
package com.example;

public enum DaysEnum {
    SUNDAY, MONDAY, TUESDAY, THURSDAY, FRIDAY, SATURDAY;
}
java
package com.example;

public enum DirectionsEnum {
    NORTH("up",0),
    SOUTH("down",1),
    EAST("right",2),
    WEST("left",3);

    final String description; //final makes sure people can't change the value
    final int numeric;

    DirectionsEnum(String description, int numeric){
        this.description = description;
        this.numeric = numeric;
    }
}

Example 2

java
public class Main {
  enum Level {
    LOW,
    MEDIUM,
    HIGH
  }

  public static void main(String[] args) {
    Level myVar = Level.MEDIUM; 
    System.out.println(myVar);
  }
}

Abstraction

java
// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Inner Classes

java
class OuterClass {
  int x = 10;

  private class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}

Polymorphism

java
class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

Generics

All files below will be in demo/src/main/java/com/example/ where demo is the name top level project folder.

java
package com.example;
import com.example.Printer;
import com.example.GenericPrinter;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        Printer printer = new Printer(null);
        GenericPrinter<Integer> genericPrinter = new GenericPrinter<>(null);
        printer.print("Hello");
        genericPrinter.print(2);
    }
}
java
package com.example;

public class Printer {
    String text;

    // Constructor
    public Printer(String text){
        this.text = text;
    }

    // Class Method
    public void print(String x){
        System.out.println(x);
    }
}
java
package com.example;

public class DynamicPrinter <T> {
    T text;

    // Constructor
    public DynamicPrinter(T text){
        this.text = text;
    }

    // Class Method
    public void print(T x){
        System.out.println(x);
    }
}

Exception Handling

java
package com.atm;
public class Main{
    public static void main(String[] args){

        try{
            validateAge(3);
        }catch (Exception e){
            System.out.println("The age is too low")
        }finally{
            System.out.println("I will always print")
        }
    }

    private static void validateAge(int age) throws Exception {
        if (age < 0){
            throw new Exception("Can't do that");
        }
    }
}

Custom Exceptions

java
package com.atm;
import com.atm.Atm;
import com.atm.Account;

public class Main{
    public static void main(String[] args){
        Account account = new Account("23423423","0000");
        account.balance = "23.5";
        try{
            account.withdraw(25);
        }catch(InsufficientFundsException e){
            System.out.println(e);
        }
    }
}
java
package.com.atm;

public class Account{
    String cardNumber;
    String pin;
    String balance = "0";

    Account(String cardNumber, String pin){
        this.cardNumber = cardNumber;
        this.pin = pin;
        System.out.println("ATM CONSTRUCTOR");
    }
    public void withdraw(double amount) throws InsufficientFundsException{
        double newAmount = Double.parseDouble(this.balance);
        try{
            newAmount -= amount;
            this.balance = String.valueOf(newAmount);
        }catch{
            throw new InsufficientFundsException();
        }
        if(amount > newAmount){
            throw new InsufficientFundsException("Insufficient funds");
        }

    }
}
java
class Java
java
package com.atm;

public class InsufficientFundsException extends Exception{
    public InsufficientFundsException(){};
    public InsufficientFundsException(String message){
        super(message);
    };
    public InsufficientFundsException(Throwable cause){
        super(cause);
    };
    public InsufficientFundsException(String message, Throwable cause){
        super(message,cause)
    };
}

https://www.youtube.com/watch?v=OIozDnGYqIU&t=611s

Multithreading

Stream API

Collection Framework

Your Turn

Details
java
package com.atm;
import com.atm.ATM;
import com.atm.Account;

public class Main{
    public static void main(String[] args){
        Account account = new Account("23423423","0000");
        account.balance = "23.5";
        System.out.println(account.checkBalance());
        account.deposit(600);
        System.out.println(account.checkBalance());
        System.out.println(account.pin);
        System.out.println(account.changePin("0000","1234"));
        System.out.println(account.pin);
        try{
            account.withdraw(25);
        }catch(InsufficientFundsException e){
            System.out.println(e);
        }
        System.out.println(account.balance);

        ATM machine = new ATM();
        machine.accounts.put("OZK", new Account("4839384",'4321'));
        System.out.println(machine.accounts);
        System.out.printl(machine.accounts.get("OZK"));
    }
}
java
package.com.atm;
import java.lang.annotation.Documented;

@Documented
@interface MyCustomAnnotation{
    String value() default "default value";
}

public class Account{
    String cardNumber;
    String pin;
    String balance = "0";

    Account(String cardNumber, String pin){
        this.cardNumber = cardNumber;
        this.pin = pin;
        System.out.println("ATM CONSTRUCTOR");
    }
    @MyCustomAnnotation(value="upskil")
    public double checkBalance(){
        return Double.parseDouble(this.balance);
    }
    /**
     * Deposit money into an account
     * @param amount the amount to be deposited
     * @return the new balance increased by the amount as a double
    */
    public double deposit(double amount){
        double newAmount = Double.parseDouble(this.balance);
        newAmount += amount;
        this.balance = String.valueOf(newAmount);
        return newAmount;
    }
    public void withdraw(double amount) throws InsufficientFundsException{
        double newAmount = Double.parseDouble(this.balance);
        try{
            newAmount -= amount;
            this.balance = String.valueOf(newAmount);
        }catch{
            throw new InsufficientFundsException();
        }
        if(amount > newAmount){
            throw new InsufficientFundsException("Insufficient funds");
        }
    }
    public String changePin(String oldPin, String newPin){
        if(oldPin.equals(this.pin)){
            this.pin = newPin;
            return "PIN UPDATED";
        }else{
            return "INCORRECT PIN";
        }
    }
    /**
     * @deprecated
     * This code is no longer used please remove or update before the end of the year
    */
    @Deprecated
    public void create(){
        System.out.println("NEW ACCOUNT CREATED");
    }
}
java
package com.atm;
import java.util.HashMap;
import java.util.Map;

public class ATM{
    Map<String,Account> accounts = new HashMap<>();

    public void addAccount(Account account){
        this.accounts.put("name",account);
    }

    public void authenticate(String cardNumber, String, pin){
        System.out.println(cardNumber);
        System.out.println(pin);
        System.out.println("You set up a new ATM")
    }
}
java
package com.atm;

public class InsufficientFundsException extends Exception{
    public InsufficientFundsException(){};
    public InsufficientFundsException(String message){
        super(message);
    };
    public InsufficientFundsException(Throwable cause){
        super(cause);
    };
    public InsufficientFundsException(String message, Throwable cause){
        super(message,cause)
    };
}
java
package com.atm;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Database{
    Database(){
        String DB_URL = "jdbc:sqlite:data.db"; // actually used full path to file instead :data.db
        try{
            Connection connection = DriverManager.getConnection(DB_URL);
            String sql = "SELECT * FROM user";
            Statement statement = connection.createStatement();

            ResultSet result = statement.executeQuery(sql);

            while(result.next()){
                String name = result.getString("name");
                System.out.printlin("Your name is:");
                System.out.println(name);
            }
        }catch(SQLException e){
            System.out.println("Error connecting to SQLITE DB");
            e.printStackTrace();
        }
    }
}
xml
<depenencies>
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.46.0.0</version>
    </dependency>
</depenencies>
Folder Structure
appname
    src
        main
            java
                com
                    atm
                        Main.java
                        ATM.java
                        Account.java
                        Database.java
                        InsufficientFundsException.java
            resources
        test
            java
    target
        classes
            com
                atm
                    Account.class
                    ATM.class
                    Database.class
                    InsufficientFundsException.class
                    Main.class
                    MyCustomAnnotation.class
        test-classes
data.db
pom.xml
sqlite-jdbc-3.46.0.0-javadoc.jar

Build a mortgage calculator

Instructions

  1. Principal
  2. Interest
  3. Period (years)

This program doesn't have input validation

Solution
java
package com.tutorialdoctor;
import java.text.NumberFormat;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        final byte MONTHS_IN_YEAR = 12; //no magic numbers
        final byte PERCENT = 100;
        Scanner scanner = new Scanner(System.in);

        System.out.print("Principal: ");
        int principal = scanner.nextInt();

        System.out.print("Annual Interest Rate: ");
        float annualInterest = scanner.nextFloat(); // no magic names
        float monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;


        System.out.print("Period (Years): ");
        int years = scanner.nextByte();
        int numberOfPayments = years * MONTHS_IN_YEAR;

        double mortgage = principal * (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments)) / (Math.pow(1 + monthlyInterest, numberOfPayments) - 1);

        String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
        System.out.println("Mortgage: " + mortgageFormatted);

    }
}

Resources

Note: add cards for related tech like juke, kafka, spring boot etc. Do this for other documentation as well