Prints Hello World in Java console.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Declare variables and print them.
int x = 10;
int y = 5;
System.out.println(x + y);
Simple if-else example.
int age = 18;
if(age >= 18){
System.out.println("Adult");
}else{
System.out.println("Minor");
}
Loop through numbers 1 to 5.
for(int i=1; i<=5; i++){
System.out.println(i);
}
Loop until a condition is false.
int count = 0;
while(count < 5){
System.out.println(count);
count++;
}
Define a method and call it.
public static void greet(String name){
System.out.println("Hello " + name);
}
greet("Alice");
Create an array and loop through it.
int[] numbers = {1,2,3,4,5};
for(int num : numbers){
System.out.println(num);
}
Manipulate strings in Java.
String text = "Hello Java";
System.out.println(text.toUpperCase());
Read input from user.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello " + name);
Basic math operations in Java.
int a = 10, b = 5;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
Create and access 2D arrays.
int[][] matrix = {{1,2},{3,4}};
System.out.println(matrix[0][1]);
Use ArrayList to store elements.
import java.util.ArrayList;
ArrayList list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list);
Loop through ArrayList using for-each.
for(String fruit : list){
System.out.println(fruit);
}
Example of switch-case in Java.
int day = 3;
switch(day){
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
}
Handle exceptions in Java.
try{
int a = 5/0;
}catch(Exception e){
System.out.println("Error: " + e);
}
Define a simple class and object.
class Person{
String name;
int age;
}
Person p = new Person();
p.name = "Alice";
p.age = 25;
System.out.println(p.name);
Define and call a static method.
class Utils{
static void greet(String name){
System.out.println("Hello " + name);
}
}
Utils.greet("Alice");
Use final keyword to make a constant.
final int MAX = 100;
System.out.println(MAX);
Generate a random number using Math.random().
int rand = (int)(Math.random()*10)+1;
System.out.println(rand);
Single-line and multi-line comments in Java.
// This is a single-line comment
/* This is
a multi-line comment */