JAVA tutorials

Java Update Array Items

To update an array item, assign a new value to the specified index.


  public class Main {
    public static void main(String[] args) {
      String[] fruits = {"Apple", "Banana", "Orange"};
      fruits[1] = "Grape"; // Updates Banana to Grape
      System.out.println(fruits[1]); // Outputs: Grape
    }
  }
    

Java Add Array Items

In Java, arrays have a fixed size, but you can use ArrayList to dynamically add items.


  import java.util.ArrayList;
  
  public class Main {
    public static void main(String[] args) {
      ArrayList fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Orange");
      fruits.add("Grapes"); // Adds Grapes to the end
      System.out.println(fruits.get(3)); // Outputs: Grapes
    }
  }
    

Java Remove Array Items

In Java, use ArrayList and its remove() method to remove items.


  import java.util.ArrayList;
  
  public class Main {
    public static void main(String[] args) {
      ArrayList fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Orange");
      fruits.remove(1); // Removes Banana
      System.out.println(fruits); // Outputs: [Apple, Orange]
    }
  }
    

Java Loop Through Array

You can loop through an array using a for loop or enhanced for loop in Java.


  public class Main {
    public static void main(String[] args) {
      String[] fruits = {"Apple", "Banana", "Orange"};
      for (String fruit : fruits) {
        System.out.println(fruit); // Outputs each fruit in the array
      }
    }
  }
    

Java Introduction

Java ek high-level programming language hai. Iska matlab hai ki Java ko likhne aur samajhne mein humare liye asaani hoti hai. Yeh Sun Microsystems ne develop ki thi, lekin ab Oracle Corporation ke under hai.

Java ko platform-independent banaya gaya hai. Iska matlab hai ki ek baar jo code likha jata hai, woh kisi bhi operating system (Windows, Mac, Linux) par chal sakta hai, bas Java runtime environment (JRE) hona chahiye.

Java ka use zyada tar large-scale software applications, mobile applications (Android apps), aur web applications banane mein hota hai.

Java Installation Guide

Follow the steps below to install Java on your system:

Step 1: Download Java

Visit the official Oracle website to download the latest version of the Java Development Kit (JDK):

Download JDK from Oracle

Alternatively, you can download OpenJDK from other sources:

Download OpenJDK

Step 2: Install Java on Windows

Follow these steps to install Java on Windows:

Step 3: Install Java on macOS

Follow these steps to install Java on macOS:

Step 4: Install Java on Linux

Follow these steps to install Java on Linux:

Step 5: Verify Installation

After installing Java, verify the installation by checking the Java version:

java -version

If everything is installed correctly, you should see the installed Java version displayed on the screen.

Step 6: Set JAVA_HOME Environment Variable

It's important to set the JAVA_HOME variable on your system:

Step 7: Test Java Installation

Test Java installation by compiling and running a simple Java program:

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

Java Get Started

Java programming shuru karne ke liye, aapko sabse pehle apne computer mein **Java Development Kit (JDK)** install karna hoga.

Java code likhne ke liye aap kisi bhi **text editor** ka use kar sakte hain, lekin **IDEs (Integrated Development Environments)** jaise **IntelliJ IDEA**, **Eclipse**, ya **NetBeans** se kaam asaan ho jata hai.

Steps to get started with Java:

  1. Sabse pehle **JDK (Java Development Kit)** ko install karein.
  2. Text editor ya IDE mein **Java code** likhein.
  3. Code ko **compile** karne ke liye command prompt mein `javac` command use karein.
  4. Finally, program ko **run** karne ke liye `java` command use karein.

Java Syntax

Java syntax, yaani likhne ka tareeka, **C++** jaise programming languages se milta-julta hai. Java mein har statement ko **semicolon (;)** se end karna zaroori hota hai.

Java code ko likhte waqt **keywords** ka dhyaan rakhein, jaise `public`, `class`, `void`, etc. Keywords case-sensitive hote hain, matlab `Class` aur `class` alag hain.


  public class Main {
    public static void main(String[] args) {
      // Yeh ek simple Java program hai
      System.out.println("Hello, World!");  // Print message to console
    }
  }
    

Output:


  Hello, World!
    

Upar diye gaye code mein:

Java Output

Java mein output ko print karne ke liye hum **System.out.println()** ka use karte hain. Yeh method kisi bhi message ko console par display karta hai.


  public class Main {
    public static void main(String[] args) {
      // Output print karna
      System.out.println("Hello, Java!");  // Print message to console
    }
  }
    

Output:


  Hello, Java!
    

**Explanation**:

Java Comments

Java mein comments do tareekon se likhe ja sakte hain:


  // Yeh ek single-line comment hai
  public class Main {
    public static void main(String[] args) {
      System.out.println("Hello, Java!");  // Yeh comment hai is line ke end mein
    }
  }
  
  /* 
  Yeh ek multi-line comment hai 
  Jisme kai lines ko comment kiya gaya hai
  */
  public class AnotherClass {
    public static void main(String[] args) {
      System.out.println("Java Comments Example");
    }
  }
    

Explanation:

Variables in Java

Java mein variable ek memory location ko represent karta hai jahan data store hota hai. Har variable ko ek type assign kiya jata hai, jaise int, double, String, etc.


  public class Main {
    public static void main(String[] args) {
      // Variable declaration
      int age = 25;  // Integer type variable
      String name = "John";  // String type variable
    }
  }
    

Explanation:

Multiple Variables in Java

Java mein ek hi line mein multiple variables ko declare aur initialize kiya ja sakta hai. Variables ko comma se separate kiya jata hai.


  public class Main {
    public static void main(String[] args) {
      // Declare multiple variables
      int age = 25, salary = 50000;
      String name = "John", city = "New York";
  
      // Print multiple variables
      System.out.println("Name: " + name);
      System.out.println("Age: " + age);
      System.out.println("Salary: " + salary);
      System.out.println("City: " + city);
    }
  }
    

Output:


  Name: John
  Age: 25
  Salary: 50000
  City: New York
    

**Explanation**:

Identifiers in Java

Identifiers Java mein wo names hote hain jo variables, classes, functions, arrays, etc. ko denote karte hain. Identifier ka name kisi bhi valid letter, number, ya underscore (_) se start ho sakta hai. Lekin space nahi hona chahiye.


  public class Main {
    public static void main(String[] args) {
      int age = 25;  // Valid identifier
      String name = "John";  // Valid identifier
      // int 1age = 30;  // Invalid identifier, starts with a number
      // int age&name = 50;  // Invalid identifier, special character used
    }
  }
    

Explanation:

Real-Life Examples of Variables

Variables ko real-life examples ke through samjha ja sakta hai. Jaise ek car ka model, speed, aur color ke liye variables banaye ja sakte hain.


  public class Main {
    public static void main(String[] args) {
      // Real-life example variables
      String carModel = "Toyota Corolla";  // Car model
      int carSpeed = 120;  // Car speed in km/h
      String carColor = "Red";  // Car color
  
      // Print the variables
      System.out.println("Car Model: " + carModel);
      System.out.println("Car Speed: " + carSpeed + " km/h");
      System.out.println("Car Color: " + carColor);
    }
  }
    

Output:


  Car Model: Toyota Corolla
  Car Speed: 120 km/h
  Car Color: Red
    

**Explanation**:

Data Types in Java

In this section, we will explore the different data types in Java. Java supports two types of data types: Primitive Data Types and Non-Primitive Data Types. We will cover both categories along with examples.

Java Numbers

Is program mein hum integer aur floating-point numbers ko declare karenge aur print karenge. Java mein hum int, float, aur double


  public class Main {
    public static void main(String[] args) {
      int num1 = 10;  // Integer number
      float num2 = 20.5f;  // Floating point number
      double num3 = 30.75;  // Double precision floating point number
      
      // Printing the numbers
      System.out.println("Integer Number: " + num1);
      System.out.println("Float Number: " + num2);
      System.out.println("Double Number: " + num3);
    }
  }
    

Output:


  Integer Number: 10
  Float Number: 20.5
  Double Number: 30.75
    

**Explanation**:

Java Booleans

Is program mein hum boolean type ko use karenge. Java mein boolean type sirf do values le sakta hai: true ya false.


  public class Main {
    public static void main(String[] args) {
      boolean isJavaFun = true;  // Boolean variable
      
      // Printing the boolean value
      System.out.println("Is Java Fun? " + isJavaFun);
    }
  }
    

Output:


  Is Java Fun? true
    

**Explanation**:

Java Characters

Is program mein hum character type ko use karenge. Java mein character variable ko char type ke variable se declare karte hain jo ek single character ko store karta hai.


  public class Main {
    public static void main(String[] args) {
      char grade = 'A';  // Character variable
      
      // Printing the character value
      System.out.println("Grade: " + grade);
    }
  }
    

Output:


  Grade: A
    

**Explanation**:

Real-Life Example of Java Data Types

Chaliye ek real-life example lete hain jisme hum Java ke data types ko istemal karenge. Is example mein hum ek student ke record ko store karenge jisme naam (String), age (int), grade (char), aur height (double) store karenge.


  public class Main {
    public static void main(String[] args) {
      String name = "Alice";  // Student's name
      int age = 21;  // Student's age
      char grade = 'B';  // Student's grade
      double height = 5.6;  // Student's height in feet
      
      // Printing the student's details
      System.out.println("Student Name: " + name);
      System.out.println("Age: " + age);
      System.out.println("Grade: " + grade);
      System.out.println("Height: " + height);
    }
  }
    

Output:


  Student Name: Alice
  Age: 21
  Grade: B
  Height: 5.6
    

**Explanation**:

Non-Primitive Data Type: Array

Is program mein hum Java mein ek array ko define karenge. Arrays ko non-primitive data types kaha jata hai kyunki woh ek collection hote hain multiple elements ka.


  public class Main {
    public static void main(String[] args) {
      // Array of integers
      int[] numbers = {10, 20, 30, 40, 50};
      
      // Printing the array values
      for (int num : numbers) {
        System.out.println(num);
      }
    }
  }
    

Output:


  10
  20
  30
  40
  50
    

**Explanation**:

Implicit Casting (Widening)

Implicit casting occurs when a smaller data type is automatically converted to a larger data type. Java does this automatically.


  public class Main {
    public static void main(String[] args) {
      int myInt = 9;
      double myDouble = myInt;  // Implicit casting from int to double
  
      System.out.println("Integer: " + myInt);
      System.out.println("Double: " + myDouble);
    }
  }
    

Output:


  Integer: 9
  Double: 9.0
    

Java Operators

In this section, we will explore the different types of operators in Java, including arithmetic, relational, logical, and assignment operators.

Java Arithmetic Operators

Arithmetic operators are used to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and modulus.


  public class Main {
    public static void main(String[] args) {
      int a = 10;
      int b = 5;
      
      System.out.println("Addition: " + (a + b));
      System.out.println("Subtraction: " + (a - b));
      System.out.println("Multiplication: " + (a * b));
      System.out.println("Division: " + (a / b));
      System.out.println("Modulus: " + (a % b));
    }
  }
    

Output:


  Addition: 15
  Subtraction: 5
  Multiplication: 50
  Division: 2
  Modulus: 0
    

Java Relational Operators

Relational operators are used to compare two values. These operators return a boolean result: true or false.


  public class Main {
    public static void main(String[] args) {
      int x = 10;
      int y = 20;
      
      System.out.println("x > y: " + (x > y));
      System.out.println("x < y: " + (x < y));
      System.out.println("x == y: " + (x == y));
    }
  }
    

Output:


  x > y: false
  x < y: true
  x == y: false
    

Java Strings

In this section, we will learn about Java strings. A string is a sequence of characters, and Java provides a class String to handle strings.

Creating Strings

Strings can be created in Java using string literals or by using the new keyword.


  public class Main {
    public static void main(String[] args) {
      String greeting = "Hello, World!";  // String literal
      String anotherGreeting = new String("Hello, Java!");  // Using new keyword
  
      System.out.println(greeting);
      System.out.println(anotherGreeting);
    }
  }
    

Output:


  Hello, World!
  Hello, Java!
    

String Concatenation in Java

In this section, we will explore string concatenation in Java, which is the process of combining two or more strings.

Java String Concatenation

Strings can be concatenated using the + operator.


  public class Main {
    public static void main(String[] args) {
      String firstName = "John";
      String lastName = "Doe";
      
      // Concatenating strings
      String fullName = firstName + " " + lastName;
      
      System.out.println("Full Name: " + fullName);
    }
  }
    

Output:


  Full Name: John Doe
    

Numbers and Strings in Java

In this section, we will learn how to work with numbers and strings together. We will explore how Java handles the conversion between numbers and strings.

Java Numbers and Strings

You can concatenate numbers with strings. Java automatically converts numbers to strings when using the + operator.


  public class Main {
    public static void main(String[] args) {
      int number = 100;
      String text = "The value is: ";
      
      // Concatenating number with string
      String result = text + number;
      
      System.out.println(result);
    }
  }
    

Output:


  The value is: 100
    

Special Characters in Strings

In this section, we will explore special characters in strings, such as escape sequences. These characters allow us to represent characters that would otherwise be difficult to include.

Special Characters in Strings

You can use escape sequences to include special characters in strings. For example, \n for a newline, \t for a tab, and \" for double quotes.


  public class Main {
    public static void main(String[] args) {
      System.out.println("Hello\nWorld!");  // Newline
      System.out.println("This is\ta tab.");  // Tab
      System.out.println("He said, \"Java is great!\"");  // Double quotes
    }
  }
    

Output:


  Hello
  World!
  This is    a tab.
  He said, "Java is great!"
    

Java Math

In this section, we will explore the Math class in Java. The Math class provides methods for performing basic mathematical operations such as square roots, powers, and trigonometric functions.

Java Math Methods

Java provides several static methods in the Math class to perform mathematical operations.


  public class Main {
    public static void main(String[] args) {
      double num = 25;
      double result = Math.sqrt(num);  // Square root of num
      System.out.println("Square root of " + num + " is: " + result);
      
      result = Math.pow(2, 3);  // 2 raised to the power of 3
      System.out.println("2 raised to the power of 3 is: " + result);
    }
  }
    

Output:


  Square root of 25.0 is: 5.0
  2 raised to the power of 3 is: 8.0
    

Java Booleans

In this section, we will explore the boolean data type in Java. A boolean represents one of two values: true or false.

Java Boolean Example

Booleans are often used in conditional statements to test expressions and control the flow of execution.


  public class Main {
    public static void main(String[] args) {
      boolean isJavaFun = true;
      boolean isFishTasty = false;
      
      System.out.println("Is Java fun? " + isJavaFun);
      System.out.println("Is fish tasty? " + isFishTasty);
    }
  }
    

Output:


  Is Java fun? true
  Is fish tasty? false
    

Java If...Else

In this section, we will explore the if, else, and else if statements in Java. These are used to perform different actions based on different conditions.

Java if Statement

The if statement allows you to test a condition and execute a block of code if the condition is true.


  public class Main {
    public static void main(String[] args) {
      int age = 20;
      
      if (age >= 18) {
        System.out.println("You are an adult.");
      }
    }
  }
    

Output:


  You are an adult.
    

Java else Statement

The else statement is used to execute a block of code when the condition in the if statement is false.


  public class Main {
    public static void main(String[] args) {
      int age = 16;
      
      if (age >= 18) {
        System.out.println("You are an adult.");
      } else {
        System.out.println("You are not an adult.");
      }
    }
  }
    

Output:


  You are not an adult.
    

Java else if Statement

The else if statement is used to test multiple conditions. It is useful when you have more than two conditions to test.


  public class Main {
    public static void main(String[] args) {
      int age = 20;
      
      if (age >= 18) {
        System.out.println("You are an adult.");
      } else if (age >= 13) {
        System.out.println("You are a teenager.");
      } else {
        System.out.println("You are a child.");
      }
    }
  }
    

