Java is a high-level, object-oriented programming language that was released by Sun Microsystems in 1995. It has become one of the most widely used programming languages for enterprise and web applications.
public class Person { // Instance variables (encapsulation) private String name; private int age; // Constructor public Person(String name, int age) { this.name = name; this.age = age; } // Getter and Setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } // Method public void introduce() { System.out.println("Hi, I'm " + name + " and I'm " + age + " years old."); }}// UsagePerson person = new Person("Alice", 25);person.introduce();
Proper exception handling is crucial for building robust applications.
public class ExceptionExample { public static void main(String[] args) { try { // Code that might throw an exception int result = divide(10, 0); System.out.println("Result: " + result); } catch (ArithmeticException e) { // Handle specific exception System.out.println("Error: Cannot divide by zero"); } catch (Exception e) { // Handle any other exception System.out.println("An error occurred: " + e.getMessage()); } finally { // Always executed System.out.println("Execution completed"); } } public static int divide(int a, int b) throws ArithmeticException { if (b == 0) { throw new ArithmeticException("Division by zero"); } return a / b; }}
import java.util.*;public class CollectionsDemo { public static void main(String[] args) { // List example List<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("JavaScript"); // Set example Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(2); // Duplicate, will not be added // Map example Map<String, Integer> map = new HashMap<>(); map.put("Alice", 25); map.put("Bob", 30); // Iteration for (String item : list) { System.out.println(item); } // Lambda with streams (Java 8+) list.stream() .filter(s -> s.startsWith("J")) .forEach(System.out::println); }}