An Introduction to Java
ArchieMaclean (649)

Java Tutorial for Beginners

This is a very fast tour of some basic Java. You should type everything in to a Java repl, and try changing values to see what happens.
You should know how to program in other languages - I'm assuming knowledge of a language like Python or JavaScript.

Basics

Java is OOP (Object-Oriented Programming) so everything must be in a class. The Java compiler will automatically run any code in the main method.

class Main {
  public static void main(String[] args) {
    // This is a comment
    // This will be run
  }
}

In Java, blocks are defined with curly braces {} - indentation is not necessary, but improves readability. All lines in Java must end with either ;, or } (where appropriate).

You can print stuff to the screen using System.out.println.

class Main {
  public static void main(String[] args) {
    System.out.println("Hello, world!");    // => 'Hello, World!'
  }
}

Mathematical operators are as follows:

class Main {
  public static void main(String[] args) {
    System.out.println(2+3);  // addition
    System.out.println(2-3);  //subtraction
    System.out.println(2*3);  // multiplication
    System.out.println(2/3);  // division - rounds down
    System.out.println(3%2);  // modulus - remainder of division
  }
}

Variables and Datatypes

When declaring a variable in Java, use the suntax variable_type variable_name;. This declares an empty variable

class Main {
  public static void main(String[] args) {
    int num;
    num = 3;
    System.out.println(num);

    // Or, on one line
    int another_num = 3;
    System.out.println(another_num);
  }
}

There are a few datatypes - here are the most common:

class Main {
  public static void main(String[] args) {
    // integers up to 2,147,483,647
    int i = 3;
    // integers up to 9,223,372,036,854,775,807
    long l = 314159265;
    // 64-bit floating-point number
    double d = 3.1415d;
    // 32-bit floating-point number (for saving memory)
    float f = 3.14f;
    // text
    String s = "Hello, World!";
    // single character
    char c = 'a';
    // true/false
    boolean b = false;
  }
}

Arrays are when you assign multiple values to one variable name, e.g. x = {1,2,3}. The syntax is type[] name = new type[length];

class Main {
  public static void main(String[] args) {
    // integer array of length 10
    int[] i = new int[10];

    // access elements with 0-based index, i.e. first element is 0, second is 1 e.t.c.
    i[0] = 1;
    i[6] = 32;


    // another way of defining arrays
    int[] i2 = {1,2,3};

    // use .length to find the length of the array
    System.out.println(i.length);
    System.out.println(i2.length);
  }
}

The String datatype is basically an array of chars.

class Main {
  public static void main(String[] args) {
    char[] c = {'H','e','l','l','o'};
    String s = new String(c);
    System.out.println(s);

    // .length() is used to find the length of a String
    System.out.println(s.length());
  }
}

For an array with variable length, you can use an ArrayList

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList al = new ArrayList();
    al.add('a');
    al.add(3);
    al.add("Hi there!");
    // pushes to 0 index
    al.add(0,"First");
    System.out.println(al);
    System.out.println(al.size());  // => 4

    // remove removes by index, not value
    al.remove(0);
    System.out.println(al.size());  // => 3


    // also, you can set it to only 1 datatype
    ArrayList<String> sal = new ArrayList<String>();
    sal.add("Hi");
    sal.add(34);    // fails because it is not String
  }
}

HashMaps give each item a key and a value (also called Hashes, dicts or maps in other langs).

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // key is String, value is Integer
    // datatypes are different than normal
    // use Boolean, Character, Double for boolean,char,double
    HashMap<String, Integer> hm = new HashMap<String, Integer>();

    hm.put("John",23);
    hm.put("Anne",17);
    System.out.println(hm);
    // use get to find a specific value
    System.out.println(hm.get("Anne"));

    hm.remove("Anne");
    System.out.println(hm);
  }
}

Control Flow

Comparison operators are used to compare things.

class Main {
  public static void main(String[] args) {
    System.out.println(1==1); // equal to
    System.out.println(2>1);  // greater than
    System.out.println(2<1);  // less than
    System.out.println(1>=1); // greater than or equal to
    System.out.println(2<=1); // less than or equal to
    System.out.println(2!=1); // not equal to
  }
}

Logical operators are ways of choosing based on trues and falses.

class Main {
  public static void main(String[] args) {
    // AND - true if both are true
    System.out.println(true && true);
    // OR - true if either are true
    System.out.println(true || false);
    // NOT - swaps true with false and vice versa
    System.out.println(!true);
    // XOR - true if either are true but not both
    System.out.println(true^false);
    System.out.println(true^true);
  }
}

If statements do things depending on whether certain conditions are evaluated as true or false.

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

    // outputs "10 is greater than 5!"
    if (10>5) {
      System.out.println("10 is greater than 5!");
    } else {
      System.out.println("10 is not greater than 5");
    }

    int a = 10;

    // outputs "a is greater than 8"
    if (a<2) {
      System.out.println("a is less than 2");
    } else if (a<8) {
      System.out.println("a is less than 8");
    } else {
      System.out.println("a is greater than 8");
    }
  }
}

for loops are used to loop a fixed number of times.

class Main {
  public static void main(String[] args) {
    // loops 10 times, incrementing i by 1 each time
    // (i++)
    for (int i=0;i<10;i++) {
      System.out.println(i);
    }


    char[] c_array = {'a','b','c','d'};
    // loos for each item in the array
    for (char c:c_array) {
      System.out.println(c);
    }
  }
}

while loops continue looping until a certain criteria is met.

class Main {
  public static void main(String[] args) {
    int x = 3;

    // continues until x=6
    // because then 6*4 == 24
    while ((x*4)!=24) {
      System.out.println(x);
      x++;
    }
  }
}

Classes and Methods

Methods are another name for functions inside classes.

class Main {
  public static void main(String[] args) {
    sayHello();
    
    String farewell = sayGoodbye();
    System.out.println(farewell);

    System.out.println("3 is greater than 5: "+isGreaterThanFive(3));
    System.out.println("10 is greater than 5: "+isGreaterThanFive(10));

  }

  // public and static will be covered in a minute
  // void means the method doesn't return anything
  public static void sayHello() {
    System.out.println("Hello!");
  }

  // String means that the method returns a String
  public static String sayGoodbye() {
    return "Goodbye!";
  }

  // boolean so returns true/false
  public static boolean isGreaterThanFive(int n) {
    return (n>5);
  }
}

A class is like a blueprint, with which you can make objects (instances).

class Main {
  public static void main(String[] args) {
    // create a new 'instance' of the dog class, called George
    Dog George = new Dog("George");
    George.bark();
    George.live();
    George.eat(); // fails because eat() is private
  }
}

class Dog {
  // this is an attribute that all 
  // of our Dog objects will have
  String name;

  // this is called the constructor
  // it is called when the dog is created
  public Dog(String name) {
    // this. means that name applies the this dog
    // it means that it's name can be used elsewhere
    // in the class
    this.name = name;

    System.out.println("A dog called "+this.name+" was just created!");
  }

  // public means that it can be accessed by other classes
  public void bark() {
    System.out.println(this.name+" just said 'Woof!'");
  }

  public void live() {
    this.eat();
  }

  // private so cannot be accessed by other classes
  private void eat() {
    System.out.println(this.name+" is eating!");
  }
}

static methods can be referenced from a static setting.

class Main {
  public static void main(String[] args) {
    // create a new instance of the Shop class
    Shop Amazon = new Shop();
    Amazon.buy();

    // static, so we can just do this
    Shop.buy();

    Amazon.showDetails();

    // fails because it is not an instance
    // and the method is not static
    Shop.showDetails();
  }
}

class Shop {
  // static so don't need to instantiate in order to 
  // use the method
  public static void buy() {
    System.out.println("Buying!");
  }

  public void showDetails() {
    System.out.println("You have to create a instance for this to work");
  }
}

Input

The Scanner class is used to scan text.

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

class Main {
  public static void main(String[] args) {
    // creates a new Scanner looking at the string "Hello World"
    Scanner input_reader = new Scanner("Hello World");

    // outputs each word one at a time
    while (input_reader.hasNext()) {
      String input = input_reader.next();
      System.out.println(input);
    }
  }
}

You can use the Scanner class to read input from the keyboard.

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner input_reader = new Scanner(System.in);

    System.out.println("Enter some text: ");
    String input = input_reader.nextLine();
    System.out.println("You said: "+input);
  }
}

Error Handling

You can handle errors with try..catch

import java.lang.ArithmeticException;

class Main {
  public static void main(String[] args) {
    
    try {
      System.out.println(1/0);
    } catch (ArithmeticException e) {
      System.out.println("Got error: "+e);
    }
  }
}

Conclusion

That was a quick look over some basic Java. You may want to re-read this to make sure you understand it all.
Please upvote if you liked this tutorial, it helps support me :)

Suggested further topics:

  • File reading/writing (may not work on repl.it)
  • Inner Classes
  • Inheritance
  • Interfaces
  • Packages
You are viewing a single comment. View All