Output:


  You are an adult.
    

Java Short Hand If... Else

The short-hand if...else (also called ternary operator) is a shorthand way of writing an if...else statement.


  public class Main {
    public static void main(String[] args) {
      int age = 20;
      
      String result = (age >= 18) ? "You are an adult." : "You are not an adult.";
      System.out.println(result);
    }
  }
    

Output:


  You are an adult.
    

Real-Life Examples of if...else

In this section, we will provide some real-life examples of how the if...else statements can be applied to make decisions in real life.

Real-Life Example Using if...else

Let's consider an example where we decide whether a person is eligible for a driver's license based on age.


  public class Main {
    public static void main(String[] args) {
      int age = 21;
      
      if (age >= 18) {
        System.out.println("You are eligible for a driver's license.");
      } else {
        System.out.println("You are not eligible for a driver's license.");
      }
    }
  }
    

Output:


  You are eligible for a driver's license.
    

Java Switch

In this section, we will explore the switch statement in Java. The switch statement allows you to execute one out of many blocks of code based on the value of a variable.

Java Switch Statement

The switch statement is used to execute one block of code among many options.


  public class Main {
    public static void main(String[] args) {
      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;
        default:
          System.out.println("Invalid day");
      }
    }
  }
    

Output:


  Wednesday
    

Java While Loop

In this section, we will explore the while loop in Java. A while loop is used to execute a block of code as long as a specified condition is true.

Java While Loop

The while loop runs a block of code as long as the condition evaluates to true.


  public class Main {
    public static void main(String[] args) {
      int i = 0;
      
      while (i < 5) {
        System.out.println(i);
        i++;
      }
    }
  }
    

Output:


  0
  1
  2
  3
  4
    

Java Do/While Loop

In this section, we will learn about the do...while loop. Unlike the while loop, the do...while loop will execute the block of code at least once before checking the condition.

Java Do/While Loop

The do...while loop is used to execute a block of code first and then check the condition.


  public class Main {
    public static void main(String[] args) {
      int i = 0;
      
      do {
        System.out.println(i);
        i++;
      } while (i < 5);
    }
  }
    

Output:


  0
  1
  2
  3
  4
    

Real-Life Examples of Loops

In this section, we will explore real-life examples of how loops can be applied to solve everyday problems using Java loops.

Real-Life Example: Counting a Range of Numbers

In this example, we will use a loop to count and print numbers from 1 to 10. This is a simple real-life scenario where we need to display numbers sequentially.


  public class Main {
    public static void main(String[] args) {
      int start = 1;
      int end = 10;
      
      for (int i = start; i <= end; i++) {
        System.out.println(i);
      }
    }
  }
    

Output:


  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
    

Real-Life Example: Calculating Factorial Using While Loop

This example calculates the factorial of a number using the while loop. Factorial is used in mathematical calculations like permutations and combinations.


  public class Main {
    public static void main(String[] args) {
      int number = 5;
      int factorial = 1;
      int i = 1;
      
      while (i <= number) {
        factorial *= i;
        i++;
      }
      
      System.out.println("Factorial of " + number + " is: " + factorial);
    }
  }
    

Output:


  Factorial of 5 is: 120
    

Java For Loop

In this section, we will explore the for loop in Java. The for loop is used to iterate over a block of code a specified number of times.

Java For Loop

The for loop is used when you know beforehand how many times you want to execute a statement or a block of statements.


  public class Main {
    public static void main(String[] args) {
      for (int i = 0; i < 5; i++) {
        System.out.println(i);
      }
    }
  }
    

Output:


  0
  1
  2
  3
  4
    

Nested Loops in Java

In this section, we will learn about nested loops in Java. A nested loop is a loop inside another loop. Nested loops are useful when dealing with multi-dimensional arrays or situations where you need to perform multiple iterations.

Nested For Loop

A nested for loop is a loop inside another for loop. In this example, we print a multiplication table.


  public class Main {
    public static void main(String[] args) {
      for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
          System.out.print(i * j + " ");
        }
        System.out.println();
      }
    }
  }
    

Output:


  1 2 3 
  2 4 6 
  3 6 9
    

Java For-Each Loop

In this section, we will explore the for-each loop in Java. The for-each loop is specifically used to iterate over arrays or collections. It simplifies the iteration process.

Java For-Each Loop

The for-each loop is used for iterating over arrays or collections. It eliminates the need to use an index variable.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {1, 2, 3, 4, 5};
      
      for (int num : numbers) {
        System.out.println(num);
      }
    }
  }
    

Output:


  1
  2
  3
  4
  5
    

Real-Life Examples of For Loops

In this section, we will explore real-life examples of how for loops can be applied to solve everyday problems using Java loops.

Real-Life Example: Printing Even Numbers

This example prints all even numbers from 1 to 20 using a for loop.


  public class Main {
    public static void main(String[] args) {
      for (int i = 2; i <= 20; i += 2) {
        System.out.println(i);
      }
    }
  }
    

Output:


  2
  4
  6
  8
  10
  12
  14
  16
  18
  20
    

Java Break and Continue

In this section, we will explore the break and continue statements in Java. The break statement is used to exit from a loop, while the continue statement skips the current iteration and moves to the next iteration.

Using Break in Loop

The break statement can be used to exit the loop prematurely, even if the loop condition has not been met.


  public class Main {
    public static void main(String[] args) {
      for (int i = 0; i < 5; i++) {
        if (i == 3) {
          break; // Exit the loop when i is 3
        }
        System.out.println(i);
      }
    }
  }
    

Output:


  0
  1
  2
    

Using Continue in Loop

The continue statement is used to skip the current iteration of the loop and continue with the next iteration.


  public class Main {
    public static void main(String[] args) {
      for (int i = 0; i < 5; i++) {
        if (i == 2) {
          continue; // Skip the iteration when i is 2
        }
        System.out.println(i);
      }
    }
  }
    

Output:


  0
  1
  3
  4
    

Java Arrays

In this section, we will learn about arrays in Java. An array is a container that holds a fixed number of values of a single type.

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {10, 20, 30, 40, 50};
      System.out.println(numbers[2]);  // Outputs: 30
    }
  }
    

Output:


  30
    

Loop Through an Array

In this section, we will explore how to loop through an array in Java. You can use various loop structures like for or for-each to iterate through array elements.

Loop Through an Array using For Loop

You can use a for loop to iterate through the elements of an array and print each element.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {10, 20, 30, 40, 50};
      
      for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
      }
    }
  }
    

Output:


  10
  20
  30
  40
  50
    

Loop Through an Array using For-Each Loop

The for-each loop provides a simpler way to iterate over arrays and collections.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {10, 20, 30, 40, 50};
      
      for (int num : numbers) {
        System.out.println(num);
      }
    }
  }
    

Output:


  10
  20
  30
  40
  50
    

Real-Life Examples of Arrays

In this section, we will explore some real-life examples where arrays can be applied in Java.

Real-Life Example: Storing Student Marks

Here we store the marks of students in an array and calculate their average.


  public class Main {
    public static void main(String[] args) {
      int[] marks = {85, 90, 78, 92, 88};
      int sum = 0;
      
      for (int mark : marks) {
        sum += mark;
      }
      
      double average = sum / (double) marks.length;
      System.out.println("Average Marks: " + average);
    }
  }
    

Output:


  Average Marks: 86.6
    

Java Multidimensional Arrays

In this section, we will learn about multidimensional arrays. These arrays store data in multiple dimensions and can be thought of as arrays of arrays.

Java Multidimensional Arrays

A multidimensional array is an array of arrays. It can be used to represent data in a grid-like structure, such as a matrix.


  public class Main {
    public static void main(String[] args) {
      int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
      };
      
      System.out.println(matrix[1][2]); // Outputs: 6
    }
  }
    

Output:


  6
    

Looping Through Multidimensional Arrays

You can use nested loops to loop through a multidimensional array.


  public class Main {
    public static void main(String[] args) {
      int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
      };
      
      for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
          System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
      }
    }
  }
    

Output:


  1 2 3 
  4 5 6 
  7 8 9
    

Java Methods

In this section, we will learn about methods in Java. A method is a block of code that performs a specific task. Methods allow code reusability and help in organizing the program logically.

Java Methods

A method is defined with a return type, method name, and parameters (optional). The method can be called from the main method or other methods.


  public class Main {
    public static void main(String[] args) {
      greet();  // Calling the method
    }
  
    // Method definition
    public static void greet() {
      System.out.println("Hello, Welcome to Java!");
    }
  }
    

Output:


  Hello, Welcome to Java!
    

Java Method Parameters

In this section, we will discuss method parameters. Parameters are values that you pass into a method to provide input for the task the method is supposed to perform.

Java Method Parameters

Methods can take parameters, allowing them to work with different inputs. You pass arguments to a method when calling it.


  public class Main {
    public static void main(String[] args) {
      int sum = add(5, 10);  // Passing arguments
      System.out.println("Sum: " + sum);
    }
  
    // Method with parameters
    public static int add(int a, int b) {
      return a + b;
    }
  }
    

Output:


  Sum: 15
    

Java Method Return Values

In this section, we will learn about return values in Java methods. A method can return a value to the caller, which can be used for further processing.

Returning Values from Methods

A method can return a value, which can be of any data type. The value returned can then be used in the calling code.


  public class Main {
    public static void main(String[] args) {
      int product = multiply(5, 4);  // Getting return value
      System.out.println("Product: " + product);
    }
  
    // Method with return value
    public static int multiply(int a, int b) {
      return a * b;
    }
  }
    

Output:


  Product: 20
    

Java Method Overloading

In this section, we will learn about method overloading. It is a feature in Java where multiple methods have the same name but differ in the number or type of parameters.

Method Overloading

Method overloading is when two or more methods have the same name but different parameters.


  public class Main {
    public static void main(String[] args) {
      System.out.println(add(5, 10));       // Calls add(int, int)
      System.out.println(add(5.5, 10.5));   // Calls add(double, double)
    }
  
    // Overloaded methods
    public static int add(int a, int b) {
      return a + b;
    }
  
    public static double add(double a, double b) {
      return a + b;
    }
  }
    

Output:


  15
  16.0
    

Java Scope

In this section, we will learn about scope in Java. Scope refers to the visibility and lifetime of variables within different parts of the program.

Local and Global Scope

Variables in Java can have either local scope (inside methods) or global scope (class-level variables).


  public class Main {
    static int globalVar = 10; // Global scope
  
    public static void main(String[] args) {
      int localVar = 20;  // Local scope
      System.out.println("Global Variable: " + globalVar);
      System.out.println("Local Variable: " + localVar);
    }
  }
    

Output:


  Global Variable: 10
  Local Variable: 20
    

Java Recursion

In this section, we will learn about recursion in Java. Recursion is a process where a method calls itself to solve a problem.

Java Recursion

A classic example of recursion is calculating the factorial of a number. In recursion, a method calls itself with reduced values.


  public class Main {
    public static void main(String[] args) {
      int result = factorial(5);
      System.out.println("Factorial of 5: " + result);
    }
  
    // Recursive method to find factorial
    public static int factorial(int n) {
      if (n == 1) {
        return 1;  // Base case
      } else {
        return n * factorial(n - 1);  // Recursive case
      }
    }
  }
    

Output:


  Factorial of 5: 120
    

Java Classes

In this section, we will learn about classes in Java. A class is a blueprint for creating objects, providing initial values for state (member variables), and implementations of behavior (member methods).

Defining a Java Class

In Java, a class is defined using the class keyword, followed by the class name. Inside a class, you can define attributes (variables) and methods (functions) to represent the state and behavior of objects.


  public class Car {
    // Attributes
    String color;
    String model;
  
    // Method
    public void start() {
      System.out.println("The car has started.");
    }
  }
    

Java OOP (Object-Oriented Programming)

Java is an object-oriented programming language, which means it is based on the concept of objects and classes. OOP helps in organizing and structuring code more efficiently.

Key Principles of OOP

The four main principles of object-oriented programming are:

Java Classes and Objects

In this section, we will discuss how to create objects from classes. A class serves as a blueprint, and an object is an instance of that class. We can create multiple objects from the same class.

Creating and Using Objects

To create an object, you use the new keyword followed by the class constructor. Once created, you can access the attributes and methods of the object.


  public class Main {
    public static void main(String[] args) {
      // Creating an object of the Car class
      Car myCar = new Car();
      myCar.color = "Red";
      myCar.model = "Toyota";
  
      // Calling the start method
      myCar.start();
      System.out.println("Car Model: " + myCar.model);
      System.out.println("Car Color: " + myCar.color);
    }
  }
  
  class Car {
    String color;
    String model;
  
    public void start() {
      System.out.println("The car has started.");
    }
  }
    

Output:


  The car has started.
  Car Model: Toyota
  Car Color: Red
    

Java Class Attributes

In this section, we will discuss class attributes. These are variables declared inside a class but outside any method. They represent the state or properties of an object.

Class Attributes

Class attributes are defined inside the class but outside methods. These attributes represent the properties of an object.


  public class Main {
    public static void main(String[] args) {
      // Creating an object of the Car class
      Car myCar = new Car();
      myCar.color = "Blue";
      myCar.model = "BMW";
      System.out.println("Car Model: " + myCar.model);
      System.out.println("Car Color: " + myCar.color);
    }
  }
  
  class Car {
    // Class attributes
    String color;
    String model;
  }
    

Output:


  Car Model: BMW
  Car Color: Blue
    

Java Class Methods

In this section, we will discuss methods in a class. A method is a function defined inside a class that defines the behavior of an object.

Defining and Calling Methods

Methods inside a class can be called on an object. These methods define the actions that an object can perform.


  public class Main {
    public static void main(String[] args) {
      Car myCar = new Car();
      myCar.color = "Green";
      myCar.start();
    }
  }
  
  class Car {
    String color;
  
    // Class method
    public void start() {
      System.out.println("The " + color + " car has started.");
    }
  }
    

Output:


  The Green car has started.
    

Java Constructors

In this section, we will learn about constructors. A constructor is a special method used to initialize objects. It has the same name as the class and is called when an object is created.

Using Constructors

Constructors are used to initialize the state of an object. If no constructor is defined, the default constructor is used.


  public class Main {
    public static void main(String[] args) {
      // Creating an object using the constructor
      Car myCar = new Car("Red", "Toyota");
      System.out.println("Car Model: " + myCar.model);
      System.out.println("Car Color: " + myCar.color);
    }
  }
  
  class Car {
    String color;
    String model;
  
    // Constructor
    public Car(String color, String model) {
      this.color = color;
      this.model = model;
    }
  }
    

Output:


  Car Model: Toyota
  Car Color: Red
    

Java Modifiers

In this section, we will explore modifiers in Java. Modifiers determine the visibility and behavior of classes, methods, and variables.

Access Modifiers

In Java, access modifiers such as public, private, and protected control the visibility of classes, methods, and variables.


  public class Main {
    public static void main(String[] args) {
      Car myCar = new Car();
      myCar.color = "Yellow";  // Accessible
      System.out.println("Car Color: " + myCar.color);
    }
  }
  
  class Car {
    public String color;  // Public attribute
  }
    

Output:


  Car Color: Yellow
    

Java Encapsulation

In this section, we will discuss encapsulation. Encapsulation is the technique of bundling data (variables) and methods that operate on that data into a single unit, i.e., a class.

Encapsulation with Getter and Setter

Encapsulation is achieved by providing private access to variables and using public getter and setter methods to access and modify them.


  public class Main {
    public static void main(String[] args) {
      Car myCar = new Car();
      myCar.setColor("Black");
      System.out.println("Car Color: " + myCar.getColor());
    }
  }
  
  class Car {
    private String color;
  
    // Getter and Setter methods
    public String getColor() {
      return color;
    }
  
    public void setColor(String color) {
      this.color = color;
    }
  }
    

