-
Notifications
You must be signed in to change notification settings - Fork 2
Basic Java Syntax
ck-109 edited this page Mar 17, 2021
·
3 revisions
System.out.println("A"); #printing out "A"
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
class Apple {
public final colour; #attributes/properties
Apple(String word) { #instance constructor
this.colour = word; #assignment of input 'word' as the instance attribute
}
public void getColour { #method/function
return this.colour;
}
}
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;
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
Some useful String format symbols
* %d for integer (incl. byte, short, int, long, bigint)
* %s for any type of String value
* %b for any type of "true" if non-null, "false" if null
* \n for creation of new line
* %04d for xxxx data format
* %4f for floating point numbers with 4 decimal places
A neat way to transform any data type [Boolean/ int/ float] into a String is to add it with an empty string.
Eg; 13 + "" OR true + ""
if (#condition 1) {
#your code;
} else if (condition 2) { #possible to have multiple if-else statements
#your code;
} else (condition 3) {
#your code;
}
while (#condition) {
#your code;
}
for (int i = 0; i < 8; i++) {
your code;
}
for (Apple apple: Apples) {
your code;
}