Java beginners guide

Introduction

Java is a widely-used, object-oriented programming language that's known for its portability across platforms. It's employed for various applications, from mobile apps to enterprise systems.

Classes and Objects

In Java, everything revolves around classes and objects. A class defines the structure for objects:


public class Dog {
    String breed;
    int age;
}
  

Methods

Methods in Java are blocks of reusable code inside a class:


public void bark() {
    System.out.println('Woof!');
}
  

Variables and Data Types

Java has various data types to represent different kinds of data:


int age = 30;
double salary = 50000.50;
char letter = 'A';
String name = 'Alice';
  

Conditions and Loops

Java supports conditional statements and loops:


if (age > 18) {
    System.out.println('Adult');
} else {
    System.out.println('Not an adult');
}

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

int j = 0;
while (j < 5) {
    System.out.println(j);
    j++;
}
  

Arrays

Java arrays are containers that can hold multiple values:


int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]); // Outputs 3
  

Inheritance and Polymorphism

Java supports OOP principles like inheritance and polymorphism:


class Animal {
    void eat() {
        System.out.println('This animal eats food.');
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println('Woof!');
    }
}
  

Exception Handling

Java provides a mechanism to handle runtime errors:


try {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println('Error: Index out of bounds.');
}