Output:


  Car Color: Black
    

Java Packages / API

In this section, we will learn about Java Packages and how to use built-in Java APIs. Packages are used to group related classes and interfaces.

Using Java Packages

A package in Java is used to organize classes and interfaces into namespaces. You can import pre-defined classes using the import keyword.


  // Importing the Scanner class from java.util package
  import java.util.Scanner;
  
  public class Main {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);  // Create Scanner object to get user input
      System.out.print("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Hello, " + name);
    }
  }
    

Output:


  Enter your name: John
  Hello, John
    

Java Inheritance

Inheritance is a mechanism in Java where one class acquires the properties (fields) and behaviors (methods) of another class. Inheritance supports reusability.

Creating Subclass and Superclass

A subclass inherits from a superclass. In Java, the extends keyword is used to define a subclass.


  class Animal {
    public void sound() {
      System.out.println("Animals make sound.");
    }
  }
  
  class Dog extends Animal {
    public void sound() {
      System.out.println("Dog barks.");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound();  // Calls the overridden method from Dog class
    }
  }
    

Output:


  Dog barks.
    

Java Polymorphism

Polymorphism allows one interface to be used for a general class of actions. It can take two forms: method overriding and method overloading.

Method Overloading and Overriding

Polymorphism enables one method to behave differently based on the object that is calling it (method overriding), or to have multiple methods with the same name but different parameters (method overloading).


  class Animal {
    public void sound() {
      System.out.println("Animal makes a sound.");
    }
    
    // Method Overloading
    public void sound(String sound) {
      System.out.println("Animal makes a " + sound);
    }
  }
  
  class Dog extends Animal {
    public void sound() {
      System.out.println("Dog barks.");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Animal animal = new Animal();
      animal.sound();  // Calls the Animal class method
      animal.sound("growl");  // Overloaded method
  
      Dog dog = new Dog();
      dog.sound();  // Overridden method in Dog class
    }
  }
    

Output:


  Animal makes a sound.
  Animal makes a growl
  Dog barks.
    

Java Inner Classes

In Java, you can define a class inside another class. These are known as inner classes, and they have access to the instance variables and methods of the outer class.

Inner Classes Example

Inner classes are useful for grouping classes that will only be used in one place.


  class OuterClass {
    private String message = "Hello from Outer Class!";
    
    // Inner Class
    class InnerClass {
      public void showMessage() {
        System.out.println(message);  // Accessing Outer Class variable
      }
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      OuterClass outer = new OuterClass();
      OuterClass.InnerClass inner = outer.new InnerClass();  // Creating instance of inner class
      inner.showMessage();
    }
  }
    

Output:


  Hello from Outer Class!
    

Java Abstraction

Abstraction is the concept of hiding the complex implementation details and showing only the necessary features of an object. It is achieved through abstract classes or interfaces.

Abstract Classes

An abstract class is a class that cannot be instantiated directly. It may contain abstract methods (methods without a body) that must be implemented by subclasses.


  abstract class Animal {
    abstract void sound();
    
    public void eat() {
      System.out.println("Animal eats food.");
    }
  }
  
  class Dog extends Animal {
    public void sound() {
      System.out.println("Dog barks.");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Animal dog = new Dog();
      dog.sound();
      dog.eat();
    }
  }
    

Output:


  Dog barks.
  Animal eats food.
    

Java Interface

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields.

Using Interfaces

An interface defines methods that a class must implement. A class can implement multiple interfaces, and this is one of the ways Java supports multiple inheritance.


  interface Animal {
    void sound();
  }
  
  interface Pet {
    void play();
  }
  
  class Dog implements Animal, Pet {
    public void sound() {
      System.out.println("Dog barks.");
    }
  
    public void play() {
      System.out.println("Dog plays with a ball.");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound();
      dog.play();
    }
  }
    

Output:


  Dog barks.
  Dog plays with a ball.
    

Java Enums

Enum in Java is a special class that represents a group of constants (unchangeable variables). Enums are a powerful way to define sets of constants.

Using Enums

An enum is a class that represents a collection of constants.


  enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
  }
  
  public class Main {
    public static void main(String[] args) {
      Day today = Day.MONDAY;
      System.out.println("Today is: " + today);
    }
  }
    

Output:


  Today is: MONDAY
    

Java User Input

Java provides the Scanner class for obtaining user input. It allows reading various types of data like strings, numbers, etc.

Getting User Input

To get input from the user, we use the nextLine() method of the Scanner class for strings or nextInt() for integers.


  import java.util.Scanner;
  
  public class Main {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      
      System.out.print("Enter your age: ");
      int age = sc.nextInt();  // Read integer value
      System.out.println("Your age is: " + age);
    }
  }
    

Output:


  Enter your age: 25
  Your age is: 25
    

Java Date

In Java, the java.util.Date class represents a specific instant in time, with millisecond precision. It is used to manipulate and format dates and times.

Using Java Date

The java.util.Date class provides methods for manipulating dates and times. Here's an example:


  import java.util.Date;
  
  public class Main {
    public static void main(String[] args) {
      Date date = new Date();  // Get the current date and time
      System.out.println("Current date and time: " + date);
    }
  }
    

Output:


  Current date and time: Sat Jan 11 10:59:42 IST 2025
    

Java ArrayList

An ArrayList is a resizable array implementation of the List interface. It allows storing dynamic data and provides several methods to manipulate the list.

Using ArrayList

The ArrayList class provides methods for adding, removing, and accessing elements dynamically.


  import java.util.ArrayList;
  
  public class Main {
    public static void main(String[] args) {
      ArrayList fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Orange");
  
      // Accessing elements
      System.out.println(fruits.get(1));  // Output: Banana
    }
  }
    

Output:


  Banana
    

Java LinkedList

A LinkedList is a collection that stores elements in a doubly linked list. Unlike an ArrayList, a LinkedList uses pointers to link each element to the next and previous elements.

Using LinkedList

The LinkedList class implements both the List and Deque interfaces and provides methods for adding, removing, and accessing elements in the list.


  import java.util.LinkedList;
  
  public class Main {
    public static void main(String[] args) {
      LinkedList cities = new LinkedList<>();
      cities.add("New York");
      cities.add("Los Angeles");
      cities.add("Chicago");
  
      // Accessing elements
      System.out.println(cities.get(2));  // Output: Chicago
    }
  }
    

Output:


  Chicago
    

Java List Sorting

In Java, you can sort a list using the Collections.sort() method. It sorts elements based on their natural order or by using a custom comparator.

Sorting a List

The Collections.sort() method can be used to sort lists in ascending or descending order.


  import java.util.ArrayList;
  import java.util.Collections;
  
  public class Main {
    public static void main(String[] args) {
      ArrayList numbers = new ArrayList<>();
      numbers.add(5);
      numbers.add(2);
      numbers.add(8);
      
      // Sorting in ascending order
      Collections.sort(numbers);
      System.out.println("Sorted list: " + numbers);
    }
  }
    

Output:


  Sorted list: [2, 5, 8]
    

Java HashMap

A HashMap is a collection that stores key-value pairs. It allows fast access to elements based on keys.

Using HashMap

A HashMap is used to store data in the form of key-value pairs. You can access the values using the keys.


  import java.util.HashMap;
  
  public class Main {
    public static void main(String[] args) {
      HashMap capitals = new HashMap<>();
      capitals.put("USA", "Washington, D.C.");
      capitals.put("India", "New Delhi");
  
      // Accessing value using key
      System.out.println("Capital of USA: " + capitals.get("USA"));
    }
  }
    

Output:


  Capital of USA: Washington, D.C.
    

Java HashSet

A HashSet is a collection that does not allow duplicate elements. It stores elements in an unordered manner.

Using HashSet

A HashSet allows you to store elements without any duplicates. If you try to add a duplicate, it will not be added.


  import java.util.HashSet;
  
  public class Main {
    public static void main(String[] args) {
      HashSet fruits = new HashSet<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Apple");  // Duplicate element, will not be added
  
      System.out.println(fruits);  // Output: [Apple, Banana]
    }
  }
    

Output:


  [Apple, Banana]
    

Java Iterator

An Iterator is an object that can be used to traverse through a collection (like ArrayList, HashSet, etc.).

Using Iterator

The Iterator interface provides methods to iterate through elements, such as hasNext() and next().


  import java.util.ArrayList;
  import java.util.Iterator;
  
  public class Main {
    public static void main(String[] args) {
      ArrayList fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Orange");
  
      Iterator iterator = fruits.iterator();
      while (iterator.hasNext()) {
        System.out.println(iterator.next());
      }
    }
  }
    

Output:


  Apple
  Banana
  Orange
    

Java Wrapper Classes

Java Wrapper Classes provide a way to use primitive data types (like int, char, etc.) as objects. These classes are part of the java.lang package and allow for easy conversion between primitive types and their corresponding objects.

Using Wrapper Classes

Wrapper classes in Java allow you to convert primitive types into objects. For example, Integer is a wrapper class for the int primitive type.


  public class Main {
    public static void main(String[] args) {
      int num = 10;
      Integer numWrapper = Integer.valueOf(num);  // Convert int to Integer object
      System.out.println("Integer Wrapper: " + numWrapper);
    }
  }
    

Output:


  Integer Wrapper: 10
    

Java Exceptions

Exceptions are unwanted or unexpected events that can occur during the execution of a program. Java provides a robust mechanism for handling errors using try-catch blocks.

Handling Exceptions

In Java, you can handle exceptions using the try-catch blocks. This helps you to maintain the normal flow of the program even if an exception occurs.


  public class Main {
    public static void main(String[] args) {
      try {
        int result = 10 / 0;  // This will throw an exception
      } catch (ArithmeticException e) {
        System.out.println("Error: " + e.getMessage());  // Handling the exception
      }
    }
  }
    

Output:


  Error: / by zero
    

Java RegEx

Java Regular Expressions (RegEx) are used for pattern matching within strings. The java.util.regex package provides the classes for using regular expressions.

Using Regular Expressions

Regular expressions allow you to perform pattern matching on strings. Here's an example of using RegEx to validate an email address.


  import java.util.regex.*;
  
  public class Main {
    public static void main(String[] args) {
      String email = "test@example.com";
      String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
  
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(email);
  
      if (matcher.matches()) {
        System.out.println("Valid Email!");
      } else {
        System.out.println("Invalid Email!");
      }
    }
  }
    

Output:


  Valid Email!
    

Java Threads

Java Threads allow for multi-threading, meaning multiple tasks can run concurrently. The Thread class and the Runnable interface are used for creating threads.

Creating a Thread

Threads in Java are created by either extending the Thread class or implementing the Runnable interface. Here's an example of creating a thread by extending the Thread class.


  class MyThread extends Thread {
    public void run() {
      System.out.println("Thread is running");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      MyThread thread = new MyThread();
      thread.start();  // Start the thread
    }
  }
    

Output:


  Thread is running
    

Java Lambda

Java Lambda expressions enable you to treat functionality as a method argument, or to create a short method without a name. Lambdas are used primarily to define the behavior of the functional interfaces.

Using Lambda Expressions

Lambda expressions provide a clear and concise way to represent a method in the form of an expression. Here's an example of using a lambda expression to implement a functional interface.


  interface MyFunction {
    void printMessage(String message);
  }
  
  public class Main {
    public static void main(String[] args) {
      MyFunction function = (message) -> System.out.println(message);
      function.printMessage("Hello, Lambda!");
    }
  }
    

Output:


  Hello, Lambda!
    

Java Advanced Sorting

Advanced sorting allows you to sort data in customized ways. Java provides various methods such as Comparator and Comparable for advanced sorting.

Using Comparator for Sorting

The Comparator interface can be used to define custom sorting logic for collections. Here's an example where we sort a list of strings by length using a comparator.


  import java.util.*;
  
  public class Main {
    public static void main(String[] args) {
      List fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Kiwi");
  
      // Sorting by length using Comparator
      fruits.sort((a, b) -> a.length() - b.length());
  
      System.out.println(fruits);
    }
  }
    

Output:


  [Kiwi, Apple, Banana]
    

Java File Handling

Java provides a comprehensive API for file handling, allowing you to create, read, write, and delete files. The java.io package is used for file input and output operations.

Understanding Files in Java

In Java, files are represented as objects of the File class from the java.io package. You can use the File class to perform operations like checking file existence, getting file properties, and more.


  import java.io.File;
  
  public class Main {
    public static void main(String[] args) {
      File file = new File("example.txt");
  
      // Checking if the file exists
      if (file.exists()) {
        System.out.println("File exists.");
      } else {
        System.out.println("File does not exist.");
      }
    }
  }
    

Output:


  File does not exist.
    

Java Create/Write Files

Java allows you to create and write data to files using classes like FileWriter and BufferedWriter. Here's how you can create and write to a file.

Creating and Writing to a File

You can use the FileWriter class to create a new file and write data to it. The file will be created in the specified location.


  import java.io.FileWriter;
  import java.io.BufferedWriter;
  import java.io.IOException;
  
  public class Main {
    public static void main(String[] args) {
      try {
        FileWriter writer = new FileWriter("example.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
  
        bufferedWriter.write("Hello, World!");
        bufferedWriter.close();
        System.out.println("File written successfully.");
      } catch (IOException e) {
        System.out.println("An error occurred: " + e.getMessage());
      }
    }
  }
    

Output:


  File written successfully.
    

Java Read Files

You can read data from a file in Java using the FileReader and BufferedReader classes. This allows you to fetch the contents of a file line by line.

Reading from a File

In this example, we'll read the content of a file using FileReader and BufferedReader to output the file contents to the console.


  import java.io.FileReader;
  import java.io.BufferedReader;
  import java.io.IOException;
  
  public class Main {
    public static void main(String[] args) {
      try {
        FileReader reader = new FileReader("example.txt");
        BufferedReader bufferedReader = new BufferedReader(reader);
  
        String line;
        while ((line = bufferedReader.readLine()) != null) {
          System.out.println(line);
        }
        bufferedReader.close();
      } catch (IOException e) {
        System.out.println("An error occurred: " + e.getMessage());
      }
    }
  }
    

Output:


  Hello, World!
    

Java Delete Files

In Java, you can delete files using the delete() method of the File class. This will remove the file from the file system.

Deleting a File

To delete a file in Java, simply create a File object representing the file you want to delete, and then call its delete() method.


  import java.io.File;
  
  public class Main {
    public static void main(String[] args) {
      File file = new File("example.txt");
  
      if (file.delete()) {
        System.out.println("File deleted successfully.");
      } else {
        System.out.println("Failed to delete the file.");
      }
    }
  }
    

Output:


  File deleted successfully.
    

Java How To's

Here are a few examples of common Java operations and their implementations, such as adding two numbers, counting words, reversing a string, and other array manipulations.

Adding Two Numbers

This example shows how to add two numbers in Java.


  import java.util.Scanner;
  
  public class Main {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter first number: ");
      int num1 = sc.nextInt();
      System.out.print("Enter second number: ");
      int num2 = sc.nextInt();
  
      int sum = num1 + num2;
      System.out.println("Sum of the numbers: " + sum);
    }
  }
    

Output:


  Enter first number: 5
  Enter second number: 7
  Sum of the numbers: 12
    

Counting Words in a String

This example demonstrates how to count the number of words in a string.


  public class Main {
    public static void main(String[] args) {
      String sentence = "Java is awesome and easy to learn!";
      String[] words = sentence.split("\\s+");
      System.out.println("Number of words: " + words.length);
    }
  }
    

Output:


  Number of words: 6
    

Reversing a String

This example demonstrates how to reverse a string in Java.


  public class Main {
    public static void main(String[] args) {
      String original = "Java Programming";
      String reversed = new StringBuilder(original).reverse().toString();
      System.out.println("Reversed string: " + reversed);
    }
  }
    

