Basic
Basic Java Programs
A basic Java program starts with a class definition, which contains a main method.
The main method is where the program starts executing:
public static void main(String[] args) {
// your code goes here
System.out.println("Hello World");
}
- The main method is a static method, which means it can be called without creating an instance of the class.
- args is used to pass command-line arguments to the program (the first element is the name of the program itself)
Variables and Data Types
int age = 20;
System.out.println(age);
int age = 20; // Integer (whole number)
float myWeight = 55.5f; // 4 bytes Floating point number
double myWeight2 = 55.5; // 8 bytes Floating point number
String name = "Hiep"; // String
char firstLetter = 'H'; // Character
boolean isMale = true; // Boolean
Condition
If else
int age = 20;
if (age < 13) {
System.out.println("Children");
} else if (age < 18) {
System.out.println("Adolescents");
} else {
System.out.println("Adults");
}
Ternary operator
int age = 20;
String result = (age < 18) ? "No good" : "OK";
System.out.println(result);
Switch
int age = 15;
switch (age) {
case 15:
System.out.println("class 10");
break;
case 16:
System.out.println("class 11");
break;
default:
System.out.println("class 12");
}
Loop
While
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do While
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
For
for (int i = 0; i < 5; i++) {
/* if (i == 4) {
continue;
} */
System.out.println(i);
/* if (i == 4) {
break;
} */
}
For-Each
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Method
Also known as function.
Code once, use many times.
public class Main {
// fname, age is Parameters
static void printAge(String fname, int age) {
System.out.println(fname + " is " + age);
}
// Calculate sum
static int calSum(int x, int y) {
// return int value
return x + y;
}
public static void main(String[] args) {
// "Hiep", 20 is Arguments
printAge("Hiep", 20);
int sum = calSum(5, 8);
System.out.println(sum);
}
}
Other
Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter weight: ");
double weight = scanner.nextDouble();
scanner.nextLine(); // ignore Enter (new line)
System.out.print("Enter country: ");
String country = scanner.nextLine();
System.out.print("Is male (true or false): ");
boolean isMale = scanner.nextBoolean();
scanner.close(); // Close the scanner
// Using String.format() to format the string
String result = String.format("Result:\nName: %s, Age: %d, Weight: %.2f, Country: %s, Is male: %b", name, age, weight, country, isMale);
System.out.println(result);
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
Casting
double age = 20.6d;
int ageInt = (int) age; // Outputs 20
String ageText = "20";
int ageValue = Integer.parseInt(ageText);
String weightText = "50.6";
double weightValue = Double.parseDouble(weightText);
String methods
String str = "Hello, world!";
int length = str.length(); // length is 13
int index = str.indexOf('o'); // index is 4
int lastIndex = str.lastIndexOf("o"); // lastIndex is 8
char ch = str.charAt(0); // ch is 'H'
String subStr = str.substring(7, 12); // subStr is "world"
String subStrEnd = str.substring(7); // subStrEnd is "world!"
String lowerCaseStr = str.toLowerCase(); // lowerCaseStr is "hello, world!"
String upperCaseStr = str.toUpperCase(); // upperCaseStr is "HELLO, WORLD!"
String str2 = " Hello, world! ";
String trimmedStr = str2.trim(); // trimmedStr is "Hello, world!"
String replacedStr = str.replace("o", "x"); // replacedStr is "Hellx, wxrld!"
Character methods
char c = 'A';
boolean isLetter = Character.isLetter(c); // true
char upperCh = Character.toUpperCase(c); // 'A'
String str = Character.toString(c); // "a"
char ch = '9';
boolean isDigit = Character.isDigit(ch); // true
Math
Math.max(5, 10); // 10
Math.min(5, 10); // 5
Math.round(5.5); // 6
Math.floor(5.5); // 5.0
Math.ceil(5.5); // 6.0
Math.sqrt(64); // 8
Math.random();
int randomNum = (int)(Math.random() * 101); // 0 to 100
Arrays
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; // fixed-size
System.out.println("First car: " + cars[0]); // Volvo
System.out.println("Cars length:" + cars.length); // 4
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
for (String i : cars) {
System.out.println(i);
}