Skip to content
Shop

CommunityJoin Our PatreonDonate

Sponsored Ads

Sponsored Ads

The Basics

Data

Primitive types store strings or whole numbers

typebytesrange
byte1[-128, 127]
short2[-32K, 32K]
int4[-2B, 2B]
long8
float4
double8
char2A, B, C...
boolean1true / false
java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int viewsCount 3_123_456_789;
        float price = 10.99
        System.out.println(viewsCount)
    }
}

Note

Integer number too large (change to long).

Error default numbers seen as integers. Java compiler ses as integer. Add L as a suffix. Seen as double add suffix for float F

java
int viewsCount 3_123_456_789L;
float price = 10.99F;

Reference types (non-primitive types)

Used for storing complex objects.

java
package com.tutorialdoctor;

import java.util.Date;

public class Main{
    public static void main(String[] args){
        byte age = 30;
        Date now = new Date();
        now.getTime()
        System.out.println(now);
    }
}

Note

Primitive types don't have members like .getTime()

Variables

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String name = "Tutorial Doctor";
        int myAge = 30;
        double avogadro = 6.022;
        boolean wifi = true;
    }
}

Constants

Use final to treat a variable as a constant. Use all all caps for constant names.

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        final float PI = 3.14f;
    }
}

Statements

java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        String name = "Tutorial Doctor";
        System.out.print("Hello " + name);
    }
}
java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.print("Age:");
        byte age = scanner.nextByte();
        System.out.println("You are " + age)
    }
}

Strings

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String message = new String("Hello World") //redundant
        String message = "Hello World" //shorthand
        System.out.println(message)
    }
}

String Methods

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String message = "Hello World" + "!!"
        System.out.println(message);
        message.endsWith("!!");
        message.endsWith("!!");
        message.length();
        message.indexOf("H");
        message.replace(target:"!", replacement:"*");
        message.toLowerCase();
        message.toUpperCase();
        message.trim() //gets rid of white space;
    }
}

Note

replace() and toLowerCase() don't modify original string (returns a new string). Strings are immutable (you cannot change them).

Escape

Arrays

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int[] = numbers = new int[5];
        numbers[0] = 1
        numbers[1] = 2
        numbers[10] = 3 //exception/errror
        System.out.println(numbers); // weird string
        
    }
}

Print the array

java
package com.tutorialdoctor;

import java.utils.Arrays;

public class Main{
    public static void main(String[] args){
        int[] = numbers = new int[5];
        numbers[0] = 1
        numbers[1] = 2
        System.out.println(Arrays.toString(numbers));
    }
}

Note

Other values are set to 0 by default. if it were a boolean array, all values would default to false. String array, all items initialized to an empty string ''

Another way length and sort.

java
package com.tutorialdoctor;

import java.utils.Arrays;

public class Main{
    public static void main(String[] args){
        int[] = numbers = { 2, 3, 5, 1, 4 }; 
        System.out.println(numbers.length());
        System.out.println(Arrays.sort(numbers));
    }
}

Note

arrays have fixed size/length

Loops

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        for (int i = 0; i < 5; i++){
            System.out.println("Hello World " + i);
        }

        for (int i = 5; i > 5; i--){
            System.out.println("Hello World " + i);
        }
    }
}
java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int i = 5;
        while (i > 0){
            System.out.println("Hello World " + i);
            i--;
        }
    }
}

Note

If you know how many times you want to repeat, use a for loop, if you don't, use while loop.

For Loop

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        for (int i = 0; i < 5; i++){
            System.out.println("Hello World " + i);
        }

        for (int i = 5; i > 5; i--){
            System.out.println("Hello World " + i);
        }
    }
}

While Loop

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int i = 5;
        while (i > 0){
            System.out.println("Hello World " + i);
            i--;
        }
    }
}

::info Note If you know how many times you want to repeat, use a for loop, if you don't, use while loop. :::

java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while(!input.equals("quit")) {
            System.out.println("Input: ");
            input = scanner.next().toLowerCase();
            System.out.println(input)
        }
    }
}

Do While Loops