Output:


  Reversed string: gnimmargorP avaJ
    

Sum of Array Elements

This example shows how to find the sum of all elements in an array.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {1, 2, 3, 4, 5};
      int sum = 0;
      
      for (int num : numbers) {
        sum += num;
      }
      
      System.out.println("Sum of array elements: " + sum);
    }
  }
    

Output:


  Sum of array elements: 15
    

Convert String to Array

This example demonstrates how to convert a string into an array of characters.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char[] charArray = str.toCharArray();
  
      System.out.println("String to array:");
      for (char c : charArray) {
        System.out.print(c + " ");
      }
    }
  }
    

Output:


  String to array:
  H e l l o 
    

Sort an Array

This example demonstrates how to sort an array of integers in Java.


  import java.util.Arrays;
  
  public class Main {
    public static void main(String[] args) {
      int[] numbers = {5, 2, 8, 1, 3};
      
      Arrays.sort(numbers);
      
      System.out.println("Sorted array:");
      for (int num : numbers) {
        System.out.print(num + " ");
      }
    }
  }
    

Output:


  Sorted array:
  1 2 3 5 8
    

Find Array Average

This example shows how to calculate the average of elements in an array.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {10, 20, 30, 40, 50};
      int sum = 0;
      
      for (int num : numbers) {
        sum += num;
      }
      
      double average = sum / (double) numbers.length;
      System.out.println("Average of array elements: " + average);
    }
  }
    

Output:


  Average of array elements: 30.0
    

Find Smallest Element in Array

This example demonstrates how to find the smallest element in an array.


  public class Main {
    public static void main(String[] args) {
      int[] numbers = {5, 2, 8, 1, 3};
      
      int smallest = numbers[0];
      for (int num : numbers) {
        if (num < smallest) {
          smallest = num;
        }
      }
      
      System.out.println("Smallest element in array: " + smallest);
    }
  }
    

Output:


  Smallest element in array: 1
    

Java How To's (Continued)

Continuing with more examples like looping through an ArrayList, calculating the area of a rectangle, checking number properties, and generating random numbers.

Loop Through ArrayList

This example demonstrates how to loop through an ArrayList using a for-each loop.


  import java.util.ArrayList;
  
  public class Main {
    public static void main(String[] args) {
      ArrayList fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Banana");
      fruits.add("Orange");
  
      for (String fruit : fruits) {
        System.out.println(fruit);
      }
    }
  }
    

Output:


  Apple
  Banana
  Orange
    

Loop Through HashMap

This example shows how to loop through a HashMap using entrySet() and a for-each loop.


  import java.util.HashMap;
  import java.util.Map;
  
  public class Main {
    public static void main(String[] args) {
      HashMap capitals = new HashMap<>();
      capitals.put("India", "New Delhi");
      capitals.put("USA", "Washington D.C.");
      capitals.put("Japan", "Tokyo");
  
      for (Map.Entry entry : capitals.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
      }
    }
  }
    

Output:


  India: New Delhi
  USA: Washington D.C.
  Japan: Tokyo
    

Loop Through an Enum

This example demonstrates how to loop through an Enum using the values() method.


  enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
  }
  
  public class Main {
    public static void main(String[] args) {
      for (Day day : Day.values()) {
        System.out.println(day);
      }
    }
  }
    

Output:


  MONDAY
  TUESDAY
  WEDNESDAY
  THURSDAY
  FRIDAY
  SATURDAY
  SUNDAY
    

Area of a Rectangle

This example shows how to calculate the area of a rectangle.


  public class Main {
    public static void main(String[] args) {
      double length = 5.0;
      double width = 3.0;
      
      double area = length * width;
      System.out.println("Area of rectangle: " + area);
    }
  }
    

Output:


  Area of rectangle: 15.0
    

Check Even or Odd Number

This example demonstrates how to check if a number is even or odd.


  public class Main {
    public static void main(String[] args) {
      int number = 7;
      
      if (number % 2 == 0) {
        System.out.println(number + " is even.");
      } else {
        System.out.println(number + " is odd.");
      }
    }
  }
    

Output:


  7 is odd.
    

Check if Number is Positive or Negative

This example demonstrates how to check if a number is positive or negative.


  public class Main {
    public static void main(String[] args) {
      int number = -5;
      
      if (number > 0) {
        System.out.println(number + " is positive.");
      } else if (number < 0) {
        System.out.println(number + " is negative.");
      } else {
        System.out.println("The number is zero.");
      }
    }
  }
    

Output:


  -5 is negative.
    

Calculate Square Root

This example shows how to calculate the square root of a number.


  public class Main {
    public static void main(String[] args) {
      double number = 16;
      
      double squareRoot = Math.sqrt(number);
      System.out.println("Square root of " + number + " is: " + squareRoot);
    }
  }
    

Output:


  Square root of 16 is: 4.0
    

Generate Random Number

This example demonstrates how to generate a random number in Java.


  import java.util.Random;
  
  public class Main {
    public static void main(String[] args) {
      Random random = new Random();
      int randomNumber = random.nextInt(100);  // Generates a random number between 0 and 99
      
      System.out.println("Random number: " + randomNumber);
    }
  }
    

Output:


  Random number: 42
    

Java Reference

In this section, we will explore various important Java keywords and their usage. Keywords are reserved words in Java that have special meanings.

Java Keywords

Keywords in Java are predefined identifiers used to define the structure of the code. They cannot be used as variable names or identifiers.

assert Keyword Example

The assert keyword is used for debugging purposes, and it checks the truth of a condition.


  public class Main {
    public static void main(String[] args) {
      int number = -5;
      assert number > 0 : "Number is not positive"; // This will throw an error because the condition is false
    }
  }
    

Output:


  Exception in thread "main" java.lang.AssertionError: Number is not positive
    

abstract Keyword Example

The abstract keyword defines an abstract class or method. It is used to declare methods that must be implemented by subclasses.


  abstract class Animal {
    abstract void sound(); // Abstract method
  }
  
  class Dog extends Animal {
    void sound() {
      System.out.println("Bark");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Animal myDog = new Dog();
      myDog.sound(); // Outputs: Bark
    }
  }
    

Output:


  Bark
    

boolean Keyword Example

The boolean keyword defines a variable that can hold either true or false.


  public class Main {
    public static void main(String[] args) {
      boolean isJavaFun = true;
      System.out.println(isJavaFun); // Outputs: true
    }
  }
    

Output:


  true
    

break Keyword Example

The break keyword is used to exit from a loop or a switch statement prematurely.


  public class Main {
    public static void main(String[] args) {
      for (int i = 1; i <= 5; i++) {
        if (i == 3) {
          break; // Exit the loop when i equals 3
        }
        System.out.println(i);
      }
    }
  }
    

Output:


  1
  2
    

byte Keyword Example

The byte keyword defines a variable that can store a signed 8-bit integer.


  public class Main {
    public static void main(String[] args) {
      byte b = 100; // byte variable
      System.out.println(b); // Outputs: 100
    }
  }
    

Output:


  100
    

case Keyword Example

The case keyword is used in a switch statement to define the possible values.


  public class Main {
    public static void main(String[] args) {
      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"); // Matched case
          break;
        default:
          System.out.println("Invalid day");
      }
    }
  }
    

Output:


  Wednesday
    

catch Keyword Example

The catch keyword defines a block of code that handles exceptions in a try-catch statement.


  public class Main {
    public static void main(String[] args) {
      try {
        int result = 10 / 0; // Causes an ArithmeticException
      } catch (ArithmeticException e) {
        System.out.println("Error: " + e.getMessage()); // Catches the exception
      }
    }
  }
    

Output:


  Error: / by zero
    

Conclusion

Java keywords are predefined identifiers that cannot be used as variable names. They define the structure of the program and are essential for creating a Java application.

Java Reference

In this section, we will explore various important Java keywords and their usage. Keywords are reserved words in Java that have special meanings.

Java Keywords

Keywords in Java are predefined identifiers used to define the structure of the code. They cannot be used as variable names or identifiers.

double Keyword Example

The double keyword defines a variable that can store a double-precision floating-point number.


  public class Main {
    public static void main(String[] args) {
      double price = 19.99;
      System.out.println(price); // Outputs: 19.99
    }
  }
    

Output:


  19.99
    

else Keyword Example

The else keyword defines a block of code to execute if the condition in an if statement is false.


  public class Main {
    public static void main(String[] args) {
      int num = 10;
      if (num > 20) {
        System.out.println("Greater");
      } else {
        System.out.println("Lesser or Equal"); // Executes because 10 is not greater than 20
      }
    }
  }
    

Output:


  Lesser or Equal
    

enum Keyword Example

The enum keyword defines a set of named constants. It is often used to represent fixed values such as days of the week, colors, etc.


  enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
  
  public class Main {
    public static void main(String[] args) {
      Day today = Day.MONDAY;
      System.out.println(today); // Outputs: MONDAY
    }
  }
    

Output:


  MONDAY
    

exports Keyword Example

The exports keyword is used in Java 9 and above to specify which packages are accessible to other modules in the module system.


  module MyModule {
    exports com.myapp;
  }
    

Explanation:

This code declares that the package com.myapp is accessible to other modules in the Java module system.

extends Keyword Example

The extends keyword is used in Java to inherit from a superclass and access its properties and methods.


  class Animal {
    void sound() {
      System.out.println("Animal sound");
    }
  }
  
  class Dog extends Animal { 
    void sound() {
      System.out.println("Bark");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound(); // Outputs: Bark
    }
  }
    

Output:


  Bark
    

final Keyword Example

The final keyword is used to declare constants, methods that cannot be overridden, and classes that cannot be inherited.


  final int MAX_VALUE = 100; // constant
  MAX_VALUE = 200; // Error: cannot assign a value to a final variable
    

Explanation:

The MAX_VALUE variable cannot be reassigned because it is declared as final.

finally Keyword Example

The finally keyword defines a block of code that will always execute after a try-catch block, regardless of whether an exception is thrown.


  public class Main {
    public static void main(String[] args) {
      try {
        int result = 10 / 0; // Causes an ArithmeticException
      } catch (ArithmeticException e) {
        System.out.println("Error: " + e.getMessage());
      } finally {
        System.out.println("This will always execute."); // Always executes
      }
    }
  }
    

Output:


  Error: / by zero
  This will always execute.
    

float Keyword Example

The float keyword defines a variable that can store a single-precision floating-point number.


  public class Main {
    public static void main(String[] args) {
      float price = 19.99f; // float value
      System.out.println(price); // Outputs: 19.99
    }
  }
    

Output:


  19.99
    

for Keyword Example

The for keyword is used to define a loop that executes a block of code for a set number of iterations.


  public class Main {
    public static void main(String[] args) {
      for (int i = 1; i <= 5; i++) {
        System.out.println(i); // Outputs: 1 2 3 4 5
      }
    }
  }
    

Output:


  1
  2
  3
  4
  5
    

if Keyword Example

The if keyword is used to define a block of code that executes if a specified condition is true.


  public class Main {
    public static void main(String[] args) {
      int num = 10;
      if (num > 5) {
        System.out.println("Greater than 5"); // Executes because 10 is greater than 5
      }
    }
  }
    

Output:


  Greater than 5
    

In this section, we have explored various essential Java keywords and their usage with examples. These keywords form the building blocks of Java programs.

Java Keywords

Keywords in Java are predefined words that have a special meaning. These cannot be used as identifiers like variable names or function names. Let's explore some important Java keywords with examples.

implements Keyword Example

The implements keyword is used when a class implements an interface. A class can implement one or more interfaces, thereby inheriting their abstract methods.


  interface Animal {
    void sound();
  }
  
  class Dog implements Animal {
    public void sound() {
      System.out.println("Bark");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound(); // Outputs: Bark
    }
  }
    

Output:


  Bark
    

import Keyword Example

The import keyword is used to include classes or entire packages to use their functionality in the current class.


  import java.util.Scanner;
  
  public class Main {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number:");
      int num = sc.nextInt();
      System.out.println("You entered: " + num);
    }
  }
    

Output:


  Enter a number:
  5
  You entered: 5
    

instanceof Keyword Example

The instanceof keyword is used to test whether an object is an instance of a specific class or implements a particular interface.


  class Animal {}
  class Dog extends Animal {}
  
  public class Main {
    public static void main(String[] args) {
      Animal myAnimal = new Dog();
      System.out.println(myAnimal instanceof Dog); // Outputs: true
      System.out.println(myAnimal instanceof Animal); // Outputs: true
      System.out.println(myAnimal instanceof String); // Outputs: false
    }
  }
    

Output:


  true
  true
  false
    

int Keyword Example

The int keyword is used to declare variables that store 32-bit signed integers.


  public class Main {
    public static void main(String[] args) {
      int number = 10;
      System.out.println("The number is: " + number); // Outputs: The number is: 10
    }
  }
    

Output:


  The number is: 10
    

Conclusion

Understanding Java keywords like implements, import, instanceof, and int is essential to writing effective Java code. These keywords play significant roles in defining the behavior and functionality of the program.

Java Keywords

Keywords in Java are reserved words that have special meaning in the language. They cannot be used as identifiers (such as variable names, class names, or function names). Below are some important Java keywords explained with examples.

interface Keyword Example

The interface keyword defines an interface, which can be implemented by classes to ensure they provide specific method implementations.


  interface Animal {
    void sound();
  }
  
  class Dog implements Animal {
    public void sound() {
      System.out.println("Bark");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound(); // Outputs: Bark
    }
  }
    

Output:


  Bark
    

long Keyword Example

The long keyword is used to define a variable that can store a 64-bit signed integer.


  public class Main {
    public static void main(String[] args) {
      long largeNumber = 1234567890123L;
      System.out.println("The large number is: " + largeNumber);
    }
  }
    

Output:


  The large number is: 1234567890123
    

module Keyword Example

The module keyword is used to define a module in Java, which is part of the Java Platform Module System (JPMS), introduced in Java 9.


  module mymodule {
    requires java.base;
  }
    

Explanation:

This module declaration specifies that mymodule requires java.base module.

native Keyword Example

The native keyword is used when declaring a method that is implemented in native code (e.g., C or C++).


  public class Main {
    public native void sayHello(); // Native method
  
    static {
      System.loadLibrary("hello"); // Loads the native library
    }
  
    public static void main(String[] args) {
      Main obj = new Main();
      obj.sayHello(); // Calls the native method
    }
  }
    

Note: The actual implementation of sayHello() would be done in a native library.

new Keyword Example

The new keyword is used to create new objects in Java.


  public class Main {
    public static void main(String[] args) {
      String str = new String("Hello, World!");
      System.out.println(str); // Outputs: Hello, World!
    }
  }
    

Output:


  Hello, World!
    

package Keyword Example

The package keyword is used to define a package, which is a way to organize classes and interfaces.


  package com.example;
  
  public class Main {
    public static void main(String[] args) {
      System.out.println("Hello from the com.example package!");
    }
  }
    

Output:


  Hello from the com.example package!
    

private Keyword Example

The private keyword specifies that a member (variable or method) is accessible only within the same class.


  public class Main {
    private int secretNumber = 10;
  
    private void displaySecret() {
      System.out.println("The secret number is: " + secretNumber);
    }
  
    public static void main(String[] args) {
      Main obj = new Main();
      obj.displaySecret(); // This works because it's within the same class
    }
  }
    

Output:


  The secret number is: 10
    

protected Keyword Example

The protected keyword makes a member accessible within the same package and by subclasses.


  class Animal {
    protected void sound() {
      System.out.println("Animal sound");
    }
  }
  
  public class Dog extends Animal {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound(); // Outputs: Animal sound
    }
  }
    

Output:


  Animal sound
    

