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
}
}
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
}
}
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]
}
}
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 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.
Follow the steps below to install Java on your system:
Visit the official Oracle website to download the latest version of the Java Development Kit (JDK):
Download JDK from OracleAlternatively, you can download OpenJDK from other sources:
Download OpenJDKFollow these steps to install Java on Windows:
Follow these steps to install Java on macOS:
java -version
.Follow these steps to install Java on Linux:
sudo apt update
sudo apt install openjdk-11-jdk
java -version
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.
It's important to set the JAVA_HOME variable on your system:
export JAVA_HOME=/path/to/jdkAdd the above line to your .bash_profile (macOS) or .bashrc (Linux) file to make the change permanent.
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!"); } }
javac HelloWorld.java
java HelloWorld
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.
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
}
}
Hello, World!
Upar diye gaye code mein:
public class Main
ek **class** define karta hai.public static void main(String[] args)
**main method** hai jahan se program run hota hai.System.out.println("Hello, World!");
is line se **output** screen par text print hota hai.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
}
}
Hello, Java!
**Explanation**:
System.out.println("Hello, Java!");
is line mein **output** screen par text "Hello, Java!" print hota hai.Java mein kisi bhi text ko print karne ke liye hum **System.out.println()** ka use karte hain. Isme text ko double quotes mein likhna padta hai.
public class Main {
public static void main(String[] args) {
// Text print karna
System.out.println("Welcome to Java Programming!"); // Print a welcome message
}
}
Welcome to Java Programming!
**Explanation**:
System.out.println("Welcome to Java Programming!");
se "Welcome to Java Programming!" message console par print hota hai.Java mein numbers ko print karne ke liye bhi hum **System.out.println()** ka use karte hain. Ismein hum numbers directly likh sakte hain ya variables ke through print kar sakte hain.
public class Main {
public static void main(String[] args) {
// Numbers print karna
System.out.println(123); // Print an integer
System.out.println(45.67); // Print a floating point number
}
}
123
45.67
**Explanation**:
123
print hota hai.45.67
print hota hai.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");
}
}
//
se ek single-line comment start hota hai aur woh line ke baad tak valid hota hai./* */
se multi-line comment likhe jaate hain jisme kai lines ko comment kiya ja sakta hai.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
}
}
int
for integers, String
for text.Java mein variables ko print karne ke liye hum **System.out.println()** ka use karte hain. Ismein hum variables ko directly print kar sakte hain.
public class Main {
public static void main(String[] args) {
int age = 25;
String name = "John";
// Print variables
System.out.println("Name: " + name); // Print the value of name
System.out.println("Age: " + age); // Print the value of age
}
}
Name: John
Age: 25
**Explanation**:
System.out.println("Name: " + name);
se variable name
ki value print hoti hai.System.out.println("Age: " + age);
se variable age
ki value print hoti hai.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);
}
}
Name: John
Age: 25
Salary: 50000
City: New York
**Explanation**:
int age = 25, salary = 50000;
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
}
}
1age
aur age&name
invalid identifiers hain.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);
}
}
Car Model: Toyota Corolla
Car Speed: 120 km/h
Car Color: Red
**Explanation**:
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.
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);
}
}
Integer Number: 10
Float Number: 20.5
Double Number: 30.75
**Explanation**:
int
(integer), float
(single precision floating point), aur double
(double precision floating point) numbers ko declare kiya hai.System.out.println()
.
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);
}
}
Is Java Fun? true
**Explanation**:
true
ya false
isJavaFun
variable ko true
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);
}
}
Grade: A
**Explanation**:
'A'
.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);
}
}
Student Name: Alice
Age: 21
Grade: B
Height: 5.6
**Explanation**:
String
, int
, char
, aur double
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);
}
}
}
10
20
30
40
50
**Explanation**:
for-each
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);
}
}
Integer: 9
Double: 9.0
In this section, we will explore the different types of operators in Java, including arithmetic, relational, logical, and assignment 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));
}
}
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
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));
}
}
x > y: false
x < y: true
x == y: false
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.
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);
}
}
Hello, World!
Hello, Java!
In this section, we will explore string concatenation in Java, which is the process of combining two or more strings.
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);
}
}
Full Name: John Doe
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.
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);
}
}
The value is: 100
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.
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
}
}
Hello
World!
This is a tab.
He said, "Java is great!"
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 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);
}
}
Square root of 25.0 is: 5.0
2 raised to the power of 3 is: 8.0
In this section, we will explore the boolean data type in Java. A boolean represents one of two values: true
or false
.
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);
}
}
Is Java fun? true
Is fish tasty? false
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.
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.");
}
}
}
You are an adult.
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.");
}
}
}
You are not an adult.
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.");
}
}
}
You are an adult.
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);
}
}
You are an adult.
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.
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.");
}
}
}
You are eligible for a driver's license.
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.
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");
}
}
}
Wednesday
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.
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++;
}
}
}
0
1
2
3
4
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.
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);
}
}
0
1
2
3
4
In this section, we will explore real-life examples of how loops can be applied to solve everyday problems using Java loops.
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);
}
}
}
1
2
3
4
5
6
7
8
9
10
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);
}
}
Factorial of 5 is: 120
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.
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);
}
}
}
0
1
2
3
4
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.
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();
}
}
}
1 2 3
2 4 6
3 6 9
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.
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);
}
}
}
1
2
3
4
5
In this section, we will explore real-life examples of how for
loops can be applied to solve everyday problems using Java loops.
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);
}
}
}
2
4
6
8
10
12
14
16
18
20
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.
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);
}
}
}
0
1
2
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);
}
}
}
0
1
3
4
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.
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
}
}
30
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.
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]);
}
}
}
10
20
30
40
50
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);
}
}
}
10
20
30
40
50
In this section, we will explore some real-life examples where arrays can be applied in Java.
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);
}
}
Average Marks: 86.6
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.
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
}
}
6
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();
}
}
}
1 2 3
4 5 6
7 8 9
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.
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!");
}
}
Hello, Welcome to Java!
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.
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;
}
}
Sum: 15
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.
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;
}
}
Product: 20
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 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;
}
}
15
16.0
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.
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);
}
}
Global Variable: 10
Local Variable: 20
In this section, we will learn about recursion
in Java. Recursion is a process where a method calls itself to solve a problem.
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
}
}
}
Factorial of 5: 120
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).
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 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.
The four main principles of object-oriented programming are:
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.
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.");
}
}
The car has started.
Car Model: Toyota
Car Color: Red
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 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;
}
Car Model: BMW
Car Color: Blue
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.
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.");
}
}
The Green car has started.
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.
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;
}
}
Car Model: Toyota
Car Color: Red
In this section, we will explore modifiers
in Java. Modifiers determine the visibility and behavior of classes, methods, and variables.
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
}
Car Color: Yellow
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 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;
}
}
Car Color: Black
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.
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);
}
}
Enter your name: John
Hello, John
Inheritance is a mechanism in Java where one class acquires the properties (fields) and behaviors (methods) of another class. Inheritance supports reusability.
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
}
}
Dog barks.
Polymorphism allows one interface to be used for a general class of actions. It can take two forms: method overriding and method overloading.
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
}
}
Animal makes a sound.
Animal makes a growl
Dog barks.
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 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();
}
}
Hello from Outer Class!
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.
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();
}
}
Dog barks.
Animal eats food.
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.
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();
}
}
Dog barks.
Dog plays with a ball.
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.
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);
}
}
Today is: MONDAY
Java provides the Scanner
class for obtaining user input. It allows reading various types of data like strings, numbers, etc.
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);
}
}
Enter your age: 25
Your age is: 25
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.
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);
}
}
Current date and time: Sat Jan 11 10:59:42 IST 2025
An ArrayList
is a resizable array implementation of the List
interface. It allows storing dynamic data and provides several methods to manipulate the list.
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
}
}
Banana
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.
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
}
}
Chicago
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.
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);
}
}
Sorted list: [2, 5, 8]
A HashMap
is a collection that stores key-value pairs. It allows fast access to elements based on keys.
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"));
}
}
Capital of USA: Washington, D.C.
A HashSet
is a collection that does not allow duplicate elements. It stores elements in an unordered manner.
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]
}
}
[Apple, Banana]
An Iterator
is an object that can be used to traverse through a collection (like ArrayList
, HashSet
, etc.).
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());
}
}
}
Apple
Banana
Orange
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.
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);
}
}
Integer Wrapper: 10
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.
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
}
}
}
Error: / by zero
Java Regular Expressions (RegEx) are used for pattern matching within strings. The java.util.regex
package provides the classes for 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!");
}
}
}
Valid Email!
Java Threads allow for multi-threading, meaning multiple tasks can run concurrently. The Thread
class and the Runnable
interface are used for creating threads.
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
}
}
Thread is running
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.
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!");
}
}
Hello, Lambda!
Advanced sorting allows you to sort data in customized ways. Java provides various methods such as Comparator
and Comparable
for advanced 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);
}
}
[Kiwi, Apple, Banana]
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.
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.");
}
}
}
File does not exist.
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.
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());
}
}
}
File written successfully.
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.
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());
}
}
}
Hello, World!
In Java, you can delete files using the delete()
method of the File
class. This will remove the file from the file system.
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.");
}
}
}
File deleted successfully.
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.
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);
}
}
Enter first number: 5
Enter second number: 7
Sum of the numbers: 12
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);
}
}
Number of words: 6
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);
}
}
Reversed string: gnimmargorP avaJ
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);
}
}
Sum of array elements: 15
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 + " ");
}
}
}
String to array:
H e l l o
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 + " ");
}
}
}
Sorted array:
1 2 3 5 8
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);
}
}
Average of array elements: 30.0
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);
}
}
Smallest element in array: 1
Continuing with more examples like looping through an ArrayList, calculating the area of a rectangle, checking number properties, and generating random numbers.
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);
}
}
}
Apple
Banana
Orange
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());
}
}
}
India: New Delhi
USA: Washington D.C.
Japan: Tokyo
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);
}
}
}
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
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);
}
}
Area of rectangle: 15.0
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.");
}
}
}
7 is odd.
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.");
}
}
}
-5 is negative.
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);
}
}
Square root of 16 is: 4.0
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);
}
}
Random number: 42
In this section, we will explore various important Java keywords and their usage. Keywords are reserved words in Java that have special meanings.
Keywords in Java are predefined identifiers used to define the structure of the code. They cannot be used as variable names or identifiers.
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
}
}
Exception in thread "main" java.lang.AssertionError: Number is not positive
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
}
}
Bark
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
}
}
true
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);
}
}
}
1
2
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
}
}
100
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");
}
}
}
Wednesday
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
}
}
}
Error: / by zero
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.
In this section, we will explore various important Java keywords and their usage. Keywords are reserved words in Java that have special meanings.
Keywords in Java are predefined identifiers used to define the structure of the code. They cannot be used as variable names or identifiers.
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
}
}
19.99
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
}
}
}
Lesser or Equal
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
}
}
MONDAY
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;
}
This code declares that the package com.myapp
is accessible to other modules in the Java module system.
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
}
}
Bark
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
The MAX_VALUE
variable cannot be reassigned because it is declared as final.
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
}
}
}
Error: / by zero
This will always execute.
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
}
}
19.99
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
}
}
}
1
2
3
4
5
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
}
}
}
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.
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.
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
}
}
Bark
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);
}
}
Enter a number:
5
You entered: 5
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
}
}
true
true
false
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
}
}
The number is: 10
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.
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.
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
}
}
Bark
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);
}
}
The large number is: 1234567890123
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;
}
This module declaration specifies that mymodule
requires java.base
module.
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.
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!
}
}
Hello, World!
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!");
}
}
Hello from the com.example package!
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
}
}
The secret number is: 10
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
}
}
Animal sound
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
}
}
Public number: 100
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
}
}
Sum is: 15
The requires
keyword is used in module declarations to specify which other modules are required by the current module.
module mymodule {
requires java.base;
}
This module declaration specifies that mymodule
requires java.base
module.
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.
Below are more important Java keywords explained with examples. These keywords are reserved words that have special meanings in Java.
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
}
}
Short number: 1000
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
}
}
Counter: 1
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();
}
}
Animal makes sound
Dog barks
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");
}
}
}
Tuesday
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
}
}
Count: 1
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
}
}
Name: John
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
}
}
Exception in thread "main" java.lang.ArithmeticException: Not allowed
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
}
}
Exception in thread "main" java.lang.ArithmeticException: Not allowed
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...
}
}
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");
}
}
}
Cannot divide by zero
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
}
}
Number: 42
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!
}
}
Hello, World!
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();
}
}
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++;
}
}
}
i: 0
i: 1
i: 2
i: 3
i: 4
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
}
}
Character at index 1: e
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
}
}
Character at index 1: e
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
}
}
Code point before index 2: 101
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
}
}
Code point before index 2: 101
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"
}
}
Comparison result: -1
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
}
}
Comparison result: 0
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!
}
}
Hello, World!
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!
}
}
Hello, World!
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
}
}
Contains 'World': true
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
}
}
Result: Hello
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
}
}
Ends with 'World!': true
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
}
}
Strings are equal: true
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
}
}
Strings are equal (ignore case): true
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
}
}
Strings are equal (ignore case): true
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
}
}
Name: John, Age: 25
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
}
}
Hello
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
}
}
Hello
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
}
}
Hash code: 69609650
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
}
}
Is string empty: true
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 !
}
}
Hello World !
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 !
}
}
Hello World !
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
}
}
Last index of 'o': 8
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
}
}
Matches regex: true
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
}
}
Index after offset: 5
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
}
}
Regions match: true
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
}
}
apple-orange-banana
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
}
}
apple-orange-banana
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
}
}
}
apple
orange
banana
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
}
}
Starts with 'Hello': true
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
}
}
Starts with 'Hello': true
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!
}
}
World!
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
}
}
}
H e l l o
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
}
}
}
H e l l o
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!
}
}
hello world!
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!
}
}
Hello World!
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!
}
}
HELLO WORLD!
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!
}
}
Hello World!
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
}
}
100
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
}
}
5
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)
}
}
1.0471975511965979
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);
}
}
Exception in thread "main" java.lang.ArithmeticException: integer overflow
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)
}
}
0.5235987755982989
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)
}
}
0.7853981633974483
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)
}
}
0.7853981633974483
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
}
}
3.0
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
}
}
5.0
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
}
}
-5.0
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
}
}
-1.0
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
}
}
1.5430806348152437
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);
}
}
Exception in thread "main" java.lang.ArithmeticException: integer overflow
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
}
}
2.718281828459045
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
}
}
4.0
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
}
}
2
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
}
}
1
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)
}
}
3
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)
}
}
5.0
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
}
}
-1.0
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);
}
}
Exception in thread "main" java.lang.ArithmeticException: integer overflow
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
}
}
2.302585092994046
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
}
}
3.0
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
}
}
0.6931471805599453
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
}
}
20
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
}
}
10
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
}
}
10000000000
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
}
}
1.0000000000000002
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
}
}
0.9999999999999999
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
}
}
1.0000000000000002
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
}
}
8.0
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
}
}
0.8260892764043772
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
}
}
4.0
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
}
}
4
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)
}
}
12.0
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
}
}
-1
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
}
}
1.0
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
}
}
1.1752011936438014
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
}
}
50
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
}
}
1.0
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
}
}
0.7615941559557649
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
}
}
180.0
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
}
}
100000
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
}
}
3.141592653589793
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
}
}
2.220446049250313e-16
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
}
}
Hello, World!
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
}
}
The value of number is: 10
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!");
}
}
Hello, World!
Welcome to Java!
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)
}
}
0
-1
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
}
}
true
false
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
}
}
}
1
2
3
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
}
}
}
10
10
10
10
10
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
}
}
4
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]
}
}
[Apple, Banana]
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]
}
}
[Apple, Banana, Orange, Mango]
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: []
}
}
[]
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]
}
}
[Apple, Banana]
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
}
}
true
false
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]
}
}
[Apple, Banana]
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
}
}
Apple
Banana
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
}
}
Apple
Banana
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
}
}
1
-1
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
}
}
true
false
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());
}
}
}
Apple
Banana
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
}
}
2
-1
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());
}
}
}
Apple
Banana
Banana
Apple
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: []
}
}
[]
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]
}
}
[Banana]
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]
}
}
[Apple, Orange]
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]
}
}
[APPLE, BANANA]
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]
}
}
[Apple, Orange]
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
}
}
2
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]
}
}
[Apple, Banana, Orange]
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
}
}
Apple
Banana
Orange
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]
}
}
[Apple, Banana]
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);
}
}
}
Apple
Banana
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());
}
}
Capacity before trim: 2
Capacity after trim: 2
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]
}
}
[Apple, Banana]
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]
}
}
[Apple, Banana, Orange]
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: []
}
}
[]
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]
}
}
[Apple, Banana]
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
}
}
true
false
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));
}
}
Apple
Banana
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
}
}
Banana
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
}
}
Apple
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
}
}
Banana
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
}
}
1
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
}
}
true
false
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());
}
}
}
Apple
Banana
Orange
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
}
}
3
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());
}
}
}
Apple
Banana
Orange
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]
}
}
[Apple, Orange]
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]
}
}
[Orange]
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]
}
}
[Banana]
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]
}
}
[Apple]
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]
}
}
[APPLE, BANANA]
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]
}
}
[Banana, Orange]
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
}
}
3
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]
}
}
[Apple, Banana, Orange]
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);
}
}
Apple
Banana
Orange
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]
}
}
[Banana, Orange]
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);
}
}
}
Apple
Banana
Orange
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: {}
}
}
{}
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: {}
}
}
{}
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}
}
}
{Apple=15, Banana=20}
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}
}
}
{Apple=10, Banana=20}
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}
}
}
{Apple=15, Banana=20}
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
}
}
true
false
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
}
}
true
false
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());
}
}
}
Apple: 10
Banana: 20
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));
}
}
Apple: 10
Banana: 20
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
}
}
10
null
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
}
}
10
0
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
}
}
true
false
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]
}
}
[Apple, Banana]
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}
}
}
{Apple=15, Banana=20, Orange=10}
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}
}
}
{Apple=10, Banana=20}
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}
}
}
{Apple=10, Banana=20, Orange=30, Grape=40}
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}
}
}
{Apple=10, Banana=20, Orange=25}
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}
}
}
{Banana=20}
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}
}
}
{Apple=15, Banana=20}
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}
}
}
{Apple=20, Banana=40}
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
}
}
2
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]
}
}
[10, 20]
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();
}
}
Once close()
is called, the scanner cannot be used again.
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}+
}
}
\p{javaWhitespace}+
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
}
}
orange
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
}
}
orange
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
true
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
}
}
en_US
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
}
}
apple
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
}
}
true
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
}
}
100
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
}
}
5.5
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
}
}
3.14
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
}
}
42
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
}
}
Hello
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
}
}
10000000000
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
}
}
32000
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
}
}
2
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!");
}
}
Scanner reset successful!
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());
}
}
}
apple
orange
banana
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
}
}
fr
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
}
}
10
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());
}
}
}
Apple
Banana
Cherry
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());
}
}
}
Apple
Banana
Cherry
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]
}
}
[Apple, Cherry]
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);
}
}
}
Error: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
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);
}
}
}
Caught exception: java.lang.NullPointerException
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);
}
}
}
Caught exception: java.lang.ArithmeticException: / by zero
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);
}
}
}
Caught exception: java.io.FileNotFoundException: nonexistent.txt (No such file or directory)
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);
}
}
}
Caught exception: java.lang.ArithmeticException: / by zero
Here you can find some basic and advanced Java examples to help you understand Java programming concepts.
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 CompilerTry out these Java exercises to test your skills:
Take this quiz to check your knowledge of Java:
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:
Here is a basic syllabus for Java programming: