Java syntax is similar to C and C++. It uses semicolons to end statements and curly braces {} to define blocks of code.
Printing output in Java is typically done using System.out.println() or System.out.print() methods.
publicclassHelloWorld {
publicstaticvoidmain(String[] args) {
System.out.println("Hello, World!");
}
}Java variables must be declared with a specific type. Common types include int, double, boolean, String, etc.
intage = 25;
doubleprice = 19.99;
booleanisActive = true;
Stringname = "John";Java supports for, while, and do-while loops.
// For loopfor (inti = 1; i <= 5; i++) {
System.out.println(i);
}
// While loopintcount = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
// Do-while loopintnum = 1;
do {
System.out.println(num);
num++;
} while (num <= 5);Functions in Java are called methods. They are defined within classes and can be static (class-level) or instance methods
publicclassMyClass {
// Static methodpublicstaticvoidsayHello() {
System.out.println("Hello, World!");
}
// Instance methodpublicvoidgreet(Stringname) {
System.out.println("Hello, " + name);
}
publicstaticvoidmain(String[] args) {
sayHello(); // Calling a static methodMyClassobj = newMyClass();
obj.greet("John"); // Calling an instance method
}
}Methods in Java can return values using the return keyword.
publicclassCalculator {
publicintadd(inta, intb) {
returna + b;
}
publicstaticvoidmain(String[] args) {
Calculatorcalc = newCalculator();
intresult = calc.add(5, 3);
System.out.println("Sum: " + result);
}
}Java arrays are fixed-size collections of elements of the same type. ArrayLists are dynamically resizable lists.
// Arraysint[] numbers = {1, 2, 3, 4, 5};
System.out.println("First number: " + numbers[0]);
// ArrayListsimportjava.util.ArrayList;
ArrayList<String> names = newArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println("First name: " + names.get(0));