public Keyword Example

The public keyword specifies that a member (variable or method) is accessible from any other class.


  public class Main {
    public int publicNumber = 100;
  
    public void displayPublicNumber() {
      System.out.println("Public number: " + publicNumber);
    }
  
    public static void main(String[] args) {
      Main obj = new Main();
      obj.displayPublicNumber(); // Outputs: Public number: 100
    }
  }
    

Output:


  Public number: 100
    

return Keyword Example

The return keyword exits from the current method and optionally returns a value.


  public class Main {
    public int add(int a, int b) {
      return a + b;
    }
  
    public static void main(String[] args) {
      Main obj = new Main();
      int result = obj.add(5, 10);
      System.out.println("Sum is: " + result); // Outputs: Sum is: 15
    }
  }
    

Output:


  Sum is: 15
    

requires Keyword Example

The requires keyword is used in module declarations to specify which other modules are required by the current module.


  module mymodule {
    requires java.base;
  }
    

Explanation:

This module declaration specifies that mymodule requires java.base module.

Conclusion

Java keywords like interface, long, module, native, new, and others play a crucial role in defining the structure and behavior of Java programs. Understanding their usage is key to writing efficient and maintainable Java code.

Java Keywords

Below are more important Java keywords explained with examples. These keywords are reserved words that have special meanings in Java.

short Keyword Example

The short keyword is used to define a variable that can store a 16-bit signed integer.


  public class Main {
    public static void main(String[] args) {
      short num = 1000;
      System.out.println("Short number: " + num); // Outputs: Short number: 1000
    }
  }
    

Output:


  Short number: 1000
    

static Keyword Example

The static keyword is used to define a method or variable that belongs to the class rather than to instances of the class.


  class Main {
    static int counter = 0;
  
    static void incrementCounter() {
      counter++;
    }
  
    public static void main(String[] args) {
      Main.incrementCounter();
      System.out.println("Counter: " + Main.counter); // Outputs: Counter: 1
    }
  }
    

Output:


  Counter: 1
    

super Keyword Example

The super keyword is used to refer to the parent class's methods or constructors.


  class Animal {
    void sound() {
      System.out.println("Animal makes sound");
    }
  }
  
  class Dog extends Animal {
    void sound() {
      super.sound(); // Calls the parent class method
      System.out.println("Dog barks");
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Dog dog = new Dog();
      dog.sound();
    }
  }
    

Output:


  Animal makes sound
  Dog barks
    

switch Keyword Example

The switch statement provides a way to execute one of several code blocks based on the value of an expression.


  public class Main {
    public static void main(String[] args) {
      int day = 2;
      switch (day) {
        case 1:
          System.out.println("Monday");
          break;
        case 2:
          System.out.println("Tuesday");
          break;
        default:
          System.out.println("Invalid day");
      }
    }
  }
    

Output:


  Tuesday
    

synchronized Keyword Example

The synchronized keyword is used to restrict access to a block of code or method to only one thread at a time.


  class Counter {
    private int count = 0;
  
    public synchronized void increment() {
      count++;
    }
  
    public int getCount() {
      return count;
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Counter counter = new Counter();
      counter.increment();
      System.out.println("Count: " + counter.getCount()); // Outputs: Count: 1
    }
  }
    

Output:


  Count: 1
    

this Keyword Example

The this keyword refers to the current object instance.


  class Person {
    String name;
  
    Person(String name) {
      this.name = name; // Refers to the current object's name variable
    }
  
    void display() {
      System.out.println("Name: " + this.name);
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Person person = new Person("John");
      person.display(); // Outputs: Name: John
    }
  }
    

Output:


  Name: John
    

throw Keyword Example

The throw keyword is used to explicitly throw an exception.


  public class Main {
    static void validate(int age) {
      if (age < 18) {
        throw new ArithmeticException("Not allowed");
      } else {
        System.out.println("Welcome!");
      }
    }
  
    public static void main(String[] args) {
      validate(16); // This will throw an exception
    }
  }
    

Output:


  Exception in thread "main" java.lang.ArithmeticException: Not allowed
    

throw Keyword Example

The throw keyword is used to explicitly throw an exception.


  public class Main {
    static void validate(int age) {
      if (age < 18) {
        throw new ArithmeticException("Not allowed");
      } else {
        System.out.println("Welcome!");
      }
    }
  
    public static void main(String[] args) {
      validate(16); // This will throw an exception
    }
  }
    

Output:


  Exception in thread "main" java.lang.ArithmeticException: Not allowed
    

transient Keyword Example

The transient keyword is used to indicate that a field should not be serialized.


  import java.io.*;
  
  class Employee implements Serializable {
    String name;
    transient int age; // This field will not be serialized
  
    Employee(String name, int age) {
      this.name = name;
      this.age = age;
    }
  }
  
  public class Main {
    public static void main(String[] args) {
      Employee emp = new Employee("John", 30);
      // Code for serialization here...
    }
  }
    

try Keyword Example

The try block is used to define code that will be tested for exceptions.


  public class Main {
    public static void main(String[] args) {
      try {
        int num = 100 / 0; // This will throw an exception
      } catch (ArithmeticException e) {
        System.out.println("Cannot divide by zero");
      }
    }
  }
    

Output:


  Cannot divide by zero
    

var Keyword Example

The var keyword allows for local variable type inference (introduced in Java 10).


  public class Main {
    public static void main(String[] args) {
      var number = 42; // The type of number is inferred as int
      System.out.println("Number: " + number); // Outputs: Number: 42
    }
  }
    

Output:


  Number: 42
    

void Keyword Example

The void keyword specifies that a method does not return a value.


  public class Main {
    public static void displayMessage() {
      System.out.println("Hello, World!"); // This method does not return any value
    }
  
    public static void main(String[] args) {
      displayMessage(); // Outputs: Hello, World!
    }
  }
    

Output:


  Hello, World!
    

volatile Keyword Example

The volatile keyword is used to indicate that a variable's value may be modified by multiple threads.


  class Main {
    private volatile boolean flag = true;
  
    public void stopThread() {
      flag = false;
    }
  
    public static void main(String[] args) {
      Main obj = new Main();
      obj.stopThread();
    }
  }
    

while Keyword Example

The while loop repeats a block of code as long as the condition is true.


  public class Main {
    public static void main(String[] args) {
      int i = 0;
      while (i < 5) {
        System.out.println("i: " + i); // Outputs: 0 1 2 3 4
        i++;
      }
    }
  }
    

Output:


  i: 0
  i: 1
  i: 2
  i: 3
  i: 4
    

charAt() Method Example

The charAt() method returns the character at a specific index in a string.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char ch = str.charAt(1); // 'e' is at index 1
      System.out.println("Character at index 1: " + ch); // Outputs: e
    }
  }
    

Output:


  Character at index 1: e
    

charAt() Method Example

The charAt() method returns the character at a specific index in a string.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char ch = str.charAt(1); // 'e' is at index 1
      System.out.println("Character at index 1: " + ch); // Outputs: e
    }
  }
    

Output:


  Character at index 1: e
    

codePointBefore() Method Example

The codePointBefore() method returns the Unicode code point before a specific index.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      int codePoint = str.codePointBefore(2); // Unicode code point of 'e'
      System.out.println("Code point before index 2: " + codePoint); // Outputs: 101
    }
  }
    

Output:


  Code point before index 2: 101
    

codePointBefore() Method Example

The codePointBefore() method returns the Unicode code point before a specific index.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      int codePoint = str.codePointBefore(2); // Unicode code point of 'e'
      System.out.println("Code point before index 2: " + codePoint); // Outputs: 101
    }
  }
    

Output:


  Code point before index 2: 101
    

compareTo() Method Example

The compareTo() method compares two strings lexicographically.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Apple";
      String str2 = "Banana";
      int result = str1.compareTo(str2); // Compare lexicographically
      System.out.println("Comparison result: " + result); // Outputs a negative number since "Apple" comes before "Banana"
    }
  }
    

Output:


  Comparison result: -1
    

compareToIgnoreCase() Method Example

The compareToIgnoreCase() method compares two strings lexicographically, ignoring case differences.


  public class Main {
    public static void main(String[] args) {
      String str1 = "apple";
      String str2 = "Apple";
      int result = str1.compareToIgnoreCase(str2); // Ignore case while comparing
      System.out.println("Comparison result: " + result); // Outputs: 0 as they are equal ignoring case
    }
  }
    

Output:


  Comparison result: 0
    

concat() Method Example

The concat() method concatenates one string to the end of another string.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Hello, ";
      String str2 = "World!";
      String result = str1.concat(str2); // Concatenates "World!" to "Hello, "
      System.out.println(result); // Outputs: Hello, World!
    }
  }
    

Output:


  Hello, World!
    

concat() Method Example

The concat() method concatenates one string to the end of another string.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Hello, ";
      String str2 = "World!";
      String result = str1.concat(str2); // Concatenates "World!" to "Hello, "
      System.out.println(result); // Outputs: Hello, World!
    }
  }
    

Output:


  Hello, World!
    

contains() Method Example

The contains() method checks if a string contains a specific sequence of characters.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello, World!";
      boolean contains = str.contains("World"); // Check if "World" is in the string
      System.out.println("Contains 'World': " + contains); // Outputs: true
    }
  }
    

Output:


  Contains 'World': true
    

copyValueOf() Method Example

The copyValueOf() method returns a string that represents the characters of a character array.


  public class Main {
    public static void main(String[] args) {
      char[] charArray = { 'H', 'e', 'l', 'l', 'o' };
      String result = String.copyValueOf(charArray); // Convert char array to string
      System.out.println("Result: " + result); // Outputs: Hello
    }
  }
    

Output:


  Result: Hello
    

endsWith() Method Example

The endsWith() method checks if a string ends with a specific suffix.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello, World!";
      boolean ends = str.endsWith("World!"); // Check if the string ends with "World!"
      System.out.println("Ends with 'World!': " + ends); // Outputs: true
    }
  }
    

Output:


  Ends with 'World!': true
    

equals() Method Example

The equals() method compares two strings for equality.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Hello";
      String str2 = "Hello";
      boolean equals = str1.equals(str2); // Compare if both strings are equal
      System.out.println("Strings are equal: " + equals); // Outputs: true
    }
  }
    

Output:


  Strings are equal: true
    

equalsIgnoreCase() Method Example

The equalsIgnoreCase() method compares two strings, ignoring case considerations.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Hello";
      String str2 = "hello";
      boolean equals = str1.equalsIgnoreCase(str2); // Compare ignoring case
      System.out.println("Strings are equal (ignore case): " + equals); // Outputs: true
    }
  }
    

Output:


  Strings are equal (ignore case): true
    

equalsIgnoreCase() Method Example

The equalsIgnoreCase() method compares two strings, ignoring case considerations.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Hello";
      String str2 = "hello";
      boolean equals = str1.equalsIgnoreCase(str2); // Compare ignoring case
      System.out.println("Strings are equal (ignore case): " + equals); // Outputs: true
    }
  }
    

Output:


  Strings are equal (ignore case): true
    

format() Method Example

The format() method returns a formatted string using specified format specifiers.


  public class Main {
    public static void main(String[] args) {
      String name = "John";
      int age = 25;
      String formatted = String.format("Name: %s, Age: %d", name, age);
      System.out.println(formatted); // Outputs: Name: John, Age: 25
    }
  }
    

Output:


  Name: John, Age: 25
    

getChars() Method Example

The getChars() method copies characters from a string into a destination character array.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char[] charArray = new char[5];
      str.getChars(0, 5, charArray, 0); // Copy characters from string to array
      System.out.println(charArray); // Outputs: Hello
    }
  }
    

Output:


  Hello
    

getChars() Method Example

The getChars() method copies characters from a string into a destination character array.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char[] charArray = new char[5];
      str.getChars(0, 5, charArray, 0); // Copy characters from string to array
      System.out.println(charArray); // Outputs: Hello
    }
  }
    

Output:


  Hello
    

hashCode() Method Example

The hashCode() method returns the hash code of a string.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      int hash = str.hashCode(); // Get hash code of the string
      System.out.println("Hash code: " + hash); // Outputs the hash code value
    }
  }
    

Output:


  Hash code: 69609650
    

isEmpty() Method Example

The isEmpty() method checks if a string is empty (length is 0).


  public class Main {
    public static void main(String[] args) {
      String str = "";
      boolean isEmpty = str.isEmpty(); // Check if string is empty
      System.out.println("Is string empty: " + isEmpty); // Outputs: true
    }
  }
    

Output:


  Is string empty: true
    

join() Method Example

The join() method joins elements of a string array with a specified delimiter.


  public class Main {
    public static void main(String[] args) {
      String[] words = { "Hello", "World", "!" };
      String result = String.join(" ", words); // Join with space as a delimiter
      System.out.println(result); // Outputs: Hello World !
    }
  }
    

Output:


  Hello World !
    

join() Method Example

The join() method joins elements of a string array with a specified delimiter.


  public class Main {
    public static void main(String[] args) {
      String[] words = { "Hello", "World", "!" };
      String result = String.join(" ", words); // Join with space as a delimiter
      System.out.println(result); // Outputs: Hello World !
    }
  }
    

Output:


  Hello World !
    

lastIndexOf() Method Example

The lastIndexOf() method returns the index of the last occurrence of a specified character or substring.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello, World!";
      int index = str.lastIndexOf('o'); // Find the last index of 'o'
      System.out.println("Last index of 'o': " + index); // Outputs: 8
    }
  }
    

Output:


  Last index of 'o': 8
    

matches() Method Example

The matches() method checks if a string matches a regular expression.


  public class Main {
    public static void main(String[] args) {
      String str = "12345";
      boolean matches = str.matches("\\d+"); // Check if string contains only digits
      System.out.println("Matches regex: " + matches); // Outputs: true
    }
  }
    

Output:


  Matches regex: true
    

offsetByCodePoints() Method Example

The offsetByCodePoints() method returns the index within the string that is offset by the specified number of code points.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello, World!";
      int index = str.offsetByCodePoints(0, 5); // Offset by 5 code points from index 0
      System.out.println("Index after offset: " + index); // Outputs: 5
    }
  }
    

Output:


  Index after offset: 5
    
regionMatches() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toCharArray() toLowerCase() toString() toUpperCase() trim() valueOf()

regionMatches() Method Example

The regionMatches() method compares a specific region of one string with a region of another string.


  public class Main {
    public static void main(String[] args) {
      String str1 = "Hello World!";
      String str2 = "World";
      boolean match = str1.regionMatches(6, str2, 0, 5); // Compare region starting at index 6
      System.out.println("Regions match: " + match); // Outputs: true
    }
  }
    

Output:


  Regions match: true
    

replaceAll() Method Example

The replaceAll() method replaces each substring of a string that matches the regular expression with a given replacement.


  public class Main {
    public static void main(String[] args) {
      String str = "apple, orange, banana";
      String replacedStr = str.replaceAll(", ", "-"); // Replace ", " with "-"
      System.out.println(replacedStr); // Outputs: apple-orange-banana
    }
  }
    

Output:


  apple-orange-banana
    

replaceAll() Method Example

The replaceAll() method replaces each substring of a string that matches the regular expression with a given replacement.


  public class Main {
    public static void main(String[] args) {
      String str = "apple, orange, banana";
      String replacedStr = str.replaceAll(", ", "-"); // Replace ", " with "-"
      System.out.println(replacedStr); // Outputs: apple-orange-banana
    }
  }
    

Output:


  apple-orange-banana
    

split() Method Example

The split() method splits a string into an array based on a given delimiter.


  public class Main {
    public static void main(String[] args) {
      String str = "apple,orange,banana";
      String[] fruits = str.split(","); // Split string by ","
      for (String fruit : fruits) {
        System.out.println(fruit); // Outputs: apple, orange, banana
      }
    }
  }
    

Output:


  apple
  orange
  banana
    

startsWith() Method Example

The startsWith() method checks if a string starts with a specified prefix.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello World!";
      boolean starts = str.startsWith("Hello"); // Check if string starts with "Hello"
      System.out.println("Starts with 'Hello': " + starts); // Outputs: true
    }
  }
    

Output:


  Starts with 'Hello': true
    

startsWith() Method Example

The startsWith() method checks if a string starts with a specified prefix.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello World!";
      boolean starts = str.startsWith("Hello"); // Check if string starts with "Hello"
      System.out.println("Starts with 'Hello': " + starts); // Outputs: true
    }
  }
    

Output:


  Starts with 'Hello': true
    

substring() Method Example

The substring() method extracts a substring from a string.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello World!";
      String subStr = str.substring(6); // Extract substring starting at index 6
      System.out.println(subStr); // Outputs: World!
    }
  }
    

Output:


  World!
    

toCharArray() Method Example

The toCharArray() method converts a string to a new character array.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char[] charArray = str.toCharArray(); // Convert string to char array
      for (char c : charArray) {
        System.out.print(c + " "); // Outputs each character
      }
    }
  }
    

Output:


  H e l l o
    

toCharArray() Method Example

The toCharArray() method converts a string to a new character array.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello";
      char[] charArray = str.toCharArray(); // Convert string to char array
      for (char c : charArray) {
        System.out.print(c + " "); // Outputs each character
      }
    }
  }
    

Output:


  H e l l o
    

toLowerCase() Method Example

The toLowerCase() method converts all characters in a string to lowercase.


  public class Main {
    public static void main(String[] args) {
      String str = "HELLO WORLD!";
      String lower = str.toLowerCase(); // Convert to lowercase
      System.out.println(lower); // Outputs: hello world!
    }
  }
    

Output:


  hello world!
    

toString() Method Example

The toString() method returns the string itself.


  public class Main {
    public static void main(String[] args) {
      String str = "Hello World!";
      System.out.println(str.toString()); // Outputs: Hello World!
    }
  }
    

Output:


  Hello World!
    

toUpperCase() Method Example

The toUpperCase() method converts all characters in a string to uppercase.


  public class Main {
    public static void main(String[] args) {
      String str = "hello world!";
      String upper = str.toUpperCase(); // Convert to uppercase
      System.out.println(upper); // Outputs: HELLO WORLD!
    }
  }
    

Output:


  HELLO WORLD!
    

trim() Method Example

The trim() method removes leading and trailing whitespace from a string.


  public class Main {
    public static void main(String[] args) {
      String str = "   Hello World!   ";
      String trimmedStr = str.trim(); // Remove leading and trailing whitespace
      System.out.println(trimmedStr); // Outputs: Hello World!
    }
  }
    

Output:


  Hello World!
    

valueOf() Method Example

The valueOf() method converts different data types to their corresponding string representation.


  public class Main {
    public static void main(String[] args) {
      int number = 100;
      String str = String.valueOf(number); // Convert int to string
      System.out.println(str); // Outputs: 100
    }
  }
    

Output:


  100
    

abs() Method Example

The abs() method returns the absolute value of a number.


  public class Main {
    public static void main(String[] args) {
      int number = -5;
      System.out.println(Math.abs(number)); // Outputs: 5
    }
  }
    

Output:


  5
    

acos() Method Example

The acos() method returns the arc cosine of a number, in radians.


  public class Main {
    public static void main(String[] args) {
      double result = Math.acos(0.5);
      System.out.println(result); // Outputs: 1.0471975511965979 (radians)
    }
  }
    

Output:


  1.0471975511965979
    

addExact() Method Example

The addExact() method adds two numbers and throws an exception if an overflow occurs.


  public class Main {
    public static void main(String[] args) {
      int result = Math.addExact(2147483647, 1); // Throws ArithmeticException
      System.out.println(result);
    }
  }
    

Output:


  Exception in thread "main" java.lang.ArithmeticException: integer overflow
    

asin() Method Example

The asin() method returns the arc sine of a number, in radians.


  public class Main {
    public static void main(String[] args) {
      double result = Math.asin(0.5);
      System.out.println(result); // Outputs: 0.5235987755982989 (radians)
    }
  }
    

Output:


  0.5235987755982989
    

atan() Method Example

The atan() method returns the arc tangent of a number, in radians.


  public class Main {
    public static void main(String[] args) {
      double result = Math.atan(1);
      System.out.println(result); // Outputs: 0.7853981633974483 (radians)
    }
  }
    

Output:


  0.7853981633974483
    

atan2() Method Example

The atan2() method returns the arc tangent of the two numbers (y/x), in radians.


  public class Main {
    public static void main(String[] args) {
      double result = Math.atan2(1, 1);
      System.out.println(result); // Outputs: 0.7853981633974483 (radians)
    }
  }
    

Output:


  0.7853981633974483
    

cbrt() Method Example

The cbrt() method returns the cube root of a number.


  public class Main {
    public static void main(String[] args) {
      double result = Math.cbrt(27);
      System.out.println(result); // Outputs: 3.0
    }
  }
    

Output:


  3.0
    

ceil() Method Example

The ceil() method returns the smallest integer that is greater than or equal to the number.


  public class Main {
    public static void main(String[] args) {
      double result = Math.ceil(4.3);
      System.out.println(result); // Outputs: 5.0
    }
  }
    

Output:


  5.0
    

copySign() Method Example

The copySign() method returns a number with the magnitude of the first argument and the sign of the second argument.


  public class Main {
    public static void main(String[] args) {
      double result = Math.copySign(5, -1);
      System.out.println(result); // Outputs: -5.0
    }
  }
    

Output:


  -5.0
    

cos() Method Example

The cos() method returns the cosine of an angle (in radians).


  public class Main {
    public static void main(String[] args) {
      double result = Math.cos(Math.PI); // Cosine of 180 degrees (π radians)
      System.out.println(result); // Outputs: -1.0
    }
  }
    

Output:


  -1.0
    

cosh() Method Example

The cosh() method returns the hyperbolic cosine of a number.


  public class Main {
    public static void main(String[] args) {
      double result = Math.cosh(1);
      System.out.println(result); // Outputs: 1.5430806348152437
    }
  }
    

Output:


  1.5430806348152437
    

decrementExact() Method Example

The decrementExact() method decrements a number by 1 and throws an exception if the result overflows.


  public class Main {
    public static void main(String[] args) {
      int result = Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException
      System.out.println(result);
    }
  }
    

Output:


  Exception in thread "main" java.lang.ArithmeticException: integer overflow
    
exp() expm1() floor() floorDiv() floorMod() getExponent() hypot() IEEEremainder() incrementExact() log() log10(0) log1p() max() min)

exp() Method Example

The exp() method returns Euler's number (e) raised to the power of a specified value.


public class Main {
  public static void main(String[] args) {
    double result = Math.exp(1);
    System.out.println(result); // Outputs: 2.718281828459045
  }
}
  

Output:


2.718281828459045
  

floor() Method Example

The floor() method returns the largest integer less than or equal to the specified number.


public class Main {
  public static void main(String[] args) {
    double result = Math.floor(4.7);
    System.out.println(result); // Outputs: 4.0
  }
}
  

Output:


4.0
  

floorDiv() Method Example

The floorDiv() method returns the largest integer less than or equal to the result of dividing two numbers.


public class Main {
  public static void main(String[] args) {
    int result = Math.floorDiv(7, 3);
    System.out.println(result); // Outputs: 2
  }
}
  

Output:


2
  

floorMod() Method Example

The floorMod() method returns the remainder after division, following the floor division rule.


public class Main {
  public static void main(String[] args) {
    int result = Math.floorMod(7, 3);
    System.out.println(result); // Outputs: 1
  }
}
  

Output:


1
  

getExponent() Method Example

The getExponent() method returns the exponent of a specified number.


public class Main {
  public static void main(String[] args) {
    int result = Math.getExponent(8);
    System.out.println(result); // Outputs: 3 (because 8 = 2^3)
  }
}
  

Output:


3
  

hypot() Method Example

The hypot() method returns the hypotenuse of a right-angled triangle given the lengths of the other two sides.


public class Main {
  public static void main(String[] args) {
    double result = Math.hypot(3, 4);
    System.out.println(result); // Outputs: 5.0 (Pythagorean theorem)
  }
}
  

Output:


5.0
  

IEEEremainder() Method Example

The IEEEremainder() method returns the remainder of the division, following the IEEE 754 standard.


public class Main {
  public static void main(String[] args) {
    double result = Math.IEEEremainder(5, 3);
    System.out.println(result); // Outputs: -1.0
  }
}
  

Output:


-1.0
  

incrementExact() Method Example

The incrementExact() method increments a number by 1 and throws an exception if it overflows.


public class Main {
  public static void main(String[] args) {
    int result = Math.incrementExact(Integer.MAX_VALUE); // Throws ArithmeticException
    System.out.println(result);
  }
}
  

Output:


Exception in thread "main" java.lang.ArithmeticException: integer overflow
  

log() Method Example

The log() method returns the natural logarithm (base e) of a number.


public class Main {
  public static void main(String[] args) {
    double result = Math.log(10);
    System.out.println(result); // Outputs: 2.302585092994046
  }
}
  

Output:


2.302585092994046
  

log10() Method Example

The log10() method returns the base 10 logarithm of a number.


public class Main {
  public static void main(String[] args) {
    double result = Math.log10(1000);
    System.out.println(result); // Outputs: 3.0
  }
}
  

Output:


3.0
  

log1p() Method Example

The log1p() method returns the natural logarithm of 1 plus the specified value.


public class Main {
  public static void main(String[] args) {
    double result = Math.log1p(1);
    System.out.println(result); // Outputs: 0.6931471805599453
  }
}
  

Output:


0.6931471805599453
  

max() Method Example

The max() method returns the larger of two numbers.


public class Main {
  public static void main(String[] args) {
    int result = Math.max(10, 20);
    System.out.println(result); // Outputs: 20
  }
}
  

Output:


20
  

min() Method Example

The min() method returns the smaller of two numbers.


public class Main {
  public static void main(String[] args) {
    int result = Math.min(10, 20);
    System.out.println(result); // Outputs: 10
  }
}
  

Output:


10
  
multiplyExact() negateExact() nextAafter() nextDown() nextUp() pow() random() rint() round() scalb() signum() sin()

multiplyExact() Method Example

The multiplyExact() method multiplies two integers and throws an exception if the result overflows.


public class Main {
  public static void main(String[] args) {
    int result = Math.multiplyExact(100000, 100000);
    System.out.println(result); // Outputs: 10000000000
  }
}
  

Output:


10000000000
  

nextAfter() Method Example

The nextAfter() method returns the next floating-point value after the specified number, towards the target.


public class Main {
  public static void main(String[] args) {
    double result = Math.nextAfter(1.0, 2.0);
    System.out.println(result); // Outputs: 1.0000000000000002
  }
}
  

Output:


1.0000000000000002
  

nextDown() Method Example

The nextDown() method returns the next floating-point value less than the specified number.


public class Main {
  public static void main(String[] args) {
    double result = Math.nextDown(1.0);
    System.out.println(result); // Outputs: 0.9999999999999999
  }
}
  

Output:


0.9999999999999999
  

nextUp() Method Example

The nextUp() method returns the next floating-point value greater than the specified number.


public class Main {
  public static void main(String[] args) {
    double result = Math.nextUp(1.0);
    System.out.println(result); // Outputs: 1.0000000000000002
  }
}
  

Output:


1.0000000000000002
  

pow() Method Example

The pow() method returns the value of the first argument raised to the power of the second argument.


public class Main {
  public static void main(String[] args) {
    double result = Math.pow(2, 3);
    System.out.println(result); // Outputs: 8.0
  }
}
  

Output:


8.0
  

random() Method Example

The random() method returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).


public class Main {
  public static void main(String[] args) {
    double result = Math.random();
    System.out.println(result); // Outputs: a random number between 0.0 and 1.0
  }
}
  

Output:


0.8260892764043772
  

rint() Method Example

The rint() method returns the closest integer value to the argument, rounding up if the number is exactly halfway between two integers.


public class Main {
  public static void main(String[] args) {
    double result = Math.rint(3.5);
    System.out.println(result); // Outputs: 4.0
  }
}
  

Output:


4.0
  

round() Method Example

The round() method rounds the floating-point number to the nearest integer.


public class Main {
  public static void main(String[] args) {
    long result = Math.round(3.7);
    System.out.println(result); // Outputs: 4
  }
}
  

Output:


4
  

scalb() Method Example

The scalb() method scales the floating-point number by a power of two.


public class Main {
  public static void main(String[] args) {
    double result = Math.scalb(3.0, 2);
    System.out.println(result); // Outputs: 12.0 (3.0 * 2^2)
  }
}
  

Output:


12.0
  

signum() Method Example

The signum() method returns the sign of the number: -1 for negative, 1 for positive, and 0 for zero.


public class Main {
  public static void main(String[] args) {
    int result = Math.signum(-10);
    System.out.println(result); // Outputs: -1
  }
}
  

Output:


-1
  

sin() Method Example

The sin() method returns the sine of a number, where the input is in radians.


public class Main {
  public static void main(String[] args) {
    double result = Math.sin(Math.PI / 2);
    System.out.println(result); // Outputs: 1.0
  }
}
  

Output:


1.0
  
sinh() sqrt() subtractExact() tan() tanh() to Degrees() tolntExact() toRadians() ulp()

sinh() Method Example

The sinh() method returns the hyperbolic sine of a number.


public class Main {
  public static void main(String[] args) {
    double result = Math.sinh(1);
    System.out.println(result); // Outputs: 1.1752011936438014
  }
}
  

Output:


1.1752011936438014
  

subtractExact() Method Example

The subtractExact() method subtracts two integers and throws an exception if the result overflows.


public class Main {
  public static void main(String[] args) {
    int result = Math.subtractExact(100, 50);
    System.out.println(result); // Outputs: 50
  }
}
  

Output:


50
  

tan() Method Example

The tan() method returns the tangent of a number, where the input is in radians.


public class Main {
  public static void main(String[] args) {
    double result = Math.tan(Math.PI / 4);
    System.out.println(result); // Outputs: 1.0
  }
}
  

Output:


1.0
  

tanh() Method Example

The tanh() method returns the hyperbolic tangent of a number.


public class Main {
  public static void main(String[] args) {
    double result = Math.tanh(1);
    System.out.println(result); // Outputs: 0.7615941559557649
  }
}
  

Output:


0.7615941559557649
  

toDegrees() Method Example

The toDegrees() method converts an angle from radians to degrees.


public class Main {
  public static void main(String[] args) {
    double result = Math.toDegrees(Math.PI);
    System.out.println(result); // Outputs: 180.0
  }
}
  

Output:


180.0
  

toIntExact() Method Example

The toIntExact() method converts a long to an int, throwing an exception if the value is out of range for an int.


public class Main {
  public static void main(String[] args) {
    int result = Math.toIntExact(100000L);
    System.out.println(result); // Outputs: 100000
  }
}
  

Output:


100000
  

toRadians() Method Example

The toRadians() method converts an angle from degrees to radians.


public class Main {
  public static void main(String[] args) {
    double result = Math.toRadians(180);
    System.out.println(result); // Outputs: 3.141592653589793
  }
}
  

Output:


3.141592653589793
  

ulp() Method Example

The ulp() method returns the size of the ulp (unit in the last place) of a given floating-point number.


public class Main {
  public static void main(String[] args) {
    double result = Math.ulp(1.0);
    System.out.println(result); // Outputs: 2.220446049250313e-16
  }
}
  

Output:


2.220446049250313e-16
  

print() Method Example

The print() method is used to print text to the console without a newline at the end.


