Java Notes
Source: Dev.to
Running Java from Terminal
javac App.java && java App
javac compiles the Java source file (App.java) into bytecode (App.class).
The && operator runs the second command only if the first succeeds, and java executes the compiled bytecode.
Hello World Example
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Variables
Variables act as containers for values of various data types.
public class Main {
public static void main(String[] args) {
int age = 10;
String name = "Davet";
boolean isCorrect = true;
float height = 6.4F;
double weight = 6.0;
char gender = 'M';
byte a = 1;
long number = 2334323423432423L;
}
}
String Manipulation Methods
public class Main {
public static void main(String[] args) {
String name = "Davet";
name.toLowerCase(); // "davet"
name.toUpperCase(); // "DAVET"
name.trim(); // removes leading/trailing spaces
name.replace("a", "b"); // replaces characters
}
}
Enum
An enum defines a fixed set of constant values.
public class Main {
public static void main(String[] args) {
GRADE fail = GRADE.F;
System.out.println(fail);
}
enum GRADE {
A, B, C, D, E, F
}
}
While Loop
The while loop repeatedly executes a block while a condition remains true.
public class Main {
public static void main(String[] args) {
boolean isCorrect = true;
int count = 0;
while (count < 10) {
System.out.println("The answer you picked is correct");
count++;
}
}
}
Functions (Methods)
A method groups code that performs a specific task and must be invoked to run.
public class Main {
public static void main(String[] args) {
introduce();
}
public static void introduce() {
String name = "David";
String jobDescription = "Backend Developer";
System.out.printf("I am %s, a %s", name, jobDescription);
}
}
Atomicity
Atomicity ensures that a series of operations either all succeed or none are applied.
import java.util.concurrent.AtomicInteger;
public class Main {
static int count = 1;
synchronized static void increment() {
count++;
}
public static void main(String[] args) {
increment();
System.out.println(count); // prints 2
// Using AtomicInteger
AtomicInteger atomicInt = new AtomicInteger(1); // initialise with 1
System.out.println(atomicInt.getAndIncrement()); // prints 1
System.out.println(atomicInt.incrementAndGet()); // prints 3
System.out.println(atomicInt.get()); // prints 3
}
}