Quick Java Tutorial

Learn the basics of Java programming. Covering variables, conditionals, loops, methods, classes, and objects.

Overview

On this page we will cover

Variables

/* Syntax: Type variableName = VALUE; */

int wholeNumber = 93;
double numberWithDigits = 46.85;

String text = "words and stuff";

boolean isValid = true;
boolean isNegative = -3 < 0;

MyObject obj = new MyObject();

Conditionals

if (boolean1) {
    // if boolean1 is true
} else if (boolean2) {
    // if boolean1 is false but boolean2 is true
} else {
    // if boolean1 and boolean2 were both false
}

Loops

while (isLoopActive) {
    // keep doing something
}
// isLoopActive became false
for (int i = 0; i < 5; i++) { // start with i=0, increment i each time, continue while i < 5
    // do something 5 times
}

Class Methods

/* Syntax: keywords returnType methodName(ParameterType parameterName, ...) { */

public static final double divide(int dividend, double divisor) {
    double quotient = dividend / divisor;
    return quotient;
}

private void moveForward(double inches) {
    // code to move forward [inches] inches
    // don't need to return, as returnType is 'void'
}

public abstract void overrideMeLater;

Keywords:

Access Modifier keywordDescription

public

Method is accessible by any class

private

Method is accessible by the same class

protected

Method is accessible by the same class and any subclasses

[leave blank]

Method is accessible only by the class's object

Non-Access Modifier keywordDescription

static

Method belongs to class [Class.call()], not the object [object.call()]

abstract

Method must be overridden and does not have a body

final

Method cannot be overridden

Classes

public class ClassName {
    // class variables here
    String name;
    
    // constructor
    public ClassName() {
        this("default name");
    }
    public ClassName(String name) {
        this.name = name;
    }
    
    // class methods here
    public String getName() {
        return name;
    }
}

Using Objects

// Creating objects
MyObject objName1 = new MyObject();
MyObject objName2 = new MyObject("Second try");

// Calling methods
MyObject.staticMethod();
objName1.method();
objName2.method();

// Using return values
String output = objName1.toString() + " | " + objName2.toString();


// Note: objects are just unique instances of a class; 
//       you can have multiple of the same class

Last updated