Tutorials | Java Tutorial

1. Basic Java Syntax

Java is a widely used, high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). Here’s a brief overview of some basic Java syntax:

  1. Comments:

    • Single-line comments start with //.
    • Multi-line comments are enclosed between /* and */.
    java:

    // This is a single-line comment

    /*
    This is a
    multi-line comment
    */

  2. Variables:

    • Java is statically-typed, meaning you need to declare the type of a variable before using it.
    • Common data types include int, double, char, boolean, and more.
    java:
    int age = 25;
    double salary = 50000.50;
    char grade = 'A';
    boolean isStudent = true;
  3. Data Types:

    • Primitive data types: int, double, char, boolean, etc.
    • Object data types: String, Array, Object, etc.
    java:
    String name = "John";
    int[] numbers = {1, 2, 3, 4, 5};
  4. Operators:

    • Arithmetic operators: +, -, *, /, %.
    • Comparison operators: ==, !=, <, >, <=, >=.
    • Logical operators: && (and), || (or), ! (not).
    java:
    int sum = 10 + 5;
    boolean isEqual = (sum == 15);
  5. Control Flow:

    • if, else if, else statements for conditional branching.
    • for, while, do-while loops for iteration.
    java:

    if (age >= 18) {
    System.out.println(“You are an adult.”);
    } else {
    System.out.println(“You are a minor.”);
    }

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

  6. Methods:

    • Methods are defined using the method keyword.
    • Main method is the entry point of a Java program.
    java:

    public class MyClass {
    public static void main(String[] args) {
    System.out.println(“Hello, World!”);
    }

    public static int add(int a, int b) {
    return a + b;
    }
    }

  7. Classes and Objects:

    • Java is an object-oriented language, and most code is organized into classes and objects.
    java:

    public class Car {
    String model;
    int year;

    public void start() {
    System.out.println(“Car is starting.”);
    }
    }

    // Creating an object
    Car myCar = new Car();
    myCar.model = “Toyota”;
    myCar.year = 2022;
    myCar.start();

2. Control Statements

  1. Conditional Statements:

    • if-else: It executes a block of code if a specified condition is true, and another block if the condition is false.

      java:
      int x = 10;
      if (x > 5) {
      System.out.println("x is greater than 5");
      } else {
      System.out.println("x is not greater than 5");
      }
    • else-if: Used to specify multiple conditions.

      java:
      int time = 20;
      if (time < 12) {
      System.out.println("Good morning!");
      } else if (time < 18) {
      System.out.println("Good afternoon!");
      } else {
      System.out.println("Good evening!");
      }
  2. Looping Statements:

    • for: Executes a block of code a specified number of times.

      java:
      for (int i = 0; i < 5; i++) {
      System.out.println("Iteration: " + i);
      }
    • while: Executes a block of code as long as a specified condition is true.

      java:
      int count = 0;
      while (count < 5) {
      System.out.println("Count: " + count);
      count++;
      }
    • do-while: Similar to the while loop, but it guarantees that the block of code is executed at least once before the condition is checked.

      java:
      int num = 5;
      do {
      System.out.println("Number: " + num);
      num--;
      } while (num > 0);
  3. Branching Statements:

    • break: Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

      java:
      for (int i = 0; i < 10; i++) {
      if (i == 5) {
      break;
      }
      System.out.println("Iteration: " + i);
      }
    • continue: Skips the current iteration of a loop and proceeds to the next iteration.

      java:
      for (int i = 0; i < 5; i++) {
      if (i == 2) {
      continue;
      }
      System.out.println("Iteration: " + i);
      }
    • return: Exits from the current method and returns control to the caller.

      java:
      public int sum(int a, int b) {
      return a + b;
      }

3. Java Object Class

The Object class in Java plays a fundamental role in implementing Object-Oriented Programming (OOP) concepts. OOP is a programming paradigm based on the concept of “objects,” which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods). Here’s an explanation of how the Object class relates to key OOP concepts:

1. Abstraction:

  • Abstraction is the process of simplifying complex reality by modeling classes that represent real-world entities. In Java, classes are used to achieve abstraction. The Object class provides a common base for all classes in Java, serving as the ultimate abstraction.

    Abstraction involves simplifying complex reality by modeling classes that represent real-world entities.

    // Example demonstrating abstraction
    public abstract class Shape {
    // Abstract method representing area calculation
    public abstract double calculateArea();
    }

    public class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
    this.radius = radius;
    }

    @Override
    public double calculateArea() {
    return Math.PI * radius * radius;
    }
    }

    public class Rectangle extends Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
    this.length = length;
    this.width = width;
    }

    @Override
    public double calculateArea() {
    return length * width;
    }
    }

    public class Main {
    public static void main(String[] args) {
    Shape circle = new Circle(5);
    Shape rectangle = new Rectangle(4, 6);

    System.out.println(“Area of Circle: ” + circle.calculateArea());
    System.out.println(“Area of Rectangle: ” + rectangle.calculateArea());
    }
    }

    2. Encapsulation:

    • Encapsulation is the bundling of data and methods that operate on the data into a single unit (class). This helps in hiding the internal state of an object and only exposing the necessary functionalities. The Object class encapsulates various common functionalities and behaviors that are applicable to all Java objects, such as toString(), equals(), and hashCode() methods.

      Encapsulation involves bundling data and methods that operate on the data into a single unit (class), hiding the internal state of an object.

      // Example demonstrating encapsulation
      public class Person {
      private String name;
      private int age;

      public Person(String name, int age) {
      this.name = name;
      this.age = age;
      }

      // Getter and setter methods for name
      public String getName() {
      return name;
      }

      public void setName(String name) {
      this.name = name;
      }

      // Getter and setter methods for age
      public int getAge() {
      return age;
      }

      public void setAge(int age) {
      this.age = age;
      }
      }

      public class Main {
      public static void main(String[] args) {
      Person person = new Person(“John”, 30);
      System.out.println(“Name: ” + person.getName());
      System.out.println(“Age: ” + person.getAge());

      // Updating age using setter method
      person.setAge(35);
      System.out.println(“Updated Age: ” + person.getAge());
      }
      }

      3. Inheritance:

      • Inheritance is the mechanism by which one class can inherit properties and behavior from another class. In Java, every class directly or indirectly inherits from the Object class. If a class does not explicitly extend any other class, it implicitly extends the Object class. This enables classes to inherit the common methods provided by the Object class.
        Inheritance allows a class to inherit properties and behavior from another class.

        // Example demonstrating inheritance
        public class Animal {
        public void sound() {
        System.out.println(“Animal makes a sound”);
        }
        }

        public class Dog extends Animal {
        @Override
        public void sound() {
        System.out.println(“Dog barks”);
        }
        }

        public class Cat extends Animal {
        @Override
        public void sound() {
        System.out.println(“Cat meows”);
        }
        }

        public class Main {
        public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();

        dog.sound(); // Output: Dog barks
        cat.sound(); // Output: Cat meows
        }
        }

        4. Polymorphism:

        • Polymorphism allows objects of different classes to be treated as objects of a common superclass. Since every class in Java is a subclass of Object, polymorphism can be achieved by treating objects of different classes as instances of the Object class. This allows for more flexible and generic programming.

          // Example demonstrating polymorphism
          public class Vehicle {
          public void move() {
          System.out.println(“Vehicle moves”);
          }
          }

        public class Car extends Vehicle {
        @Override
        public void move() {
        System.out.println(“Car moves on roads”);
        }
        }

        public class Boat extends Vehicle {
        @Override
        public void move() {
        System.out.println(“Boat moves on water”);
        }
        }

        public class Main {
        public static void main(String[] args) {
        Vehicle car = new Car();
        Vehicle boat = new Boat();

        car.move(); // Output: Car moves on roads
        boat.move(); // Output: Boat moves on water
        }
        }

      5. Object:

      • An object is an instance of a class that encapsulates data and behaviors. In Java, objects are created using the new keyword followed by a constructor call. The Object class itself represents a generic object in Java. It provides basic functionalities and behaviors that are common to all objects, such as the ability to be cloned, compared for equality, and converted to a string representation.

4. Java Array

In Java, an array is a data structure used to store a fixed-size sequential collection of elements of the same data type. Here’s a detailed explanation of Java arrays:

1. Declaration and Initialization:

You declare an array by specifying the type of elements it will hold, followed by square brackets [] and the array name. Arrays can be initialized during declaration or after declaration using the new keyword.

Declaration and Initialization in One Line:
java:
int[] numbers = {1, 2, 3, 4, 5}; // Initializing array with values
String[]
names = {"Alice", "Bob", "Charlie"}; // Initializing array with strings
 
Declaration and Initialization Separately:
java:
int[] scores; // Declaration
scores = new int[5]; // Initialization with size 5

String[] daysOfWeek;

daysOfWeek = new String[7]; // Initialization with size 7

2. Accessing Elements:

You can access individual elements of an array using their index, which starts from 0 and goes up to length - 1.

java:
int firstScore = scores[0]; // Accessing the first element
String thirdName = names[2]; // Accessing the third element

3. Array Length:

The length of an array represents the number of elements it can hold. You can obtain the length of an array using the length property.

java:
int size = scores.length; // Getting the length of the scores array

4. Iterating Over Arrays:

You can use loops like for or foreach to iterate over the elements of an array.

java:
// Iterating over the elements of the scores array using for loop
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + (i + 1) + ": " + scores[i]);
}
// Iterating over the elements of the names array using foreach loop

for (String name : names) {
System.out.println(name);
}
5. Multi-dimensional Arrays:

Java supports multi-dimensional arrays, allowing you to create arrays of arrays.

java:
// Declaration and initialization of a 2D array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
6. Arrays are Objects:

In Java, arrays are objects, and they inherit properties and methods from the java.lang.Object class, such as toString() and equals().

java:
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
System.out.println(array1.equals(array2)); // Output: false

System.out.println(Arrays.equals(array1, array2)); // Output: true

Arrays are a fundamental part of Java programming, providing a convenient way to work with collections of data. Understanding how to declare, create, and manipulate arrays is essential for Java developers.