Java
- Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
- It is open-source and free
- It is secure, fast and powerful
- It has huge community support
- Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs
- Set up Java in computer
Compile & running in cmd | Terminal
javac
build.java
to.class
java
run.class
file
> javac Main.java
> java Main
Syntax
public class Main {
public static void main(String[] args) {
String name;
// Manual input in console
Scanner sc = new Scanner(System.in);
/* This is comment
in multiple lines
*/
// System.out.print(1 + 1); // This print not enter a new line
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Hello " + name + "!");
sc.close(); // garbage collector
}
}
Variables
[static] [final] type variableName = value;
- Variable's name are case-sensitive
- List Java keywords
Naming
package com.company.appname.feature.layer;
enum Direction {NORTH, EAST, SOUTH, WEST}
public interface IControl {};
public class UserControl implements IControl {
private final String SECRET_KEY = "Nothing!";
private String username;
private Properties properties;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
};
// Generic:
// <K,V> -> key, value
// <T> -> type
// <E> -> collection elements
// <S> -> service loaders
public interface UserAction<T extends Gender> extends Action<T> {}
// Annotation
public @interface FunctionalInterface {}
public @Test Documented {}
Data Types
Primitive
Type | Describe | Range |
---|---|---|
byte | 8-bit integer | -128 to 127 |
short | 16-bit integer | -32,768 to 32,767. |
int | 32-bit integer | -2^31 to 2^31-1 |
long | 64-bit integer | -2^63 to 2^63-1 |
float | 32-bit floating-point | |
double | 64-bit floating-point | |
char | 16-bit Unicode character | |
boolean | true / false |
boolean isValid = false;
int age = 20;
long onlineUsers = 3_000_000L; // or 3000000
float weight = 2.5f;
double balanceAmount = -2000.277d;
Reference
// The root class of the Java hierarchy. All classes inherit this
Object obj = new Object();
String str = "Hello world!";
int[] numbers = {1, 2, 3, 4, 5};
float[] amounts = new float[5]; // arr with length = 5
// (Integer|Long).MAX_VALUE
Integer iNumber = Integer.MIN_VALUE;
// (Float|Double)
// - NEGATIVE|POSITIVE_INFINITY
// - MIN_VALUE: The smallest positive value greater than zero that can be represented in a float|double variable.
// - MAX_VALUE: The largest positive value that can be represented in a float|double variable.
// - NaN: not a number of type
Float fNumber = Float.NEGATIVE_INFINITY;
Blocks
public class Demo {
private Integer number;
// constructor
public Demo() {}
// Non-static block statement
// Executed every Demo is created
{
System.out.println("Non-static block executed")
}
// Executed once when the class is loaded by JVM
static {
System.out.println("Static block executed")
}
}
Control Flow
If - else
if (condition) {
// code block
} else if (anotherCondition) {
// another code block
} else {
// default code block
}
// Ternary
value = condition ? trueExpression : falseExpression;
Switch - case - default
enum Day { MON, TUE, WED, THUR, FRI, SAT, SUN }
public static Boolean isWeekDay(Day day)
{
boolean result = false;
switch(day) {
case MON, TUE, WED, THUR, FRI:
result = true;
break;
case SAT, SUN:
result = false;
break;
default:
throw new IllegalArgumentException("Invalid day: " + day.name())
}
return result;
}
// switch + arrow break (JDK 13+)
int day = 3;
String dayType = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
// instanceof parsing (JDK 17+)
Object o;
switch (o)
{
case Integer i -> String.format("int %d", i);
case Double d -> String.format("double %f", d);
case String s -> String.format("String %s", s);
default -> o.toString();
}
Loop
For loop
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(number);
}
// Enhanced for loop
for (int number : numbers) {
System.out.println(number);
}
// Collection.forEach
List<Integer> listNumber = List.of(1, 2, 3, 4, 5);
listNumber.forEach(num -> {}); // use with lambda
While, Do - while Loop
int i = 1, sum = 0;
// check before run
while(i <= 5) {
sum += i;
i++;
}
// Run 1st before check
do {
sum += i;
i++;
} while(i <= 5)