java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while(!input.equals("quit")) {
            System.out.println("Input: ");
            input = scanner.next().toLowerCase();
            System.out.println(input)
        }

        do{
            System.out.println("Input: ");
            input = scanner.next().toLowerCase();
            System.out.println(input)
        }while(!input.equals("quit"));
    }
}

Note

Do-while loops get executed at least once, even if the condition is false. These loops are rarely used.

Break and Continue

Break terminates a loop. Continue moves control to the beginning of the loop.

java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while(!input.equals("quit")) {
            System.out.println("Input: ");
            input = scanner.next().toLowerCase();
            if(!input.equals("quit"))
                System.out.println(input)
        }
    }
}
java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while(!input.equals("quit")) {
            System.out.println("Input: ");
            input = scanner.next().toLowerCase();
            if(input.equals("pass"))
                continue;
            if(input.equals("quit"))
                break;
            System.out.println(input)
        }
    }
}

Better

java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while(true) {
            System.out.println("Input: ");
            input = scanner.next().toLowerCase();
            if(input.equals("pass"))
                continue;
            if(input.equals("quit"))
                break;
            System.out.println(input)
        }
    }
}

Note

Without break, you will get an infinite loop.

For-Each Loop

To iterate over arrays or collections

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String[] fruits = {"Apple","Mango","orange"};

        for (int i = 0; i < fruits.length; i++)
            System.out.println(fruits[i]);

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

        for (int i = fruits.length ; i > 0; i--)
            System.out.println(fruits[i]); //not working
    }
}

Note

Can only loop forward and not backward.

Mortgage Calculator

Solution

https://youtu.be/eIrMbAQSU34?list=PLTjRvDozrdlxCs_3gaqd120LcGxmfe8rG&t=8871

Multiple objects

java
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj1 = new Main();  // Object 1
    Main myObj2 = new Main();  // Object 2
    System.out.println(myObj1.x);
    System.out.println(myObj2.x);
  }
}

Multiple classes

java
public class Main {
  int x = 5;
}

class Second {
  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}
java

public class Person {
  private String name; // private = restricted access

  // Getter
  public String getName() {
    return name;
  }

  // Setter
  public void setName(String newName) {
    this.name = newName;
  }
}

Functions

java
class Car {
  public static void main(String[] args) {
    public static void sayHello(String name){
        System.out.println("Hello " + name);
    }

    sayHello("John");
    sayHello("Sandy");
  }
}

Classes

java
public class Main {
  int x = 5;
}
java
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}
java
class Vehicle {
  protected String brand = "Ford";
  public void honk() {
    System.out.println("Tuut, tuut!");
  }
}

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

    Car myCar = new Car();
    myCar.honk();
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

Math Class

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        //overloaded, implemented twice
        int result = Math.round(1.1F); 
        System.out.println(result);

        int result = (int)Math.ceil(1.1F); 
        System.out.println(result);

        int result = (int)Math.floor(1.1F); 
        System.out.println(result);

        int result = (int)Math.max(1,2); 
        System.out.println(result);

        int result = (int)Math.min(1,2); 
        System.out.println(result);

        double result = Math.random(); 
        System.out.println(result);

        double result = Math.random() * 100; 
        System.out.println(result);

        int result = (int) Math.round(Math.random() * 100); 
        System.out.println(result);

        int result = (int) Math.random() * 100; 
        System.out.println(result); //error

        int result = (int) (Math.random() * 100); 
        System.out.println(result);
    }
}

Packages

import package.name.Class;   // Import a single class
import package.name.*;   // Import the whole package
java
package.com.upskil;
import com.upskil.Something;

class Main {
  public static void main(String[] args) {
    Something something = new Something;
    something.create();
  }
}
java
package.com.upskil;
class Something {
  public void create(){
    System.out.println("Something was created!")
  }
}

Dependencies

xml
<depenencies>
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.46.0.0</version>
    </dependency>
</depenencies>

Memory Management

Primitive type memory management

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        byte x = 1;
        byte y = x;
    }
}

Note

x and y are at two different memory locations. If you change x, y not affected.

Reference type memory management

java
package com.tutorialdoctor;

import java.awt.*;

public class Main{
    public static void main(String[] args){
        Point point1 = new Point(x:1,y:1); //address/reference stored
        Point point2 = point1;
        point1.x = 2;
        System.out.println(point2)
    }
}