public class Main {
  public static void main(String[] args) {
    System.out.print("Hello, ");
    System.out.print("World!"); // No new line
  }
}
  

Output:


Hello, World!
  

printf() Method Example

The printf() method allows formatted output. You can specify the format of the output using format specifiers.


public class Main {
  public static void main(String[] args) {
    int number = 10;
    System.out.printf("The value of number is: %d", number); // %d is the format specifier for integers
  }
}
  

Output:


The value of number is: 10
  

println() Method Example

The println() method prints text to the console followed by a new line, meaning the next output will appear on a new line.


public class Main {
  public static void main(String[] args) {
    System.out.println("Hello, World!"); // Adds a new line after the text
    System.out.println("Welcome to Java!");
  }
}
  

Output:


Hello, World!
Welcome to Java!
  

compare() Method Example

The compare() method is used to compare two arrays. It returns 0 if both arrays are equal, a positive value if the first array is greater, and a negative value if the second array is greater.


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] array1 = {1, 2, 3};
    int[] array2 = {1, 2, 3};
    int[] array3 = {3, 2, 1};

    System.out.println(Arrays.compare(array1, array2)); // Output: 0 (arrays are equal)
    System.out.println(Arrays.compare(array1, array3)); // Output: a negative number (array1 is less than array3)
  }
}
  

Output:


0
-1
  

equals() Method Example

The equals() method compares two arrays for equality. It returns true if both arrays have the same elements in the same order, otherwise false.


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] array1 = {1, 2, 3};
    int[] array2 = {1, 2, 3};
    int[] array3 = {3, 2, 1};

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

Output:


true
false
  

sort() Method Example

The sort() method is used to sort the elements of an array in ascending order.


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] array = {3, 1, 2};

    Arrays.sort(array);

    for (int num : array) {
      System.out.println(num); // Output: 1, 2, 3
    }
  }
}
  

Output:


1
2
3
  

fill() Method Example

The fill() method is used to assign a specific value to all the elements of an array.


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] array = new int[5];

    Arrays.fill(array, 10); // Fills the array with the value 10

    for (int num : array) {
      System.out.println(num); // Output: 10, 10, 10, 10, 10
    }
  }
}
  

Output:


10
10
10
10
10
  

length Attribute Example

The length attribute returns the number of elements in an array.


public class Main {
  public static void main(String[] args) {
    int[] array = {1, 2, 3, 4};

    System.out.println(array.length); // Output: 4
  }
}
  

Output:


4
  

add() Method Example

The add() method adds an element to the end of the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();

    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

addAll() Method Example

The addAll() method adds all elements from a specified collection to the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    ArrayList moreFruits = new ArrayList<>();
    moreFruits.add("Orange");
    moreFruits.add("Mango");

    fruits.addAll(moreFruits);

    System.out.println(fruits); // Output: [Apple, Banana, Orange, Mango]
  }
}
  

Output:


[Apple, Banana, Orange, Mango]
  

clear() Method Example

The clear() method removes all elements from the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.clear();

    System.out.println(fruits); // Output: []
  }
}
  

Output:


[]
  

clone() Method Example

The clone() method creates a shallow copy of the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    ArrayList clonedFruits = (ArrayList) fruits.clone();

    System.out.println(clonedFruits); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

contains() Method Example

The contains() method checks if a specific element exists in the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.contains("Apple")); // Output: true
    System.out.println(fruits.contains("Mango")); // Output: false
  }
}
  

Output:


true
false
  

ensureCapacity() Method Example

The ensureCapacity() method increases the capacity of the ArrayList to the specified size.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.ensureCapacity(10); // Ensures the ArrayList has at least 10 elements of capacity

    System.out.println(fruits); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

forEach() Method Example

The forEach() method performs the specified action on each element of the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.forEach(fruit -> System.out.println(fruit)); // Output: Apple, Banana
  }
}
  

Output:


Apple
Banana
  

get() Method Example

The get() method retrieves the element at the specified index in the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.get(0)); // Output: Apple
    System.out.println(fruits.get(1)); // Output: Banana
  }
}
  

Output:


Apple
Banana
  

indexOf() Method Example

The indexOf() method returns the index of the first occurrence of the specified element in the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    System.out.println(fruits.indexOf("Banana")); // Output: 1
    System.out.println(fruits.indexOf("Mango"));  // Output: -1
  }
}
  

Output:


1
-1
  

isEmpty() Method Example

The isEmpty() method checks if the ArrayList is empty. It returns true if the list is empty, otherwise false.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    System.out.println(fruits.isEmpty()); // Output: true

    fruits.add("Apple");
    System.out.println(fruits.isEmpty()); // Output: false
  }
}
  

Output:


true
false
  

iterator() Method Example

The iterator() method returns an iterator that can be used to loop through the elements of the ArrayList.


import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    Iterator iterator = fruits.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
  

Output:


Apple
Banana
  

lastIndexOf() Method Example

The lastIndexOf() method returns the index of the last occurrence of the specified element in the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Apple");

    System.out.println(fruits.lastIndexOf("Apple")); // Output: 2
    System.out.println(fruits.lastIndexOf("Mango")); // Output: -1
  }
}
  

Output:


2
-1
  

listIterator() Method Example

The listIterator() method returns a list iterator that can be used to traverse the elements of the ArrayList in both directions.


import java.util.ArrayList;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    ListIterator listIterator = fruits.listIterator();
    while (listIterator.hasNext()) {
      System.out.println(listIterator.next());
    }

    // Traverse in reverse order
    while (listIterator.hasPrevious()) {
      System.out.println(listIterator.previous());
    }
  }
}
  

Output:


Apple
Banana
Banana
Apple
  

remove() Method Example

The remove() method removes the element at the specified index or removes the specified element.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.remove("Apple"); // Removes the specified element
    fruits.remove(0); // Removes the element at index 0

    System.out.println(fruits); // Output: []
  }
}
  

Output:


[]
  

removeAll() Method Example

The removeAll() method removes all elements from the ArrayList that are contained in the specified collection.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    ArrayList removeFruits = new ArrayList<>();
    removeFruits.add("Apple");

    fruits.removeAll(removeFruits);

    System.out.println(fruits); // Output: [Banana]
  }
}
  

Output:


[Banana]
  

removeIf() Method Example

The removeIf() method removes all elements that satisfy the given condition.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    fruits.removeIf(fruit -> fruit.startsWith("B"));

    System.out.println(fruits); // Output: [Apple, Orange]
  }
}
  

Output:


[Apple, Orange]
  

replaceAll() Method Example

The replaceAll() method replaces each element of the ArrayList with the result of applying the specified operator.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.replaceAll(fruit -> fruit.toUpperCase());

    System.out.println(fruits); // Output: [APPLE, BANANA]
  }
}
  

Output:


[APPLE, BANANA]
  

retainAll() Method Example

The retainAll() method retains only the elements in the ArrayList that are contained in the specified collection.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    ArrayList retainFruits = new ArrayList<>();
    retainFruits.add("Apple");
    retainFruits.add("Orange");

    fruits.retainAll(retainFruits);

    System.out.println(fruits); // Output: [Apple, Orange]
  }
}
  

Output:


[Apple, Orange]
  
set() size() sort() spliterator() subList() toArray() trim ToSize()

size() Method Example

The size() method returns the number of elements in the ArrayList.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.size()); // Output: 2
  }
}
  

Output:


2
  

sort() Method Example

The sort() method sorts the elements of the ArrayList in ascending order according to their natural ordering.


import java.util.ArrayList;
import java.util.Collections;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    Collections.sort(fruits);

    System.out.println(fruits); // Output: [Apple, Banana, Orange]
  }
}
  

Output:


[Apple, Banana, Orange]
  

spliterator() Method Example

The spliterator() method provides a Spliterator that can be used to traverse the ArrayList and perform bulk operations.


import java.util.ArrayList;
import java.util.Spliterator;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    Spliterator spliterator = fruits.spliterator();
    spliterator.forEachRemaining(System.out::println);  // Output each element
  }
}
  

Output:


Apple
Banana
Orange
  

subList() Method Example

The subList() method returns a view of the portion of the ArrayList between the specified fromIndex and toIndex.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    System.out.println(fruits.subList(0, 2)); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

toArray() Method Example

The toArray() method converts the ArrayList to an array.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    Object[] array = fruits.toArray();
    for (Object fruit : array) {
      System.out.println(fruit);
    }
  }
}
  

Output:


Apple
Banana
  

trimToSize() Method Example

The trimToSize() method trims the capacity of the ArrayList to the current size, removing any excess capacity.


import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>(10);
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println("Capacity before trim: " + fruits.size());
    fruits.trimToSize(); // Trims the capacity to size
    System.out.println("Capacity after trim: " + fruits.size());
  }
}
  

Output:


Capacity before trim: 2
Capacity after trim: 2
  

add() Method Example

The add() method is used to add an element to the end of the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

addAll() Method Example

The addAll() method is used to add all elements from another collection to the LinkedList.


import java.util.LinkedList;
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");

    ArrayList moreFruits = new ArrayList<>();
    moreFruits.add("Banana");
    moreFruits.add("Orange");

    fruits.addAll(moreFruits);

    System.out.println(fruits); // Output: [Apple, Banana, Orange]
  }
}
  

Output:


[Apple, Banana, Orange]
  

clear() Method Example

The clear() method removes all elements from the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.clear();

    System.out.println(fruits); // Output: []
  }
}
  

Output:


[]
  

clone() Method Example

The clone() method creates a shallow copy of the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    LinkedList fruitsClone = (LinkedList) fruits.clone();

    System.out.println(fruitsClone); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

contains() Method Example

The contains() method checks if a specific element exists in the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.contains("Banana")); // Output: true
    System.out.println(fruits.contains("Orange")); // Output: false
  }
}
  

Output:


true
false
  

forEach() Method Example

The forEach() method performs an action for each element of the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.forEach(fruit -> System.out.println(fruit));
  }
}
  

Output:


Apple
Banana
  

get() Method Example

The get() method returns the element at the specified index in the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.get(1)); // Output: Banana
  }
}
  

Output:


Banana
  

getFirst() Method Example

The getFirst() method returns the first element of the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.getFirst()); // Output: Apple
  }
}
  

Output:


Apple
  

getLast() Method Example

The getLast() method returns the last element of the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.getLast()); // Output: Banana
  }
}
  

Output:


Banana
  

indexOf() Method Example

The indexOf() method returns the index of the first occurrence of the specified element in the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    System.out.println(fruits.indexOf("Banana")); // Output: 1
  }
}
  

Output:


1
  

isEmpty() Method Example

The isEmpty() method checks if the LinkedList is empty or not.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    System.out.println(fruits.isEmpty()); // Output: true

    fruits.add("Apple");
    System.out.println(fruits.isEmpty()); // Output: false
  }
}
  

Output:


true
false
  

iterator() Method Example

The iterator() method returns an iterator over the elements in the LinkedList.


import java.util.LinkedList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    Iterator iterator = fruits.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
  

Output:


Apple
Banana
Orange
  

lastIndexOf() Method Example

The lastIndexOf() method returns the index of the last occurrence of the specified element in the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");
    fruits.add("Banana");

    System.out.println(fruits.lastIndexOf("Banana")); // Output: 3
  }
}
  

Output:


3
  

listIterator() Method Example

The listIterator() method returns a list iterator over the elements in the LinkedList.


import java.util.LinkedList;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    ListIterator listIterator = fruits.listIterator();
    while (listIterator.hasNext()) {
      System.out.println(listIterator.next());
    }
  }
}
  

Output:


Apple
Banana
Orange
  

remove() Method Example

The remove() method removes the first occurrence of the specified element from the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    fruits.remove("Banana");

    System.out.println(fruits); // Output: [Apple, Orange]
  }
}
  

Output:


[Apple, Orange]
  

removeAll() Method Example

The removeAll() method removes all elements in the LinkedList that are contained in the specified collection.


import java.util.LinkedList;
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    ArrayList removeList = new ArrayList<>();
    removeList.add("Apple");
    removeList.add("Banana");

    fruits.removeAll(removeList);

    System.out.println(fruits); // Output: [Orange]
  }
}
  

Output:


[Orange]
  

removeFirst() Method Example

The removeFirst() method removes the first element from the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.removeFirst();

    System.out.println(fruits); // Output: [Banana]
  }
}
  

Output:


[Banana]
  

removeLast() Method Example

The removeLast() method removes the last element from the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.removeLast();

    System.out.println(fruits); // Output: [Apple]
  }
}
  

Output:


[Apple]
  

replaceAll() Method Example

The replaceAll() method replaces each element of the LinkedList with the result of applying the specified operator.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");

    fruits.replaceAll(fruit -> fruit.toUpperCase());

    System.out.println(fruits); // Output: [APPLE, BANANA]
  }
}
  

Output:


[APPLE, BANANA]
  

retainAll() Method Example

The retainAll() method retains only the elements in the LinkedList that are contained in the specified collection.


import java.util.LinkedList;
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    ArrayList retainList = new ArrayList<>();
    retainList.add("Banana");
    retainList.add("Orange");

    fruits.retainAll(retainList);

    System.out.println(fruits); // Output: [Banana, Orange]
  }
}
  

Output:


[Banana, Orange]
  
set() size() sort() spliterator() subList() toArray()

size() Method Example

The size() method returns the number of elements in the LinkedList.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    System.out.println(fruits.size()); // Output: 3
  }
}
  

Output:


3
  

sort() Method Example

The sort() method sorts the elements of the LinkedList using the natural ordering of the elements or a provided comparator.


import java.util.LinkedList;
import java.util.Collections;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    Collections.sort(fruits);

    System.out.println(fruits); // Output: [Apple, Banana, Orange]
  }
}
  

Output:


[Apple, Banana, Orange]
  

spliterator() Method Example

The spliterator() method returns a Spliterator over the elements in the LinkedList, which can be used for parallel processing.


import java.util.LinkedList;
import java.util.Spliterator;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    Spliterator spliterator = fruits.spliterator();
    spliterator.forEachRemaining(System.out::println);
  }
}
  

Output:


Apple
Banana
Orange
  

subList() Method Example

The subList() method returns a view of the portion of the LinkedList between the specified fromIndex (inclusive) and toIndex (exclusive).


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");
    fruits.add("Mango");

    System.out.println(fruits.subList(1, 3)); // Output: [Banana, Orange]
  }
}
  

Output:


[Banana, Orange]
  

toArray() Method Example

The toArray() method converts the LinkedList into an array.


import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    LinkedList fruits = new LinkedList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    String[] fruitsArray = fruits.toArray(new String[0]);

    for (String fruit : fruitsArray) {
      System.out.println(fruit);
    }
  }
}
  

Output:


Apple
Banana
Orange
  

clear() Method Example

The clear() method removes all the key-value mappings from the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);
    map.put("Orange", 30);

    map.clear(); // Removes all key-value pairs

    System.out.println(map); // Output: {}
  }
}
  

Output:


{}
  

clear() Method Example

The clear() method removes all the key-value mappings from the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);
    map.put("Orange", 30);

    map.clear(); // Removes all key-value pairs

    System.out.println(map); // Output: {}
  }
}
  

Output:


{}
  

compute() Method Example

The compute() method computes a new value for the specified key using the given remapping function.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.compute("Apple", (key, value) -> value + 5); // Adds 5 to the value of "Apple"

    System.out.println(map); // Output: {Apple=15, Banana=20}
  }
}
  

Output:


{Apple=15, Banana=20}
  

computeIfAbsent() Method Example

The computeIfAbsent() method computes a value for the specified key if it is absent, using the provided mapping function.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);

    map.computeIfAbsent("Banana", key -> 20); // Computes and adds "Banana" with value 20 if absent

    System.out.println(map); // Output: {Apple=10, Banana=20}
  }
}
  

