Skip to content
arjann57 edited this page Mar 16, 2021 · 3 revisions

1. Console

Console output

System.out.println("A"); #printing out "A"

##Console input

import java.util.Scanner; 
Scanner sc = new Scanner(System.in); #create a new scanner instance 
String a = sc.next(); #read next word from input file
int b = sc.nextInt(); #read next int from input file

2. Class structure

class Apple {
    public final colour;     #attributes/properties

    Apple(String word) {     #instance constructor
        this.colour = word;  #assignment of input as the instance attribute
    }

    public void getColour {  #method/function 
        return this.colour;
    }
}

3. Variable declaration

int i; #declaring a new integer variable "i"
double j = 3.0; #declaring a new double variable "j" with value of 3.0
int[] m = new int[4]; #declaring a new integer array "m" with a length of 4 elements;

#4. Formatting output: use of String.format

String s = String.format("point (%.3f, %.3f)", this.x, this.y); #output "this.x" and "this.y" as a floating point number with three digits after the decimal point

#5. Control flow

if loops

if (#condition 1) {
    #your code;
} else if (condition 2) { #possible to have multiple if-else statements
    #your code;
} else (condition 3) {
    #your code;
}

while loops

while (#condition) {
    #your code;
}

for loops

for (int i = 0; i < 8; i++) {
    your code;
}

for (Apple apple: Apples) {
    your code;
}