Note

point1 and point2 point to the same memory location. If you change x, y is affected.

Arithmetic

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int result = 10 + 3
        int result = 10 - 3
        int result = 10 * 3
        double result = (double)10 / (double)3 // casting 10 to double
        System.out.println(result);
        // Increment operator
        int x = 1;
        x++;
        ++x;

        int y = x++ // copied to y then x incremented
        System.out.println(x);
        System.out.println(y);
        
        int x = 1;
        int y = ++x // x and y == 2
        System.out.println(x);
        System.out.println(y);

        int x = 1;
        x = x + 2;
        x += 2;
        System.out.println(x);

        int x = 10 + 3 * 2;
        System.out.println(x);
    }
}

Order of Operations

PEMDAS - Please Excuse My Dear Aunt Sally. Parenthesis, exponents, multiplication, division, addition, subtraction.

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        int x = 10 + 3 * 2;
        System.out.println(x);
    }
}

Casting

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        // Implicit casting (automatically)
        short x = 1; // 2 bytes
        int y = x + 2; // 4 bytes
        System.out.println(y); // 3

        double x = 1.1;
        double y = x + 2; // 1.1 + 2.0
        System.out.println(y); // 3.1

        // Explicit Casting
        double x = 1.1;
        int y = (int)x + 2; // 1 + 2
        System.out.println(y); // 3
    }
}

Note

can't cast string to integer

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String x = "1";
        y = Integer.parseInt(x) + 2;
        System.out.println(y); // 3

        String x = "1.1";
        double y = Double.parseDouble(x) + 2;
        System.out.println(y); // 3.1
    }
}

Typically Recieve input as a string from users, convert to numeric representation

Formatting Numbers

java
package com.tutorialdoctor;
import java.text.NumberFormat;

public class Main{
    public static void main(String[] args){
        // $1,234,537
        // Abstract class
        NumberFormat currency = new NumberFormat();//error

        NumberFormat currency = NumberFormat.getCurrencyInstance(); //factory method
        String result = currency.format(12345678.891)
        System.out.println(result);/// $1,234,567,89


        NumberFormat percent = NumberFormat.getPercentInstance(); //factory method
        String result = percent.format(0.1)
        System.out.println(result); // 10% 

        String result = NumberFormat.getPercentInstance().format(0.1); //method chaining
        System.out.println(result); // 10% 
    }
}

Reading Input

java
package com.tutorialdoctor;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in); //field
        System.out.print("Age:");
        byte age = scanner.nextByte();
        System.out.println("You are " + age)


        Scanner scanner = new Scanner(System.in); //field
        System.out.print("Age:");
        double age = scanner.nextDouble();
        System.out.println("You are " + age)

        Scanner scanner = new Scanner(System.in); //field
        System.out.print("Name:");
        String name = scanner.next(); // next reads one token Full name with space won't work
        System.out.println("You are " + name)

        Scanner scanner = new Scanner(System.in); //field
        System.out.print("Name:");
        String name = scanner.nextLine();
        System.out.println("You are " + name)

        Scanner scanner = new Scanner(System.in); //field
        System.out.print("Name:");
        String name = scanner.nextLine().trim(); //get rid of leading spaces.
        System.out.println("You are " + name)
    }
}

Switch Statements

java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String role = "admin";
        if(role=="admin")
            System.out.println("You are an admin");
        else if(role = "moderator")
            System.out.println("You are a moderator");
        else
            System.out.println("You are a guest");
    }
}
java
package com.tutorialdoctor;

public class Main{
    public static void main(String[] args){
        String role = "admin";
        switch(role){
            case "admin":
                System.out.println("You are an admin");
                break;
            case "moderator":
                System.out.println("You are a moderator");
                break;
            default:
                System.out.println("You are a guest");
        }
    }
}

Exercise

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

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.print("Number: ");
        int number = scanner.nextInt();

        if (number % 5 == 0 && number % 3 == 0)
            System.out.println("FizzBuzz");
        else if (number % 5 == 0)
            System.out.println("Fizz");
        else if (number % 3 == 0)
            System.out.println("Buzz");
        else
            System.out.println(number);

    }
}

Resources

Java Tutorial