Output:


{Apple=10, Banana=20}
  

computeIfPresent() Method Example

The computeIfPresent() method computes a new value for the specified key if the key is present in the map.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.computeIfPresent("Apple", (key, value) -> value + 5); // Adds 5 to the value of "Apple"

    System.out.println(map); // Output: {Apple=15, Banana=20}
  }
}
  

Output:


{Apple=15, Banana=20}
  

containsKey() Method Example

The containsKey() method checks if the specified key exists in the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map.containsKey("Apple")); // Output: true
    System.out.println(map.containsKey("Orange")); // Output: false
  }
}
  

Output:


true
false
  

containsValue() Method Example

The containsValue() method checks if the specified value exists in the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map.containsValue(10)); // Output: true
    System.out.println(map.containsValue(30)); // Output: false
  }
}
  

Output:


true
false
  

entrySet() Method Example

The entrySet() method returns a set of key-value pairs in the HashMap.


import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    for (Map.Entry entry : map.entrySet()) {
      System.out.println(entry.getKey() + ": " + entry.getValue());
    }
  }
}
  

Output:


Apple: 10
Banana: 20
  

forEach() Method Example

The forEach() method iterates over each entry in the HashMap and applies the given action.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.forEach((key, value) -> System.out.println(key + ": " + value));
  }
}
  

Output:


Apple: 10
Banana: 20
  

get() Method Example

The get() method retrieves the value associated with the specified key in the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map.get("Apple")); // Output: 10
    System.out.println(map.get("Orange")); // Output: null
  }
}
  

Output:


10
null
  

getOrDefault() Method Example

The getOrDefault() method returns the value associated with the specified key, or the default value if the key is not found.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map.getOrDefault("Apple", 0)); // Output: 10
    System.out.println(map.getOrDefault("Orange", 0)); // Output: 0
  }
}
  

Output:


10
0
  

isEmpty() Method Example

The isEmpty() method checks if the HashMap is empty.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    System.out.println(map.isEmpty()); // Output: true

    map.put("Apple", 10);
    System.out.println(map.isEmpty()); // Output: false
  }
}
  

Output:


true
false
  

keySet() Method Example

The keySet() method returns a set view of all the keys in the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map.keySet()); // Output: [Apple, Banana]
  }
}
  

Output:


[Apple, Banana]
  

merge() Method Example

The merge() method combines two values associated with the same key. If the key is not present, the new value is inserted.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.merge("Apple", 5, (oldValue, newValue) -> oldValue + newValue); // Apple = 10 + 5
    map.merge("Orange", 10, (oldValue, newValue) -> oldValue + newValue); // Orange = 10

    System.out.println(map); // Output: {Apple=15, Banana=20, Orange=10}
  }
}
  

Output:


{Apple=15, Banana=20, Orange=10}
  

put() Method Example

The put() method inserts a key-value pair into the HashMap. If the key already exists, it updates the value.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map); // Output: {Apple=10, Banana=20}
  }
}
  

Output:


{Apple=10, Banana=20}
  

putAll() Method Example

The putAll() method inserts all key-value pairs from another map into the current HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map1 = new HashMap<>();
    map1.put("Apple", 10);
    map1.put("Banana", 20);

    HashMap map2 = new HashMap<>();
    map2.put("Orange", 30);
    map2.put("Grape", 40);

    map1.putAll(map2); // Merges map2 into map1

    System.out.println(map1); // Output: {Apple=10, Banana=20, Orange=30, Grape=40}
  }
}
  

Output:


{Apple=10, Banana=20, Orange=30, Grape=40}
  

putIfAbsent() Method Example

The putIfAbsent() method inserts the key-value pair if the key is not already present in the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.putIfAbsent("Apple", 15); // Does not update value for "Apple"
    map.putIfAbsent("Orange", 25); // Adds "Orange" with value 25

    System.out.println(map); // Output: {Apple=10, Banana=20, Orange=25}
  }
}
  

Output:


{Apple=10, Banana=20, Orange=25}
  

remove() Method Example

The remove() method removes the key-value pair associated with the specified key.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.remove("Apple"); // Removes "Apple" entry

    System.out.println(map); // Output: {Banana=20}
  }
}
  

Output:


{Banana=20}
  

replace() Method Example

The replace() method replaces the value for the specified key with a new value.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    map.replace("Apple", 15); // Replaces value of "Apple" with 15

    System.out.println(map); // Output: {Apple=15, Banana=20}
  }
}
  

Output:


{Apple=15, Banana=20}
  

replaceAll() Method Example

The replaceAll() method replaces each entry’s value in the map with the result of applying the specified function to that entry.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    // Replace all values by multiplying them by 2
    map.replaceAll((key, value) -> value * 2);

    System.out.println(map); // Output: {Apple=20, Banana=40}
  }
}
  

Output:


{Apple=20, Banana=40}
  

size() Method Example

The size() method returns the number of key-value pairs in the HashMap.


import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    System.out.println(map.size()); // Output: 2
  }
}
  

Output:


2
  

values() Method Example

The values() method returns a collection view of all the values in the HashMap.


import java.util.HashMap;
import java.util.Collection;

public class Main {
  public static void main(String[] args) {
    HashMap map = new HashMap<>();
    map.put("Apple", 10);
    map.put("Banana", 20);

    Collection values = map.values();
    System.out.println(values); // Output: [10, 20]
  }
}
  

Output:


[10, 20]
  

close() Method Example

The close() method is used to close the Scanner object to free up resources.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your name:");
    String name = scanner.nextLine();
    System.out.println("Hello, " + name);
    
    // Close the scanner to release resources
    scanner.close();
  }
}
  

Note:

Once close() is called, the scanner cannot be used again.

delimiter() Method Example

The delimiter() method returns the current delimiter pattern used by the scanner.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("apple orange banana");
    System.out.println("Delimiter: " + scanner.delimiter()); // Output: \p{javaWhitespace}+
  }
}
  

Output:


\p{javaWhitespace}+
  

findInLine() Method Example

The findInLine() method searches for the next occurrence of the specified pattern in the current line and returns it.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("apple orange banana");
    String word = scanner.findInLine("orange");
    System.out.println("Found word: " + word); // Output: orange
  }
}
  

Output:


orange
  

findWithinHorizon() Method Example

The findWithinHorizon() method searches for the specified pattern within the given horizon (character limit).


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("apple orange banana");
    String result = scanner.findWithinHorizon("orange", 10);
    System.out.println("Found within horizon: " + result); // Output: orange
  }
}
  

Output:


orange
  

hasNext() Method Example

The hasNext() method returns true if there is another token available in the input.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("apple orange banana");
    System.out.println(scanner.hasNext()); // Output: true
  }
}
  

Output:


true
  

hasNextBoolean() Method Example

The hasNextBoolean() method returns true if the next token in the input can be interpreted as a boolean.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("true false");
    System.out.println(scanner.hasNextBoolean()); // Output: true
  }
}
  

Output:


true
  

hasNextByte() Method Example

The hasNextByte() method returns true if the next token in the input can be interpreted as a byte.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("100 200");
    System.out.println(scanner.hasNextByte()); // Output: true
  }
}
  

Output:


true
  

hasNextDouble() Method Example

The hasNextDouble() method returns true if the next token in the input can be interpreted as a double.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("10.5 20.7");
    System.out.println(scanner.hasNextDouble()); // Output: true
  }
}
  

Output:


true
  

hasNextFloat() Method Example

The hasNextFloat() method returns true if the next token in the input can be interpreted as a float.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("10.5f 20.7f");
    System.out.println(scanner.hasNextFloat()); // Output: true
  }
}
  

Output:


true
  

hasNextInt() Method Example

The hasNextInt() method returns true if the next token in the input can be interpreted as an integer.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("42 100");
    System.out.println(scanner.hasNextInt()); // Output: true
  }
}
  

Output:


true
  

hasNextLine() Method Example

The hasNextLine() method returns true if there is another line in the input.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("Hello World\nJava Scanner");
    System.out.println(scanner.hasNextLine()); // Output: true
  }
}
  

Output:


true
  

hasNextLong() Method Example

The hasNextLong() method returns true if the next token in the input can be interpreted as a long.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("10000000000 20000000000");
    System.out.println(scanner.hasNextLong()); // Output: true
  }
}
  

Output:


true
  

hasNextShort() Method Example

The hasNextShort() method returns true if the next token in the input can be interpreted as a short.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("10000 20000");
    System.out.println(scanner.hasNextShort()); // Output: true
  }
}
  

Output:


true
  

locale() Method Example

The locale() method returns the Locale object associated with the scanner.


import java.util.Scanner;
import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("Hello");
    System.out.println(scanner.locale()); // Output: en_US
  }
}
  

Output:


en_US
  

next() Method Example

The next() method finds and returns the next complete token in the input.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("apple orange banana");
    String token = scanner.next();
    System.out.println("Next token: " + token); // Output: apple
  }
}
  

Output:


apple
  

nextBoolean() Method Example

The nextBoolean() method scans the next token of the input as a boolean.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("true false");
    boolean value = scanner.nextBoolean();
    System.out.println("Next boolean: " + value); // Output: true
  }
}
  

Output:


true
  

nextByte() Method Example

The nextByte() method scans the next token of the input as a byte.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("100");
    byte value = scanner.nextByte();
    System.out.println("Next byte: " + value); // Output: 100
  }
}
  

Output:


100
  

nextDouble() Method Example

The nextDouble() method scans the next token of the input as a double.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("5.5 10.2");
    double value = scanner.nextDouble();
    System.out.println("Next double: " + value); // Output: 5.5
  }
}
  

Output:


5.5
  

nextFloat() Method Example

The nextFloat() method scans the next token of the input as a float.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("3.14 2.71");
    float value = scanner.nextFloat();
    System.out.println("Next float: " + value); // Output: 3.14
  }
}
  

Output:


3.14
  

nextInt() Method Example

The nextInt() method scans the next token of the input as an integer.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("42 100");
    int value = scanner.nextInt();
    System.out.println("Next integer: " + value); // Output: 42
  }
}
  

Output:


42
  

nextLine() Method Example

The nextLine() method scans the next line of the input.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("Hello\nWorld");
    String line = scanner.nextLine();
    System.out.println("Next line: " + line); // Output: Hello
  }
}
  

Output:


Hello
  

nextLong() Method Example

The nextLong() method scans the next token of the input as a long.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("10000000000 20000000000");
    long value = scanner.nextLong();
    System.out.println("Next long: " + value); // Output: 10000000000
  }
}
  

Output:


10000000000
  

nextShort() Method Example

The nextShort() method scans the next token of the input as a short.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("32000 15000");
    short value = scanner.nextShort();
    System.out.println("Next short: " + value); // Output: 32000
  }
}
  

Output:


32000
  

radix() Method Example

The radix() method returns the current radix of the scanner.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("1010");
    scanner.useRadix(2); // Set radix to binary
    System.out.println("Current radix: " + scanner.radix()); // Output: 2
  }
}
  

Output:


2
  

reset() Method Example

The reset() method resets the scanner to its initial state.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("Hello World");
    scanner.nextLine();
    scanner.reset(); // Resets the scanner
    System.out.println("Scanner reset successful!");
  }
}
  

Output:


Scanner reset successful!
  

useDelimiter() Method Example

The useDelimiter() method sets a custom delimiter for the scanner.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("apple,orange,banana");
    scanner.useDelimiter(",");
    while(scanner.hasNext()) {
      System.out.println(scanner.next());
    }
  }
}
  

Output:


apple
orange
banana
  

useLocale() Method Example

The useLocale() method sets the locale for the scanner.


import java.util.Scanner;
import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("Hello World");
    scanner.useLocale(Locale.FRENCH); // Sets locale to French
    System.out.println("Locale set to: " + scanner.locale()); // Output: fr
  }
}
  

Output:


fr
  

useRadix() Method Example

The useRadix() method sets the radix for the scanner to read numbers in the specified base.


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner("1010");
    scanner.useRadix(2); // Set radix to binary
    int value = scanner.nextInt(); // Read binary input
    System.out.println("Next integer in binary: " + value); // Output: 10
  }
}
  

Output:


10
  

hasNext() Method Example

The hasNext() method returns true if there are more elements to iterate over in the collection, otherwise it returns false.


import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    ArrayList list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    list.add("Cherry");
    
    Iterator iterator = list.iterator();
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
  

Output:


Apple
Banana
Cherry
  

hasNext() Method Example

The hasNext() method returns true if there are more elements to iterate over in the collection, otherwise it returns false.


import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    ArrayList list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    list.add("Cherry");
    
    Iterator iterator = list.iterator();
    while(iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
  

Output:


Apple
Banana
Cherry
  

remove() Method Example

The remove() method removes the last element returned by the iterator. This method can only be called once per call to next().


import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    ArrayList list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    list.add("Cherry");
    
    Iterator iterator = list.iterator();
    while(iterator.hasNext()) {
      String fruit = iterator.next();
      if(fruit.equals("Banana")) {
        iterator.remove();  // Removes "Banana"
      }
    }
    
    System.out.println(list); // Output: [Apple, Cherry]
  }
}
  

Output:


[Apple, Cherry]
  

OutOfMemoryError Example

The OutOfMemoryError occurs when the Java Virtual Machine (JVM) runs out of memory and cannot allocate more.


public class Main {
  public static void main(String[] args) {
    try {
      int[] array = new int[Integer.MAX_VALUE]; // Trying to allocate too much memory
    } catch (OutOfMemoryError e) {
      System.out.println("Error: " + e);
    }
  }
}
  

Output:


Error: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
  

NullPointerException Example

A NullPointerException occurs when the program attempts to use an object reference that has not been initialized or is null.


public class Main {
  public static void main(String[] args) {
    String str = null;
    try {
      System.out.println(str.length()); // Will throw NullPointerException
    } catch (NullPointerException e) {
      System.out.println("Caught exception: " + e);
    }
  }
}
  

Output:


Caught exception: java.lang.NullPointerException
  

ArithmeticException Example

An ArithmeticException occurs when an illegal arithmetic operation is performed, such as division by zero.


public class Main {
  public static void main(String[] args) {
    try {
      int result = 10 / 0;  // Division by zero
    } catch (ArithmeticException e) {
      System.out.println("Caught exception: " + e);
    }
  }
}
  

Output:


Caught exception: java.lang.ArithmeticException: / by zero
  

FileNotFoundException Example

A FileNotFoundException occurs when the program tries to access a file that does not exist.


import java.io.*;

public class Main {
  public static void main(String[] args) {
    try {
      FileInputStream file = new FileInputStream("nonexistent.txt");
    } catch (FileNotFoundException e) {
      System.out.println("Caught exception: " + e);
    }
  }
}
  

Output:


Caught exception: java.io.FileNotFoundException: nonexistent.txt (No such file or directory)
  

try-catch Block Example

A try-catch block is used to handle exceptions in Java. The try block contains the code that might throw an exception, while the catch block handles the exception.


public class Main {
  public static void main(String[] args) {
    try {
      int result = 10 / 0; // Will throw ArithmeticException
    } catch (ArithmeticException e) {
      System.out.println("Caught exception: " + e);
    }
  }
}
  

Output:


Caught exception: java.lang.ArithmeticException: / by zero
  

Java Examples

Here you can find some basic and advanced Java examples to help you understand Java programming concepts.

Java Compiler

You can compile and run Java programs online using various online Java compilers. Here is an example of an online Java compiler:

Click here to use JDoodle Java Compiler

Java Exercises

Try out these Java exercises to test your skills:

Java Quiz

Take this quiz to check your knowledge of Java:

Java Server

Java is widely used for server-side applications. You can learn more about Java servers and how to run Java applications on a server. Here are some popular Java server technologies:

Java Syllabus

Here is a basic syllabus for Java programming: