0% found this document useful (0 votes)
6 views

Concepts of Classes and Objects in Java

Uploaded by

nijoveh883
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Concepts of Classes and Objects in Java

Uploaded by

nijoveh883
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 122

INTRODUCATION:

Java was made by sun microsystems in “1991” and “USA” ”james


Gosling” who was one of the founders java he initially called it “ook”
and the goal of this language was to make a” simple, reliable” language.
JAVA ( Purely object oriented language)
--which means that if you want to write a code in java then you have to
do “ object oriented programming (oop)”.
--How to java works ?
-java is compiled into the bytecode and then it is interpreted to
machine code

Source Bytecode Machine


code code

Java installation –
Go to google and type =”install jdk”-
Installs java jdk
Go to google and type =”installed intelli idea”-
--what is jdk and what is jRE ?
JDK:- jdk stands for java development kit = vollection of
tools used for developing and running java programming
JRE:- Java Runtime Environment =java runtime
environment is need to run any java application so helps
in executing => helps in programs developed In java
1)Public class main {
public static void main(String []args)
{ System.out.print(“hello world”);
}
}
Output: hello world

Ex:
public class main {

because file’s name “main.java” that’s why


class name is “main”
public static void main (String[] args) {

public is on The main () method is the


access modifier here entry point into the application

//write you code here


System.out.println(“hello word”); ( Executed )
}
}
Public class main

Inside this main class we created a functions with name


“public static void main” and we put this inside the
Package named “ com.company”
- Basic Structure of a java program

What is package name ?


In Java, the package name refers to a specific identifier for a namespace that organizes classes,
interfaces, and sub-packages into a hierarchical structure. Each package name helps group related
classes together and avoid naming conflicts, promoting better organization and maintainability of the
code.

EX. Packge com.company; A package in java


Is used to group
Related classes
Think of it as a
Folder in a file

Directory.

Components of a Package Name

1. Package Declaration:
o The package name is declared at the top of a Java source file using the package
keyword.
o This declaration indicates that the classes defined in the file belong to the
specified package.

package com.example.myapp;

public class MyClass {


// Class content here
}

Concepts of Classes and Objects in Java:


 Class:

 A class in Java is a blueprint for creating objects. It defines the attributes (fields) and
methods (functions) that the objects created from the class will have.
 In Java, a class can include data members (variables) and methods.

 Object:

 An object is an instance of a class. It represents a specific entity with concrete values for
the class’s attributes.
 Each object can have unique values for its attributes but shares the same methods as
defined by its class.

 Example in Java

 Here’s a basic example of defining a class and creating an object in Java:


// Define a class named 'Car'
public class Car {
// Attributes (fields)
private String make;
private String model;
private int year;

// Constructor to initialize attributes


public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method to display car information


public void displayInfo() {
System.out.println(year + " " + make + " " + model);
}
// Main method to run the program
public static void main(String[] args) {
// Create an object (instance) of the Car class
Car myCar = new Car("Toyota", "Corolla", 2020);

// Use the object's method to display information


myCar.displayInfo();
}
}
Explanation

1. Class Definition:
o public class Car: Defines a class named Car.
o private String make;, private String model;, private int year;: These
are fields (attributes) of the Car class. They are private to restrict direct access from
outside the class.
o public Car(String make, String model, int year): This is a constructor
method used to initialize the attributes when a new Car object is created.
o public void displayInfo(): This is a method that prints the car’s details.

2. Creating an Object:
o Car myCar = new Car("Toyota", "Corolla", 2020);: Creates an instance of
the Car class named myCar with the attributes make, model, and year set to "Toyota",
"Corolla", and 2020, respectively.

3. Using the Object:


o myCar.displayInfo();: Calls the displayInfo method on the myCar object, which
prints the car's details in the format 2020 Toyota Corolla.

PRINCIPLES OF OBJECT ORIRNTED PROGRAMMING:


Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects,"
which can contain data and code. The main principles of OOP help in organizing software design and
improving code reusability, maintainability, and scalability. Here are the core principles:

1. Encapsulation

Definition: Encapsulation is the practice of bundling data (attributes) and methods (functions)
that operate on the data into a single unit, called a class. It restricts direct access to some of an
object's components, which can prevent the accidental modification of data.

Benefits:

 Information Hiding: Encapsulation hides the internal state of an object and requires all
interactions to be performed through methods.
 Reduced Complexity: By hiding the internal workings of objects, it reduces complexity
and increases modularity.

Example in Java:

public class Person {


private String name; // Private attribute

public Person(String name) {


this.name = name;
}

// Public method to access private attribute


public String getName() {
return name;
}

// Public method to modify private attribute


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

public static void main(String[] args) {


7 // Create a new Person object
Person person = new Person("John Doe");
System.out.println("Name: " + person.getName());
person.setName("Jane Doe");
System.out.println("Name: " + person.getName());
}
}
2. Abstraction

Definition: Abstraction is the concept of hiding the complex implementation details and showing
only the essential features of an object. It allows focusing on what an object does rather than how
it does it.
Benefits:

 Simplicity: Reduces complexity by exposing only the necessary parts of the object.
 Flexibility: Changes to the internal implementation do not affect how users interact with
the object.

Example in Java:

abstract class Animal {


abstract void makeSound(); // Abstract method

public void sleep() { // Concrete method


System.out.println("Sleeping...");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Woof!");
}
}
3. Inheritance
Definition: Inheritance is a mechanism where a new class (subclass or derived class) is based on
an existing class (superclass or base class). The subclass inherits attributes and methods from the
superclass and can add its own or override existing ones.

Benefits:

 Reusability: Allows the reuse of existing code without modification.


 Hierarchical Classification: Supports a natural hierarchy of classes.

Example in Java:

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

class Dog extends Animal {


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

public class Test {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Subclass method
}
}
4. Polymorphism

Definition: Polymorphism allows objects to be treated as instances of their parent class rather
than their actual class. The two types of polymorphism are method overloading and method
overriding.

 Method Overloading: Same method name with different parameters within the same
class.
 Method Overriding: Subclass provides a specific implementation of a method that is
already defined in its superclass.

Benefits:

 Flexibility: Enables one interface to be used for a general class of actions.


 Extensibility: Allows new classes to be added with minimal changes to existing code.

Example in Java:

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof!");
}
}

public class Test {


public static void main(String[] args) {
Animal myDog = new Dog(); // Polymorphism
myDog.makeSound(); // Calls Dog's version of
makeSound
}
}
ELEMENTARY CONCEPT OF OBHECT AND CLASSSES:
Basic Concepts

1. Class:
o Definition: A class in Java is a blueprint for creating objects. It defines the data
(attributes) and behaviors (methods) that the objects created from the class will
have.
o Attributes: Variables inside a class that represent the properties or state of an
object.
oMethods: Functions inside a class that define the actions or behaviors an object
can perform.
2. Object:
o Definition: An object is an instance of a class. It represents a specific realization
of the class with actual values for the class's attributes.
o Instantiation: The process of creating an object from a class.

Example in Java

Let’s go through a simple example to illustrate these concepts.

// Define a class named 'Car'


public class Car {
// Attributes (fields)
private String make;
private String model;
private int year;

// Constructor to initialize attributes


public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Method to display car information
public void displayInfo() {
System.out.println(year + " " + make + " " + model);
}

// Main method to run the program


public static void main(String[] args) {
// Create an object (instance) of the Car class
Car myCar = new Car("Toyota", "Corolla", 2020);

// Use the object's method to display information


myCar.displayInfo(); // Output: 2020 Toyota Corolla
}
}
Explanation

1. Class Definition:
o public class Car: Defines a class named Car. The public keyword means this
class can be accessed from other classes.
o private String make;, private String model;, private int year;: These
are attributes of the Car class. They are private to encapsulate the data.
o public Car(String make, String model, int year): This is the constructor
method that initializes the attributes when a new Car object is created.
o public void displayInfo(): This is a method that prints the details of the car.
2. Creating an Object:
o Car myCar = new Car("Toyota", "Corolla", 2020);: This line creates an
instance of the Car class. The myCar object has make, model, and year attributes
initialized with the values "Toyota", "Corolla", and 2020, respectively.
3. Using the Object:
o myCar.displayInfo();: Calls the displayInfo method on the myCar object.
This method prints the car's details to the console.

Key Points

 Class: Defines the structure (attributes) and behavior (methods) of objects.


 Object: An instance of a class, representing a specific example with its own data.
 Attributes: Variables that hold data about the object.
 Methods: Functions that define actions or behaviors for the object.

VALUES AND TYPES:


In programming, "values" and "types" are fundamental concepts that are closely related but represent
different aspects of how data is managed and manipulated. Let's break these concepts down and
explore them with a focus on Java.

Values

Definition: A value is the actual data stored in a variable. It represents the specific piece of
information that a variable holds. For example, if you have a variable age and assign it the value
25, then 25 is the value of the variable age.

Examples:

 Integer values: 42, -7


 Floating-point values: 3.14, -0.001
 Character values: 'a', 'Z'
 String values: "Hello, World!"

Java Example:

public class ValuesExample {


public static void main(String[] args) {
int age = 25; // Integer value
double height = 5.9; // Floating-point value
char initial = 'J'; // Character value
String name = "Alice"; // String value

System.out.println("Age: " + age);


System.out.println("Height: " + height);
System.out.println("Initial: " + initial);
System.out.println("Name: " + name);
}
}
Types

Definition: A type is a classification that specifies which kind of value a variable can hold and
what operations can be performed on that value. Types dictate the kind of data a variable can
store and how the program interprets that data.

In Java, types are broadly classified into two categories:

1. Primitive Types
2. Reference Types

1. Primitive Types

Definition: Primitive types are the basic data types provided by the language. They hold simple
values and are not objects. Java has eight primitive types.

Types and Their Examples:

 int: Integer type (e.g., 42)


 double: Double-precision floating-point type (e.g., 3.14)
 char: Character type (e.g., 'a')
 boolean: Boolean type (true or false)
 byte: 8-bit integer (e.g., 127)
 short: 16-bit integer (e.g., 32000)
 long: 64-bit integer (e.g., 123456789L)
 float: Single-precision floating-point type (e.g., 2.71f)

Java Example:

public class PrimitiveTypesExample {


public static void main(String[] args) {
int age = 25; // int type
double height = 5.9; // double type
char initial = 'J'; // char type
boolean isStudent = true; // boolean type

System.out.println("Age: " + age);


System.out.println("Height: " + height);
System.out.println("Initial: " + initial);
System.out.println("Is Student: " + isStudent);
}
}
2. Reference Types

Definition: Reference types refer to objects and arrays. They store references (or memory
addresses) to the actual data rather than the data itself.

Types and Their Examples:

 Classes: Custom data types defined by the user. (e.g., Car, Person)
 Interfaces: Types that define methods without implementing them. (e.g., Comparable,
Serializable)
 Arrays: Data structures that hold multiple values of the same type. (e.g., int[], String[])

Java Example:

// Define a class
class Person {
String name;
int age;

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

// Method
void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " +
age + " years old.");
}
}
public class ReferenceTypesExample {
public static void main(String[] args) {
// Create an object of the Person class
Person person = new Person("Alice", 30);
person.introduce(); // Output: Hi, I'm Alice and I'm
30 years old.

// Create an array of integers


int[] numbers = {1, 2, 3, 4, 5};
System.out.println("First number: " +
numbers[0]); // Output: First number: 1
}
}
OPERATORS IN JAVA:
Operators in Java are special symbols that perform operations on variables and values. Java provides a
rich set of operators that can be used for arithmetic, relational, logical, bitwise, and more. Here’s an
overview of the different types of operators in Java:

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations.

 Addition (+): Adds two operands.

int sum = 5 + 3; // 8
Subtraction (-): Subtracts the second operand from the first.
int difference = 5 - 3; // 2
Multiplication (*): Multiplies two operands.

int product = 5 * 3; // 15
Division (/): Divides the first operand by the second. For integers, it performs integer division

int quotient = 5 / 3; // 1
Modulus (%): Returns the remainder of division.

int remainder = 5 % 3; // 2
2. Relational Operators

Relational operators are used to compare two values.

 Equal to (==): Checks if two values are equal.

boolean isEqual = (5 == 3); // false


Not equal to (!=): Checks if two values are not equal.

boolean isNotEqual = (5 != 3); // true


Greater than (>): Checks if the first value is greater than the second.

boolean isGreater = (5 > 3); // true


Less than (<): Checks if the first value is less than the second.

boolean isLess = (5 < 3); // false


Greater than or equal to (>=): Checks if the first value is greater than or equal to the second.

boolean isGreaterOrEqual = (5 >= 5); // true


Less than or equal to (<=): Checks if the first value is less than or equal to the second.

boolean isLessOrEqual = (5 <= 3); // false


3) Logical Operators
Logical operators are used to perform logical operations and return boolean results.

 Logical AND (&&): Returns true if both operands are true.

java

boolean result = (5 > 3 && 8 > 6); // true

 Logical OR (||): Returns true if at least one of the operands is true.

java
oolean result = (5 > 3 || 8 < 6); // true

 Logical NOT (!): Inverts the value of a boolean expression.

java
boolean result = !(5 > 3); // false

4. Bitwise Operators

Bitwise operators operate on the binary representation of integers.

 AND (&): Performs a bitwise AND operation.

java
int result = 5 & 3; // 1 (binary 0101 & 0011 = 0001)

 OR (|): Performs a bitwise OR operation.

java
int result = 5 | 3; // 7 (binary 0101 | 0011 = 0111)

 XOR (^): Performs a bitwise XOR operation.

java
int result = 5 ^ 3; // 6 (binary 0101 ^ 0011 = 0110)

 Complement (~): Inverts all the bits of the operand.

java
int result = ~5; // -6 (binary ~0101 = 1010)

 Left Shift (<<): Shifts bits to the left.

java
int result = 5 << 1; // 10 (binary 0101 << 1 = 1010)

 Right Shift (>>): Shifts bits to the right.


java
int result = 5 >> 1; // 2 (binary 0101 >> 1 = 0010)

 Unsigned Right Shift (>>>): Shifts bits to the right and fills the leftmost bits with zeros.

java
int result = 5 >>> 1; // 2

5. Assignment Operators

Assignment operators are used to assign values to variables.

 Assignment (=): Assigns the right-hand operand to the left-hand variable.

java
int x = 5; // x is assigned 5

 Add and assign (+=): Adds the right-hand operand to the left-hand variable and assigns
the result.

java
int x = 5;
x += 3; // x is now 8

 Subtract and assign (-=): Subtracts the right-hand operand from the left-hand variable
and assigns the result.

java
int x = 5;
x -= 3; // x is now 2

 Multiply and assign (*=): Multiplies the left-hand variable by the right-hand operand
and assigns the result.

java
int x = 5;
x *= 3; // x is now 15

 Divide and assign (/=): Divides the left-hand variable by the right-hand operand and
assigns the result.

java
int x = 6;
x /= 3; // x is now 2

 Modulus and assign (%=): Applies the modulus operator and assigns the result.

java
int x = 5;
x %= 3; // x is now 2
6. Unary Operators

Unary operators operate on a single operand.

 Unary Plus (+): Indicates a positive value (usually optional).

java
int x = +5; // 5

 Unary Minus (-): Negates the value.

java
int x = -5; // -5

 Increment (++): Increases the value by 1.

java
int x = 5;
x++; // x is now 6

 Decrement (--): Decreases the value by 1.

java
int x = 5;
x--; // x is now 4

7. Conditional (Ternary) Operator

The conditional operator is a shorthand for the if-else statement.

 Conditional (?:): Evaluates a boolean expression and returns one of two values.

java
int x = (5 > 3) ? 10 : 20; // x is 10 because 5 > 3 is true

8. instanceof Operator

The instanceof operator checks whether an object is an instance of a specific class or subclass.

 instanceof: Tests if an object is an instance of a specific class or subclass.

java
String str = "Hello";
boolean result = str instanceof String; // true

mathematical libray methods in java


Java has a rich set of mathematical library methods that can be used for various
mathematical operations. Here are some of the most commonly used mathematical
library methods in Java:

For example, do you want me to write code to:

 Calculate the area of a circle using the Math class?


 Generate random numbers using the Random class?
 Perform arithmetic operations using BigInteger or BigDecimal classes?
 Implement a mathematical algorithm, such as the Fibonacci sequence or the Euclidean
algorithm?

Math Class

The Math class in Java provides a wide range of mathematical methods for tasks such
as trigonometry, logarithms, exponentiation, and more. Here are some of the most
commonly used methods:

import java.lang.Math;

public class CircleArea {

public static void main(String[] args) {

double radius = 5.0;

double area = Math.PI * Math.pow(radius, 2);

System.out.println("The area of the circle with radius " + radius + " is " +
area);

Let's say you want to calculate the area of a circle with a radius of 5 using
the Math class. Here's an example code snippet that does that:

Random Class

If you want to generate random numbers using the Random class, here's an example
code snippet that generates 10 random integers between 0 and 100:
import java.util.Random;

public class RandomNumbers {

public static void main(String[] args) {

Random rand = new Random();

for (int i = 0; i < 10; i++) {

int num = rand.nextInt(101); // generates a random integer between 0


(inclusive) and 101 (exclusive)

System.out.println(num);

The Random class in Java provides methods for generating random numbers. Here are
some of the most commonly used methods:

BigInteger and BigDecimal Classes

The BigInteger and BigDecimal classes in Java provide support for arbitrary-precision
arithmetic. Here are some of the most commonly used methods:

If you want to perform arithmetic operations using BigInteger or BigDecimal classes,


here's an example code snippet that adds, subtracts, multiplies, and divides
two BigDecimal values:

import java.math.BigDecimal;

public class BigDecimalArithmetic {

public static void main(String[] args) {

BigDecimal num1 = new BigDecimal("123.456");

BigDecimal num2 = new BigDecimal("789.123");


BigDecimal sum = num1.add(num2);

BigDecimal diff = num1.subtract(num2);

BigDecimal prod = num1.multiply(num2);

BigDecimal quot = num1.divide(num2, 10, BigDecimal.ROUND_HALF_UP); //


rounds to 10 decimal places

System.out.println("Sum: " + sum);

System.out.println("Difference: " + diff);

System.out.println("Product: " + prod);

System.out.println("Quotient: " + quot);

This code creates two BigDecimal objects, performs arithmetic operations using
the add, subtract, multiply, and divide methods, and prints the results to the
console.

conditional constructs in java


In Java, conditional constructs are used to control the flow of a program's execution based on
certain conditions or decisions. Here are the main conditional constructs in Java:

1. If-Else Statement
The if-else statement is used to execute a block of code if a certain condition is true,
and another block of code if the condition is false.

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example:

public class IfElseExample {


public static void main(String[] args) {
int x = 5;
if (x > 10) {
System.out.println("x is greater than 10");
} else {
System.out.println("x is less than or equal to 10");
}
}
}
3. If-Else-If Ladder

Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and
condition2 is true
} else if (condition3) {
// code to be executed if condition1 and condition2 are
false and condition3 is true
} else {
// code to be executed if all conditions are false
}

Example
public class IfElseIfExample {
public static void main(String[] args) {
int x = 5;
if (x > 10) {
System.out.println("x is greater than 10");
} else if (x == 5) {
System.out.println("x is equal to 5");
} else {
System.out.println("x is less than 5");
}
}
}
3. Switch Statement

The switch statement is used to execute different blocks of


code based on the value of an expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
...
default:
// code to be executed if expression does not match any
case
}
Example:

public class SwitchExample {


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;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
4. Ternary Operator (Conditional Operator)
The ternary operator is a concise way to write an if-else statement.
Syntax:
condition ? expression1 : expression2

Example:
public class TernaryExample {
public static void main(String[] args) {
int x = 5;
String result = x > 10 ? "x is greater than 10" : "x is
less than or equal to 10";
System.out.println(result);
}
}
In this example, the condition x > 10 is evaluated. Since x is 5, the condition is false,
and the second expression "x is less than or equal to 10" is assigned to
the result variable, which is then printed.
Selection statements in Java!
In Java, selection statements are used to control the flow of a program's execution
based on certain conditions or decisions. There are four types of selection statements in
Java:

1. If Statement
The if statement is used to execute a block of code if a certain condition is true.

Syntax:
if (condition) {
// code to be executed if condition is true
}

Example:
public class IfExample {
public static void main(String[] args) {
int x = 5;
if (x > 10) {
System.out.println("x is greater than 10");
}
}
}

2. If-Else Statement
The if-else statement is used to execute a block of code if
a certain condition is true, and another block of code if
the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example:
public class IfElseExample {
public static void main(String[] args) {
int x = 5;
if (x > 10) {
System.out.println("x is greater than 10");
} else {
System.out.println("x is less than or equal to 10");
}
}
}

3. If-Else-If Ladder
The if-else-if ladder is used to check multiple conditions
and execute different blocks of code based on those
conditions.

Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and
condition2 is true
} else if (condition3) {
// code to be executed if condition1 and condition2 are
false and condition3 is true
} else {
// code to be executed if all conditions are false
}
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int x = 5;
if (x > 10) {
System.out.println("x is greater than 10");
} else if (x == 5) {
System.out.println("x is equal to 5");
} else {
System.out.println("x is less than 5");
}
}
}
4. Switch Statement
The switch statement is used to execute different blocks
of code based on the value of an expression.

Syntax:
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
...
default:
// code to be executed if expression does not match
any case
}
Example:
public class SwitchExample {
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;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
iteration statements-loops in java:
Iteration statements, also known as loops, in Java!

In Java, iteration statements are used to execute a


block of code repeatedly for a specified number of
times. There are three types of iteration statements
in Java:

1. For Loop
The for loop is used to execute a block of code for a
specified number of times.

Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:

public class ForLoopExample {


public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}
}
}
2. While Loop
The while loop is used to execute a block of code as
long as a certain condition is true.

Syntax:
while (condition) {
// code to be executed
}
Example:

public class WhileLoopExample {


public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("Iteration " + i);
i++;
}
}
}
3. Do-While Loop
The do-while loop is similar to the while loop, but
the code inside the loop is executed at least once
before the condition is checked.
Syntax:
do {
// code to be executed
} while (condition);
Example:

public class DoWhileLoopExample {


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

Enhanced For Loop (For-Each Loop)


The enhanced for loop, also known as the for-each loop, is used to iterate over an array
or a collection.

Syntax:

for (type variable : array/collection) {

// code to be executed

Example:

public class ForEachLoopExample {


public static void main(String[] args) {

int[] scores = {10, 20, 30, 40, 50};

for (int score : scores) {

System.out.println("Score: " + score);

Jump statements in Java!

In Java, jump statements are used to transfer control to another part of


the program. There are three types of jump statements in Java:

1. Break Statement
The break statement is used to exit a loop or a switch statement.

Syntax:
break;
Example:

public class BreakExample {


public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println("Iteration " + i);
}
}
}

2. Continue Statement
The continue statement is used to skip the current iteration of a loop and
move to the next iteration.

Syntax:
continue;
EXMPLE:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // skip the current iteration when i is 5
}
System.out.println(i);
}
System.out.println("Loop completed");
}
}

3. Return Statement
The return statement is used to exit a method and return a value to the
caller. When a return statement is encountered, the control is transferred
to the caller of the method.

EXAMPL:
public class ReturnExample {
public static int add(int a, int b) {
if (a == 0) {
return 0; // return 0 if a is 0
}
return a + b;
}

public static void main(String[] args) {


int result = add(2, 3);
System.out.println("Result: " + result);
}
}

Nested For Loops in Java!


In Java, a nested for loop is a loop within a loop, where the
inner loop is completely executed for each iteration of the outer
loop. The inner loop is executed repeatedly for each iteration of
the outer loop.

Here's the general syntax for a nested for loop:

SYNTEX:
for (initialization; condition; increment/decrement) {
// outer loop body
for (initialization; condition; increment/decrement) {
// inner loop body
}
}

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

In this example, the outer loop iterates 3 times (i = 1, 2, 3), and for each iteration of the
outer loop, the inner loop iterates 3 times (j = 1, 2, 3). The output will be:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

Step-by-Step Explanation:

Step 1: for (int i = 1; i <= 3; i++) {

We declare a variable i and initialize it to 1.


The condition i <= 3 is checked. Since i is 1, the condition is true, and the
loop body is executed.
The increment i++ is executed at the end of each iteration, which
increments i by 1.
Step 2: for (int j = 1; j <= 3; j++) {

We declare a variable j and initialize it to 1.


The condition j <= 3 is checked. Since j is 1, the condition is true, and the
inner loop body is executed.
The increment j++ is executed at the end of each iteration, which
increments j by 1.
Step 3: System.out.println("i = " + i + ", j = " + j);

The inner loop body is executed, which prints the values of i and j using
System.out.println.
The output will be: i = 1, j = 1
Step 4: Repeat Step 2-3 until j reaches 3.

The inner loop iterates 3 times, with j taking values 1, 2, and 3.


The output will be:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3

Step 5: Repeat Step 1-4 until i reaches 3.

The outer loop iterates 3 times, with i taking values 1, 2, and 3.


The inner loop is executed repeatedly for each iteration of the outer loop.
The output will be:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

2.CLASS AS THE BASIC OF ALL COMPUATION


7. Arrays
Index of arrays:
In Java, the index of an array starts at 0, meaning the first element of
the array is accessed using index 0, the second element with index 1,
and so on.

Here’s an example in Java:

public class ArrayExample {


public static void main(String[] args) {
// Declare and initialize an array
int[] arr = {10, 20, 30, 40, 50};
// Accessing elements by index
System.out.println("Element at index 0: " + arr[0]); // Output: 10
System.out.println("Element at index 2: " + arr[2]); // Output: 30
System.out.println("Element at index 4: " + arr[4]); // Output: 50
}
}

Key Points:
 Array Index Starts at 0: The first element is arr[0], the
second is arr[1], etc.
 Accessing Out of Bound Index: Trying to access an index
outside the array size, like arr[5] for a 5-element array, will
throw an ArrayIndexOutOfBoundsException.

Declaring ,initialising and acccepting data in anarray

In Java, an array can be declared, initialized, and data can


be accepted from the user using the following steps:
1. Declaring an Array:
This defines the type and size of the array.
java
Copy code
int[] arr; // Declaration of an array of integers
2. Initializing an Array:
Arrays must be initialized before use. This can be done
either when you declare the array or afterward.
java
Copy code
arr = new int[5]; // Initialize the array with 5 elements
Alternatively, you can declare and initialize an array in one
step:
java
Copy code
int[] arr = new int[5]; // Declares and initializes an array of
size 5
You can also directly initialize the array with specific
values:
java
Copy code
int[] arr = {10, 20, 30, 40, 50}; // Declare, initialize, and
assign values
3. Accepting Data into an Array (Input from User):
To accept data from the user, you can use the Scanner
class. Below is a full example of how to declare, initialize,
and accept data into an array.
Example:
java
Copy code
import java.util.Scanner;

public class ArrayInputExample {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Declare and initialize an array


int[] arr = new int[5]; // Array of 5 integers

// Accept input from the user


System.out.println("Enter 5 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt(); // Read each integer and
store it in the array
}

// Print the array elements


System.out.println("You entered:");
for (int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " +
arr[i]);
}

// Close the scanner to prevent resource leaks


scanner.close();
}
}
Breakdown of the Example:
1. Declaration: int[] arr = new int[5]; declares and initializes
an array of size 5.
2. User Input: The Scanner object is used to accept input from
the user.
3. Loop: A for loop is used to iterate through the array,
allowing the user to enter values one by one.
4. Printing: Another for loop is used to print the entered
values.
Example Output:
Enter 5 integers:
1
2
3
4
5
You entered:
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
Key Points:
 new int[5]: Creates an array of 5 integers.
 arr.length: Gives the size of the array, in this case, 5.
 Scanner Input: scanner.nextInt() reads the input from the
user and stores it in the array.

Acccessing data of an array:


In Java, accessing the data of an array is done by referring to the
array's index. Since array indices start from 0, you can retrieve
elements by using the index numbers in square brackets [].
Here’s a step-by-step guide on accessing array elements:
Accessing Data of an Array
1. Using Index: To access individual elements, use the array's
name followed by the index inside square brackets.

int[] arr = {10, 20, 30, 40, 50}; // Declare and initialize the array

System.out.println(arr[0]); // Output: 10 (first element)


System.out.println(arr[2]); // Output: 30 (third element)
System.out.println(arr[4]); // Output: 50 (fifth element)
2. Looping through the Array: A loop, such as a for loop, is
commonly used to access all elements in an array.
Example:

public class AccessArray {


public static void main(String[] args) {
// Declare and initialize an array
int[] arr = {10, 20, 30, 40, 50};

// Loop through the array and print each element


for (int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " +
arr[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
3. Enhanced For Loop (For-Each Loop): You can also use an
enhanced for loop (for-each loop) to access array elements
without worrying about the index.
Example:

public class AccessArrayForEach {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};

// Enhanced for loop to access each element


for (int element : arr) {
System.out.println("Element: " + element);
}
}
}

Output:
Element: 10
Element: 20
Element: 30
Element: 40
Element: 50
Key Points:
 Indexing starts at 0: The first element is arr[0], the second
is arr[1], etc.
 Accessing array elements using a loop is efficient when
you need to iterate through the entire array.
 Array length: arr.length gives the size of the array, so a
loop runs from 0 to arr.length - 1 to cover all elements.
 Out of Bounds: Accessing an index outside the array's
length (like arr[5] in a 5-element array) will result in an
ArrayIndexOutOfBoundsException.

Searching:
In Java, searching for an element in an array can be done in
different ways depending on the type of search you need. The
two most common types of searching algorithms are linear
search and binary search.
1. Linear Search:
In a linear search, each element of the array is checked one by
one until the desired element is found or the end of the array is
reached. This method works for unsorted arrays.
Example of Linear Search:

public class LinearSearch {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;

int index = -1; // Variable to store the index of the element


if found

// Linear search algorithm


for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
index = i;
break; // Exit the loop once the element is found
}
}

if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found.");
}
}
}
Explanation:
 Input: An array of integers and a target value (30).
 Output: The index where the target value is found or a
message saying "Element not found".
 Process: The loop iterates through the array, checking each
element. When it finds the target, it breaks the loop and
outputs the index.
2. Binary Search:
Binary search is a more efficient searching method but it only
works on sorted arrays. It repeatedly divides the array in half,
checking if the middle element is the target. Depending on
whether the target is greater or smaller, it narrows the search to
one half of the array.
Example of Binary Search:
import java.util.Arrays;

public class BinarySearch {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50}; // The array must be sorted
int target = 30;

// Call binary search method from Arrays class


int index = Arrays.binarySearch(arr, target);

if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found.");
}
}
}
Explanation:
 Input: A sorted array of integers and a target value (30).
 Output: The index where the target value is found or a
message saying "Element not found".
 Process: The Arrays.binarySearch() method performs the
binary search and returns the index of the target if found. If
the target is not found, it returns a negative number.
Key Differences:
 Linear Search works on both sorted and unsorted arrays but
has a time complexity of O(n) (where n is the size of the
array), meaning it may check each element.
 Binary Search only works on sorted arrays but is more
efficient with a time complexity of O(log n), significantly
reducing the number of comparisons.
Example Output for Binary Search:
Element found at index: 2

Sorting:
In Java, sorting an array can be done using various algorithms.
The two most commonly used approaches are Bubble Sort and
Built-in Sort (using Arrays.sort()).
1. Bubble Sort (Manual Sorting Algorithm):
Bubble Sort is a simple comparison-based algorithm where each
pair of adjacent elements is compared, and the elements are
swapped if they are in the wrong order. This process repeats
until the array is sorted.
Example of Bubble Sort:

public class BubbleSort {


public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};

// Call the bubble sort method


bubbleSort(arr);

// Print the sorted array


System.out.println("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}

// Bubble sort method


public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
// Swap if the element is greater than the next
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
Explanation:
 Input: An unsorted array of integers {64, 34, 25, 12, 22,
11, 90}.
 Output: A sorted array {11, 12, 22, 25, 34, 64, 90}.
 Process: Bubble Sort repeatedly compares adjacent
elements and swaps them if they are in the wrong order. It
does this until the entire array is sorted.
Example Output:
Sorted array:
11 12 22 25 34 64 90
2. Built-in Sorting using Arrays.sort():
Java provides a built-in method for sorting arrays in the Arrays
class, which implements an efficient sorting algorithm (dual-
pivot quicksort for primitive types).
Example using Arrays.sort():

import java.util.Arrays;

public class BuiltInSort {


public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};

// Use Arrays.sort to sort the array


Arrays.sort(arr);

// Print the sorted array


System.out.println("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
Explanation:
 Input: An unsorted array of integers {64, 34, 25, 12, 22,
11, 90}.
 Output: A sorted array {11, 12, 22, 25, 34, 64, 90}.
 Process: The Arrays.sort() method automatically sorts the
array in ascending order.
Key Differences:
 Bubble Sort: Simple but inefficient for large arrays with a
time complexity of O(n²). It is mainly used for educational
purposes.
 Arrays.sort(): This method is highly optimized and uses an
efficient sorting algorithm with an average time complexity
of O(n log n).
Sorting in Descending Order:
To sort an array in descending order using Arrays.sort(), you can
use a Comparator.
Example of Descending Order Sort:

import java.util.Arrays;
import java.util.Collections;
public class DescendingSort {
public static void main(String[] args) {
Integer[] arr = {64, 34, 25, 12, 22, 11, 90}; // Use Integer
instead of int

// Use Arrays.sort with Collections.reverseOrder() to sort in


descending order
Arrays.sort(arr, Collections.reverseOrder());

// Print the sorted array


System.out.println("Sorted array in descending order:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
Example Output:

Sorted array in descending order:


90 64 34 25 22 12 11
Key Points:
 Bubble Sort is a manual sorting method and is slower for
large arrays.
 Arrays.sort() is fast and efficient, making it the preferred
method for most sorting tasks.
 Descending Order: Requires a bit more work using
Collections.reverseOrder() but is easily handled for non-
primitive types like Integer.

Bubble sorting:

Bubble Sort in Java (Sorting Algorithm)


Bubble Sort is a simple sorting algorithm where each pair of
adjacent elements is compared, and the elements are swapped if
they are in the wrong order. The process repeats until the entire
array is sorted.
Steps of Bubble Sort:
1. Start from the first element.
2. Compare the current element with the next element.
3. If the current element is greater than the next one, swap
them.
4. Move to the next element and repeat steps 2 and 3 until the
end of the array.
5. Repeat the process for the entire array until no more swaps
are needed.
Example Code in Java:

public class BubbleSort {


public static void main(String[] args) {
// Declare and initialize an array
int[] arr = {64, 34, 25, 12, 22, 11, 90};

// Call the bubble sort method to sort the array


bubbleSort(arr);

// Print the sorted array


System.out.println("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}

// Bubble sort method


public static void bubbleSort(int[] arr) {
int n = arr.length; // Get the size of the array
boolean swapped;

// Outer loop to go through all elements


for (int i = 0; i < n - 1; i++) {
swapped = false; // Initialize swapped as false

// Inner loop for comparing adjacent elements


for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1] if they are in the wrong
order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;

swapped = true; // Mark that a swap has happened


}
}

// If no elements were swapped during the inner loop,


break (the array is already sorted)
if (!swapped) {
break;
}
}
}
}
Explanation:
 Input: The unsorted array {64, 34, 25, 12, 22, 11, 90}.
 Output: The sorted array {11, 12, 22, 25, 34, 64, 90}.
 Process: The algorithm repeatedly compares and swaps
adjacent elements until the largest element moves to the
end of the array after each pass.
Key Points:
 Time Complexity: Bubble Sort has a time complexity of
O(n²), where n is the number of elements. This means it
becomes inefficient for large arrays.
 Swaps: Bubble Sort repeatedly swaps adjacent elements if
they are in the wrong order.
 Optimization: If no swaps occur during a pass through the
array, the algorithm can stop early, indicating that the array
is already sorted.
Example Output:

Sorted array:
11 12 22 25 34 64 90
How It Works:
 After the first pass, the largest element (90) "bubbles up" to
the correct position at the end of the array.
 After the second pass, the second-largest element (64) is
placed correctly.
 This process continues until all elements are in the correct
order.
Visual Example:
Initial Array:
[64, 34, 25, 12, 22, 11, 90]
After 1st Pass:
[34, 25, 12, 22, 11, 64, 90]
After 2nd Pass:
[25, 12, 22, 11, 34, 64, 90]
After 3rd Pass:
[12, 22, 11, 25, 34, 64, 90]
Final Sorted Array:
[11, 12, 22, 25, 34, 64, 90]
When to Use Bubble Sort:
 Small datasets: Since Bubble Sort is easy to implement
and understand, it can be useful for small arrays or
educational purposes.
 Already nearly sorted data: In cases where the array is
almost sorted, Bubble Sort can quickly finish sorting due to
the optimization of stopping early when no swaps are
made.

Selection sorting:

Selection Sort in Java (Sorting Algorithm)


Selection Sort is an in-place, comparison-based sorting
algorithm. It works by repeatedly selecting the smallest (or
largest, depending on sorting order) element from the unsorted
portion of the array and swapping it with the first unsorted
element. The process is repeated until the array is sorted.
Steps of Selection Sort:
1. Start from the first element.
2. Find the smallest element in the unsorted part of the array.
3. Swap the smallest element with the first unsorted element.
4. Move the boundary between the sorted and unsorted parts
one element to the right.
5. Repeat the process for all elements until the array is sorted.
Example Code in Java:
public class SelectionSort {
public static void main(String[] args) {
// Declare and initialize an array
int[] arr = {64, 25, 12, 22, 11};

// Call the selection sort method to sort the array


selectionSort(arr);

// Print the sorted array


System.out.println("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}

// Selection sort method


public static void selectionSort(int[] arr) {
int n = arr.length;

// Move the boundary of the unsorted part of the array


for (int i = 0; i < n - 1; i++) {
// Find the index of the minimum element in the unsorted
part
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update minIndex if a smaller
element is found
}
}

// Swap the found minimum element with the first


unsorted element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
Explanation:
 Input: An unsorted array {64, 25, 12, 22, 11}.
 Output: The sorted array {11, 12, 22, 25, 64}.
 Process: The algorithm selects the smallest element from
the unsorted part of the array and swaps it with the first
unsorted element. This is repeated until the entire array is
sorted.
Example Output:

Sorted array:
11 12 22 25 64
How It Works:
 First Pass: The smallest element (11) is found and
swapped with the first element (64).
 Second Pass: The next smallest element (12) is found and
swapped with the second element (25).
 This process continues until the array is completely sorted.
Visual Example:
Initial Array:
[64, 25, 12, 22, 11]
After 1st Pass (Smallest element is 11):
[11, 25, 12, 22, 64]
After 2nd Pass (Next smallest element is 12):
[11, 12, 25, 22, 64]
After 3rd Pass (Next smallest element is 22):
[11, 12, 22, 25, 64]
Final Sorted Array:
[11, 12, 22, 25, 64]
Key Points:
 Time Complexity: Selection Sort has a time complexity of
O(n²) because it uses two nested loops, making it
inefficient for large arrays.
 Swaps: It makes fewer swaps compared to Bubble Sort, but
the number of comparisons is still high.
 In-place Sorting: The sorting is done in place, meaning it
doesn’t require extra memory space for sorting (apart from
the temporary variable used for swapping).
Advantages of Selection Sort:
 Simple to implement and easy to understand.
 Minimizes the number of swaps compared to other
algorithms like Bubble Sort, which may be useful if
swapping elements is expensive.
Disadvantages of Selection Sort:
 Inefficient for large datasets due to its quadratic time
complexity.
 Always performs the same number of comparisons, even if
the array is already sorted.
When to Use Selection Sort:
 Small datasets: It works fine for small arrays where its
simplicity is more valuable than efficiency.
 Low swap overhead: If you want to minimize the number
of swaps and are okay with extra comparisons, Selection
Sort can be a reasonable choice.

Two dimensional arrays:

Two-Dimensional Arrays in Java


A two-dimensional array in Java is an array of arrays, where
each element of the array is also an array. It is often visualized
as a table or matrix with rows and columns.
Declaration and Initialization
1. Declaration: A two-dimensional array is declared by
specifying two sets of square brackets.
java
Copy code
int[][] arr;
2. Initialization: You can initialize a two-dimensional array
by specifying the number of rows and columns.
arr = new int[3][4]; // 3 rows and 4 columns
Or you can initialize it with values directly:
int[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
This creates a 3x4 array.
Accessing Elements in a 2D Array
You can access an element in a 2D array by specifying both the
row and column indices. Indices start from 0.

int element = arr[1][2]; // Access element at row 1, column 2


(output: 7)
Example of Declaring, Initializing, and Accessing a 2D
Array:

public class TwoDArrayExample {


public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

// Access and print a specific element


System.out.println("Element at row 1, column 2: " + arr[1]
[2]); // Output: 7

// Print all elements of the 2D array


System.out.println("All elements in the array:");
for (int i = 0; i < arr.length; i++) { // Loop through
rows
for (int j = 0; j < arr[i].length; j++) { // Loop through
columns
System.out.print(arr[i][j] + " ");
}
System.out.println(); // Move to the next line after
printing a row
}
}
}
Output:

Element at row 1, column 2: 7


All elements in the array:
1234
5678
9 10 11 12
Nested Loops for 2D Arrays:
 The outer loop iterates through the rows of the 2D array.
 The inner loop iterates through the columns (elements)
within a specific row.
Example: Accepting User Input for a 2D Array
You can use the Scanner class to take input from the user for a
2D array.

import java.util.Scanner;

public class Input2DArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Declare a 2D array of size 2x3 (2 rows, 3 columns)


int[][] arr = new int[2][3];

// Accept input from the user


System.out.println("Enter elements for a 2x3 matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("Enter element for row " + i + ",
column " + j + ": ");
arr[i][j] = scanner.nextInt(); // Store user input in the
array
}
}

// Print the elements of the 2D array


System.out.println("The matrix is:");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println(); // Move to the next line after
printing a row
}

// Close the scanner to prevent resource leak


scanner.close();
}
}
Example Input/Output:

Enter elements for a 2x3 matrix:


Enter element for row 0, column 0: 1
Enter element for row 0, column 1: 2
Enter element for row 0, column 2: 3
Enter element for row 1, column 0: 4
Enter element for row 1, column 1: 5
Enter element for row 1, column 2: 6
The matrix is:
123
456
Important Notes:
1. Array Length:
o arr.length gives the number of rows in the array.
o arr[i].length gives the number of columns in row i.
2. Jagged Arrays: In Java, 2D arrays can be "jagged,"
meaning each row can have a different number of columns.
int[][] jaggedArr = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
Here, the first row has 3 elements, the second row has 2
elements, and the third row has 4 elements.

Exercises:
Here are some exercises related to two-dimensional arrays in
Java. These exercises will help you practice declaration,
initialization, accessing elements, and performing operations on
2D arrays.
Exercise 1: Create and Print a 2D Array
1. Task: Create a 3x3 integer matrix and initialize it with
values from 1 to 9.
2. Output: Print the matrix in a structured format.

public class Exercise1 {


public static void main(String[] args) {
// Create and initialize a 3x3 array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Print the matrix


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(); // Move to the next line after each
row
}
}
}
Exercise 2: Sum of Elements in a 2D Array
1. Task: Write a program to create a 2D array of integers and
calculate the sum of all its elements.
2. Input: The user should provide the dimensions (rows and
columns) of the array and the elements.

import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input dimensions
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

// Create and initialize the array


int[][] array = new int[rows][cols];

// Input elements
System.out.println("Enter elements of the array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = scanner.nextInt();
}
}
// Calculate the sum of elements
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum += array[i][j];
}
}

// Print the sum


System.out.println("Sum of all elements: " + sum);

scanner.close();
}
}
Exercise 3: Transpose of a Matrix
1. Task: Write a program that takes a 2D array as input and
prints its transpose.
2. Input: The user should provide the dimensions and the
elements of the matrix.

import java.util.Scanner;
public class Exercise3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input dimensions
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

// Create and initialize the array


int[][] matrix = new int[rows][cols];

// Input elements
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Print the original matrix


System.out.println("Original Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Print the transpose of the matrix


System.out.println("Transpose Matrix:");
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

scanner.close();
}
}
Exercise 4: Find the Maximum Element in a 2D Array
1. Task: Write a program to find the maximum element in a
user-defined 2D array.
2. Input: The user should provide the dimensions and the
elements of the matrix.

import java.util.Scanner;

public class Exercise4 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input dimensions
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

// Create and initialize the array


int[][] array = new int[rows][cols];

// Input elements
System.out.println("Enter elements of the array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = scanner.nextInt();
}
}

// Find the maximum element


int max = array[0][0];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array[i][j] > max) {
max = array[i][j];
}
}
}

// Print the maximum element


System.out.println("Maximum element in the array: " +
max);

scanner.close();
}
}
Exercise 5: Diagonal Elements of a Square Matrix
1. Task: Write a program that prints the diagonal elements of
a square matrix (same number of rows and columns).
2. Input: The user should provide the size of the matrix and
its elements.

import java.util.Scanner;

public class Exercise5 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input dimensions
System.out.print("Enter the size of the square matrix: ");
int size = scanner.nextInt();

// Create and initialize the array


int[][] matrix = new int[size][size];

// Input elements
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Print diagonal elements


System.out.println("Diagonal elements:");
for (int i = 0; i < size; i++) {
System.out.print(matrix[i][i] + " "); // Primary diagonal
}
System.out.println(); // Move to next line

System.out.println("Secondary diagonal elements:");


for (int i = 0; i < size; i++) {
System.out.print(matrix[i][size - 1 - i] + " "); //
Secondary diagonal
}

scanner.close();
}
}
Additional Practice:
Feel free to modify the above exercises or create new ones based
on the following concepts:
 Implementing matrix addition and subtraction.
 Rotating a matrix (90 degrees).
 Checking if a matrix is symmetric.
 Flattening a 2D array into a 1D array.

8. String Handling.
String Handling in Java
In Java, strings are sequences of characters that are treated as
objects of the String class. Strings are immutable, meaning their
values cannot be changed once they are created. Java provides a
wide range of methods and techniques for string handling and
manipulation.
Declaring and Initializing Strings
1. Using String Literal:
String str = "Hello, World!";
Java optimizes the memory for string literals using a string
pool, which avoids creating duplicate string objects.
2. Using new Keyword:
String str = new String("Hello, World!");
Common String Methods
Java provides many useful methods for string handling:
1. Length of String (length()):
String str = "Hello";
int len = str.length(); // Output: 5
2. Concatenating Strings (concat() or + operator):
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(" ").concat(str2); // Output: "Hello
World"
// Or using the + operator
String result2 = str1 + " " + str2; // Output: "Hello World"
3. Character at Specific Index (charAt()):
String str = "Hello";
char ch = str.charAt(1); // Output: 'e'
4. Substring Extraction (substring()):
String str = "Hello, World!";
String sub = str.substring(7); // Output: "World!"
String sub2 = str.substring(7, 12); // Output: "World"
5. String Comparison (equals() and equalsIgnoreCase()):
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // Output: false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); //
Output: true
6. Converting to Uppercase and Lowercase:

String str = "Hello";


String upper = str.toUpperCase(); // Output: "HELLO"
String lower = str.toLowerCase(); // Output: "hello"
7. String Replacement (replace()):
String str = "Hello, World!";
String replaced = str.replace('l', 'x'); // Output: "Hexxo, Worxd!"
String replacedWord = str.replace("World", "Java"); // Output:
"Hello, Java!"
8. Trim Leading and Trailing Whitespaces (trim()):
String str = " Hello ";
String trimmed = str.trim(); // Output: "Hello"
9. Splitting a String (split()):
String str = "Java,Python,C++";
String[] languages = str.split(","); // Output: ["Java", "Python",
"C++"]
10. Checking if a String Starts or Ends with a Specific
Substring:
o startsWith():
String str = "Hello, World!";
boolean starts = str.startsWith("Hello"); // Output: true
o endsWith():
boolean ends = str.endsWith("World!"); // Output: true
11. Finding the Index of a Character or Substring
(indexOf()):

String str = "Hello, World!";


int index = str.indexOf('W'); // Output: 7
int indexSub = str.indexOf("World"); // Output: 7
int notFound = str.indexOf("Java"); // Output: -1 (substring not
found)
12. Converting String to a Character Array
(toCharArray()):

String str = "Hello";


char[] charArray = str.toCharArray(); // Output: ['H', 'e', 'l', 'l',
'o']
Example: Common String Operations
public class StringExample {
public static void main(String[] args) {
// Declare and initialize a string
String str = "Hello, World!";

// Print the length of the string


System.out.println("Length: " + str.length()); // Output: 13

// Extract a substring
String sub = str.substring(7);
System.out.println("Substring: " + sub); // Output:
"World!"

// Convert to uppercase
String upper = str.toUpperCase();
System.out.println("Uppercase: " + upper); // Output:
"HELLO, WORLD!"

// Replace a substring
String replaced = str.replace("World", "Java");
System.out.println("Replaced: " + replaced); // Output:
"Hello, Java!"
// Split the string
String[] words = str.split(", ");
System.out.println("Split: " + words[0] + " and " +
words[1]); // Output: "Hello and World!"
}
}
Mutable Strings: StringBuilder and StringBuffer
Since Java's String is immutable, every time you perform an
operation (like concatenation or replace), a new String object is
created. For more efficient string manipulation, especially when
you need to modify the string multiple times, use StringBuilder
or StringBuffer.
1. StringBuilder: Used for mutable strings.

StringBuilder sb = new StringBuilder("Hello");


sb.append(", World!");
System.out.println(sb.toString()); // Output: "Hello, World!"
2. StringBuffer: Similar to StringBuilder but is thread-safe
(synchronized).

StringBuffer sb = new StringBuffer("Hello");


sb.append(", World!");
System.out.println(sb.toString()); // Output: "Hello, World!"
Example: Using StringBuilder for Efficient String
Concatenation
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" is").append(" fun!");
System.out.println(sb.toString()); // Output: "Java is fun!"

// Inserting a string at a specific index


sb.insert(5, " programming");
System.out.println(sb.toString()); // Output: "Java
programming is fun!"

// Reversing the string


sb.reverse();
System.out.println("Reversed: " + sb.toString()); // Output:
"!nuf si gnimmargorp avaJ"
}
}
String Handling Exercise
1. Task: Write a Java program to check if two strings are
anagrams (contain the same characters in any order).
2. Task: Write a program that takes a string input from the
user and counts the number of vowels, consonants, digits,
and special characters.
3. Task: Write a program that reverses a given string without
using the built-in reverse() function.
4. Task: Write a program to check if a string is a palindrome
(reads the same forward and backward).
Exercise 1: Check if Two Strings are Anagrams
import java.util.Arrays;

public class AnagramCheck {


public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";

// Convert both strings to lowercase and sort the characters


char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();

Arrays.sort(arr1);
Arrays.sort(arr2);
// Check if sorted arrays are equal
if (Arrays.equals(arr1, arr2)) {
System.out.println(str1 + " and " + str2 + " are
anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not
anagrams.");
}
}
}
Exercise 2: Count Vowels, Consonants, Digits, and Special
Characters
import java.util.Scanner;

public class StringCharacterCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

int vowels = 0, consonants = 0, digits = 0, specialChars = 0;


// Convert the string to lowercase for easier comparison
input = input.toLowerCase();

// Iterate through each character


for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);

if (ch >= 'a' && ch <= 'z') { // Check for letters


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
vowels++;
} else {
consonants++;
}
} else if (ch >= '0' && ch <= '9') { // Check for digits
digits++;
} else { // Special characters
specialChars++;
}
}

System.out.println("Vowels: " + vowels);


System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("Special characters: " + specialChars);
}
}
These examples and exercises cover the basics and some
intermediate-level string handling tasks in Java. Would you like
help with any specific string operation or more advanced topics?

String class:

The String Class in Java


The String class in Java is part of the java.lang package and
represents a sequence of characters. Strings are one of the most
commonly used data types in Java, and the String class provides
many methods for manipulating and handling strings.
Key Features of the String Class
1. Immutability: Strings in Java are immutable, which means
once a String object is created, its value cannot be changed.
Any operation that seems to modify a string (e.g.,
concatenation) creates a new String object rather than
modifying the original.
String str = "Hello";
str = str.concat(" World"); // Creates a new String "Hello World"
2. String Pool: Java maintains a pool of strings in memory
(called the string pool). When a string literal is created,
Java first checks if the value already exists in the pool. If it
does, a reference to the existing string is returned; if not, a
new string is added to the pool.
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // Output: true (both reference the
same object in the pool)
3. Unicode Support: Java strings support Unicode, meaning
they can represent text in any language.
Creating a String
1. Using a String Literal:
String str = "Hello";
2. Using the new Keyword:
String str = new String("Hello");
Commonly Used String Methods
1. length(): Returns the length of the string (number of
characters).
String str = "Hello";
int len = str.length(); // Output: 5
2. charAt(int index): Returns the character at the specified
index (0-based).
char ch = str.charAt(1); // Output: 'e'
3. substring(int beginIndex, int endIndex): Returns a
substring of the string, from beginIndex to endIndex - 1.
String sub = str.substring(1, 4); // Output: "ell"
4. equals(Object anotherString): Compares two strings for
equality.
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // Output: true
5. equalsIgnoreCase(String anotherString): Compares two
strings for equality, ignoring case.
String str1 = "HELLO";
String str2 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); //
Output: true
6. toLowerCase() and toUpperCase(): Converts the string to
lowercase or uppercase.
String lower = str.toLowerCase(); // Output: "hello"
String upper = str.toUpperCase(); // Output: "HELLO"
7. indexOf(char ch): Returns the index of the first occurrence
of the specified character.
int index = str.indexOf('l'); // Output: 2
8. replace(char oldChar, char newChar): Replaces all
occurrences of a character with another character.
String replaced = str.replace('l', 'x'); // Output: "Hexxo"
9. trim(): Removes leading and trailing whitespace.
String str = " Hello ";
String trimmed = str.trim(); // Output: "Hello"
10. split(String regex): Splits the string based on a
regular expression.
String str = "Hello World";
String[] words = str.split(" "); // Output: ["Hello", "World"]
String Comparison
1. equals(): Compares strings for content equality.
String str1 = "Hello";
String str2 = "Hello";
boolean result = str1.equals(str2); // Output: true
2. compareTo(): Compares two strings lexicographically.
Returns:
o 0 if the strings are equal.
o A negative number if the calling string is
lexicographically smaller.
o A positive number if the calling string is
lexicographically larger.
String str1 = "Apple";
String str2 = "Banana";
int result = str1.compareTo(str2); // Output: -1 (Apple comes
before Banana)
3. equalsIgnoreCase(): Compares two strings ignoring case.
String str1 = "HELLO";
String str2 = "hello";
boolean result = str1.equalsIgnoreCase(str2); // Output: true
String Interning
The intern() method in Java ensures that strings are stored in the
string pool. If the string already exists in the pool, it returns the
reference to the existing string. Otherwise, it adds the string to
the pool.
String str1 = new String("Hello");
String str2 = str1.intern();
String str3 = "Hello";
System.out.println(str2 == str3); // Output: true (both refer to the
string in the pool)
Example of String Manipulation
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";

// Length of the string


System.out.println("Length: " + str.length()); // Output: 16

// Character at a specific index


System.out.println("Character at index 5: " + str.charAt(5));
// Output: 'P'

// Substring from index 5 to 11


System.out.println("Substring: " + str.substring(5, 11)); //
Output: "Progra"

// Convert to uppercase
System.out.println("Uppercase: " + str.toUpperCase()); //
Output: "JAVA PROGRAMMING"

// Replace 'a' with 'x'


System.out.println("Replaced: " + str.replace('a', 'x')); //
Output: "Jxvx Progrxmming"

// Check if strings are equal


String anotherStr = "Java Programming";
System.out.println("Equal: " + str.equals(anotherStr)); //
Output: true

// Split the string into words


String[] words = str.split(" ");
for (String word : words) {
System.out.println(word); // Output: "Java"
"Programming"
}
}
}
String Immutability
Because strings are immutable, operations like concatenation or
modification always result in a new String object being created.
This behavior is both a strength and a limitation:
 Strength: Immutable strings are thread-safe since they
cannot be modified once created.
 Limitation: String concatenation in loops can lead to
performance overhead because new string objects are
created repeatedly.
For efficient string manipulation, especially in cases involving
multiple modifications, you should use StringBuilder or
StringBuffer.
StringBuilder vs StringBuffer
 StringBuilder: Provides a mutable sequence of characters
and is faster, but not thread-safe.
 StringBuffer: Similar to StringBuilder, but thread-safe
(synchronized).
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World!");
System.out.println(sb.toString()); // Output: "Hello World!"
String Handling Exercises
1. Exercise 1: Write a program to count the number of vowels
in a string.
2. Exercise 2: Write a program to check if two strings are
anagrams.
3. Exercise 3: Write a program to reverse a string without
using built-in methods.
4. Exercise 4: Write a program to remove duplicate characters
from a string.
Exercise Example: Count Vowels

public class CountVowels {


public static void main(String[] args) {
String str = "Hello World!";
int vowelCount = 0;
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i));
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}

System.out.println("Number of vowels: " + vowelCount); //


Output: 3
}
}
The String class in Java is a powerful and flexible tool for text
manipulation, and mastering it is essential for effective Java
programming. Would you like further examples or details on a
specific part of the String class?

Creating a String
In Java, creating a String can be done in several ways. Below are
the primary methods for creating a String object.
1. Using a String Literal
When a string is created using a string literal, it is automatically
stored in the string pool. If the same literal is used elsewhere in
the program, Java will reuse the string from the pool rather than
creating a new object.

String str = "Hello, World!";


In this case:
 Java checks the string pool for the value "Hello, World!".
 If the string exists in the pool, it returns a reference to the
existing string.
 If not, a new string is created and added to the pool.
2. Using the new Keyword
When a string is created using the new keyword, a new object is
explicitly created in memory, even if the string with the same
value already exists in the string pool.

String str = new String("Hello, World!");


In this case:
 A new string object is created on the heap, independent of
the string pool.
 This is less efficient in terms of memory usage compared to
using string literals.
Example: Literal vs new Keyword

public class StringExample {


public static void main(String[] args) {
// String using literal
String str1 = "Hello";
String str2 = "Hello";

// String using new keyword


String str3 = new String("Hello");

// Check references for literal strings (should be true)


System.out.println(str1 == str2); // Output: true

// Check references for literal and new keyword strings


(should be false)
System.out.println(str1 == str3); // Output: false

// Check content equality (should be true)


System.out.println(str1.equals(str3)); // Output: true
}
}
3. Using a char[] Array
A String can also be created from a character array (char[]). This
is useful if you have individual characters that need to be
combined into a single string.

char[] charArray = {'H', 'e', 'l', 'l', 'o'};


String str = new String(charArray); // Output: "Hello"
4. Using String.valueOf()
You can use the static method String.valueOf() to convert other
data types (like integers, characters, etc.) into a string.

int number = 123;


String str = String.valueOf(number); // Output: "123"
This method works for different types like char[], int, double,
boolean, etc.
Example: Creating Strings from Different Sources
public class StringCreation {
public static void main(String[] args) {
// Using a string literal
String str1 = "Hello";

// Using the new keyword


String str2 = new String("World");
// Using a character array
char[] charArray = {'J', 'a', 'v', 'a'};
String str3 = new String(charArray);

// Using valueOf() to convert an int to string


int num = 100;
String str4 = String.valueOf(num);

// Output strings
System.out.println(str1); // Output: Hello
System.out.println(str2); // Output: World
System.out.println(str3); // Output: Java
System.out.println(str4); // Output: 100
}
}
Summary of Methods for Creating Strings
1. String literal:
String str = "Hello";
2. new keyword:
String str = new String("Hello");
3. Character array (char[]):
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str = new String(chars);
4. String.valueOf():
int num = 123;
String str = String.valueOf(num);
Each method has its use case, but using string literals is
generally more memory-efficient because of string interning,
which avoids creating duplicate string objects.

Methods of String Class:


The String class in Java provides numerous methods for
working with and manipulating strings. Below are some of the
most commonly used methods in the String class:
1. charAt(int index)
 Returns the character at the specified index.
 Example:
String str = "Hello";
char ch = str.charAt(1); // 'e'
2. length()
 Returns the length of the string.
 Example:
String str = "Hello";
int len = str.length(); // 5
3. substring(int beginIndex)
 Returns a new string that is a substring starting from the
specified index.
 Example:
String str = "Hello";
String sub = str.substring(2); // "llo"
4. substring(int beginIndex, int endIndex)
 Returns a new string that is a substring from beginIndex to
endIndex (excluding the endIndex).
 Example:
String str = "Hello";
String sub = str.substring(1, 4); // "ell"
5. contains(CharSequence s)
 Returns true if the string contains the specified sequence of
characters.
 Example:
String str = "Hello";
boolean contains = str.contains("ell"); // true
6. equals(Object anotherObject)
 Compares the string with another object for equality.
 Example:
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // true
7. equalsIgnoreCase(String anotherString)
 Compares two strings, ignoring case differences.
 Example:
String str1 = "hello";
String str2 = "HELLO";
boolean isEqual = str1.equalsIgnoreCase(str2); // true
8. toUpperCase()
 Converts all characters in the string to uppercase.
 Example:
String str = "hello";
String upper = str.toUpperCase(); // "HELLO"
9. toLowerCase()
 Converts all characters in the string to lowercase.
 Example:
String str = "HELLO";
String lower = str.toLowerCase(); // "hello"
10. trim()
 Removes leading and trailing whitespace.
 Example:
String str = " Hello ";
String trimmed = str.trim(); // "Hello"
11. replace(CharSequence target, CharSequence
replacement)
 Replaces each substring that matches the target with the
replacement.
 Example:
String str = "Hello World";
String replaced = str.replace("World", "Java"); // "Hello Java"
12. split(String regex)
 Splits the string around matches of the regular expression
and returns an array of strings.
 Example:
String str = "apple,banana,cherry";
String[] fruits = str.split(","); // ["apple", "banana", "cherry"]
13. indexOf(String str)
 Returns the index of the first occurrence of the specified
substring.
 Example:
String str = "Hello World";
int index = str.indexOf("World"); // 6
14. lastIndexOf(String str)
 Returns the index of the last occurrence of the specified
substring.
 Example:
String str = "Hello World World";
int index = str.lastIndexOf("World"); // 12
15. startsWith(String prefix)
 Checks if the string starts with the specified prefix.
 Example:
String str = "Hello World";
boolean starts = str.startsWith("Hello"); // true
16. endsWith(String suffix)
 Checks if the string ends with the specified suffix.
 Example:
String str = "Hello World";
boolean ends = str.endsWith("World"); // true
17. isEmpty()
 Checks if the string is empty (i.e., length is 0).
 Example:
String str = "";
boolean empty = str.isEmpty(); // true
18. join(CharSequence delimiter, CharSequence... elements)
 Joins elements with a specified delimiter into a single
string.
 Example:
String result = String.join("-", "apple", "banana", "cherry");
// "apple-banana-cherry"
19. compareTo(String anotherString)
 Compares two strings lexicographically.
 Example:
String str1 = "apple";
String str2 = "banana";
int comparison = str1.compareTo(str2); // negative because
"apple" is lexicographically smaller
20. format(String format, Object... args)
 Returns a formatted string using the specified format string
and arguments.
 Example:
String formatted = String.format("My name is %s and I am %d
years old.", "John", 25);
// "My name is John and I am 25 years old."
These are some of the most frequently used methods from the
String class. They cover basic operations such as substring
extraction, comparison, modification, and searching.

String Array:
In Java, a String Array is an array that holds
multiple String values. It can be used to store a collection of
strings and can be accessed by an index. The size of the array is
fixed once it is created, and each element in the array is
initialized to null by default if not explicitly assigned.
Declaring and Initializing a String Array
1. Declaration Without Initialization: You can declare a
string array with a specific size but not assign any values
initially.

String[] arr = new String[5]; // Array of size 5


2. Declaration and Initialization at the Same Time: You
can also declare and initialize the array in one line.

String[] arr = {"Apple", "Banana", "Cherry"};


3. Declaring and Assigning Later: You can declare the array
and assign values to each element later.
String[] arr = new String[3]; arr[0] = "Apple"; arr[1] =
"Banana"; arr[2] = "Cherry";
Accessing Elements in a String Array
You can access an element of the array by using its index
(starting from 0).
String[] fruits = {"Apple", "Banana", "Cherry"}; String firstFruit
= fruits[0]; // "Apple" String secondFruit = fruits[1]; // "Banana"
Modifying Elements in a String Array
You can change the value of an element by specifying its index.
String[] fruits = {"Apple", "Banana", "Cherry"}; fruits[1] =
"Orange"; // Change "Banana" to "Orange"
Iterating Over a String Array
1. Using a for loop:
String[] fruits = {"Apple", "Banana", "Cherry"}; for (int i = 0; i
< fruits.length; i++) { System.out.println(fruits[i]); }
2. Using a foreach loop:
String[] fruits = {"Apple", "Banana", "Cherry"}; for (String fruit
: fruits) { System.out.println(fruit); }
Common Operations on String Arrays
1. Find the Length of the Array: Use the .length property to
get the number of elements in the array.
String[] fruits = {"Apple", "Banana", "Cherry"}; int length =
fruits.length; // 3
2. Sorting a String Array: You can sort a string array
using Arrays.sort() from the java.util package.
import java.util.Arrays; String[] fruits = {"Banana", "Apple",
"Cherry"}; Arrays.sort(fruits); // Now the array is sorted:
{"Apple", "Banana", "Cherry"}
3. Converting a String Array to a List: You can convert a
string array to a list using Arrays.asList().
import java.util.Arrays;
import java.util.List;
String[] fruits = {"Apple", "Banana", "Cherry"};
List<String> fruitList = Arrays.asList(fruits);
Example: Working with a String Array
Here's a full example demonstrating how to declare, initialize,
access, and modify a string array.
public class Main { public static void main(String[] args) { //
Declare and initialize a string array String[] fruits = {"Apple",
"Banana", "Cherry"}; // Access elements
System.out.println("First fruit: " + fruits[0]); // Output: Apple //
Modify an element fruits[1] = "Orange";
System.out.println("Modified second fruit: " + fruits[1]); //
Output: Orange // Iterate over the array System.out.println("All
fruits:"); for (String fruit : fruits) { System.out.println(fruit); } //
Find the length of the array System.out.println("Number of
fruits: " + fruits.length); // Output: 3 // Sort the array
Arrays.sort(fruits); System.out.println("Sorted fruits:"); for
(String fruit : fruits) { System.out.println(fruit); } } }
Key Points:
 A string array can hold multiple String values.
 The size of an array is fixed upon creation.
 Arrays are 0-indexed, meaning the first element is at index
0.
 Arrays can be iterated using loops, and common operations
like sorting and accessing the length can be easily done.

Exercises:
Here are some exercises on String Arrays in Java. Each
exercise comes with a brief description and hints to guide you
through solving it.
Exercise 1: Declare and Print a String Array
 Task: Declare a string array with five different country
names and print each country name using a loop.
 Hint: Use a for loop or a foreach loop to iterate over the
array.
java
Copy code
public class Main { public static void main(String[] args) { //
Declare and initialize a string array with country names String[]
countries = {"USA", "India", "Canada", "Brazil",
"Australia"}; // Print each country using a loop for (String
country : countries) { System.out.println(country); } } }
Exercise 2: Find the Longest String in an Array
 Task: Given an array of string values, write a program that
finds and prints the longest string in the array.
 Hint: Compare the length of each string using
the length() method and store the longest one.
java
Copy code
public class Main { public static void main(String[] args)
{ String[] words = {"apple", "banana", "watermelon", "cherry"};
String longest = words[0]; for (String word : words) { if
(word.length() > longest.length()) { longest = word; } }
System.out.println("Longest word: " + longest); } }
Exercise 3: Reverse a String Array
 Task: Write a program that reverses the elements of a
string array.
 Hint: Swap elements from the start and end, moving
toward the center of the array.
public class Main { public static void main(String[] args)
{ String[] fruits = {"Apple", "Banana", "Cherry", "Date",
"Elderberry"}; // Reverse the array for (int i = 0; i < fruits.length
/ 2; i++) { String temp = fruits[i]; fruits[i] = fruits[fruits.length -
i - 1]; fruits[fruits.length - i - 1] = temp; } // Print the reversed
array for (String fruit : fruits) { System.out.println(fruit); } } }
Exercise 4: Count Occurrences of a String
 Task: Write a program that counts how many times a
specific string (e.g., "apple") appears in a string array.
 Hint: Loop through the array and compare each element
with the target string.
public class Main { public static void main(String[] args)
{ String[] fruits = {"apple", "banana", "apple", "cherry",
"apple"}; String target = "apple"; int count = 0; // Count
occurrences of "apple" for (String fruit : fruits) { if
(fruit.equals(target)) { count++; } } System.out.println(target + "
appears " + count + " times."); } }
Exercise 5: Sort a String Array Alphabetically
 Task: Write a program that sorts a string array of names
alphabetically.
 Hint: Use Arrays.sort() from the java.util package.
import java.util.Arrays; public class Main { public static void
main(String[] args) { String[] names = {"John", "Alice", "Bob",
"Catherine"}; // Sort the array alphabetically
Arrays.sort(names); // Print the sorted array for (String name :
names) { System.out.println(name); } } }
Exercise 6: Convert a String Array to Uppercase
 Task: Write a program that converts all strings in a string
array to uppercase.
 Hint: Use the toUpperCase() method for each string in the
array.
public class Main { public static void main(String[] args)
{ String[] colors = {"red", "blue", "green", "yellow"}; // Convert
each string to uppercase for (int i = 0; i < colors.length; i++)
{ colors[i] = colors[i].toUpperCase(); } // Print the uppercase
strings for (String color : colors) { System.out.println(color); } }
}
Exercise 7: Concatenate String Array Elements
 Task: Write a program that concatenates all elements of a
string array into a single string, with spaces between the
elements.
 Hint: Use a StringBuilder or simply append strings with a
space in between.
public class Main { public static void main(String[] args)
{ String[] words = {"Hello", "world", "Java", "is", "awesome"};
String result = ""; for (String word : words) { result += word + "
"; } // Remove trailing space and print the concatenated string
System.out.println(result.trim()); } }
Exercise 8: Check for a Palindrome in an Array
 Task: Write a program to check if a string array contains a
palindrome (a word that reads the same forward and
backward).
 Hint: Compare each string with its reversed version.
public class Main { public static void main(String[] args)
{ String[] words = {"madam", "apple", "level", "banana"}; for
(String word : words) { if (isPalindrome(word))
{ System.out.println(word + " is a palindrome."); } } } // Helper
method to check if a string is a palindrome public static boolean
isPalindrome(String word) { int n = word.length(); for (int i = 0;
i < n / 2; i++) { if (word.charAt(i) != word.charAt(n - i - 1))
{ return false; } } return true; } }
Exercise 9: Find the Index of a String
 Task: Write a program that searches for a specific string in
an array and prints its index. If the string is not found, print
a message indicating so.
 Hint: Use a loop to compare each element with the target
string.
public class Main { public static void main(String[] args)
{ String[] animals = {"cat", "dog", "elephant", "tiger", "lion"};
String target = "tiger"; int index = -1; for (int i = 0; i <
animals.length; i++) { if (animals[i].equals(target)) { index = i;
break; } } if (index != -1) { System.out.println(target + " is
found at index " + index); } else { System.out.println(target + "
is not found in the array."); } } }
Exercise 10: Find Duplicate Strings in an Array
 Task: Write a program that finds and prints duplicate
strings in an array.
 Hint: Use nested loops to compare each string with the
others.
 public class Main { public static void main(String[] args)
{ String[] names = {"John", "Alice", "Bob", "Alice",
"John"}; for (int i = 0; i < names.length; i++) { for (int j = i
+ 1; j < names.length; j++) { if (names[i].equals(names[j]))
{ System.out.println("Duplicate found: " +
names[i]); } } } } }
These exercises cover various operations and concepts related to
string arrays in Java, such as iteration, searching, sorting, and
modifying elements.

You might also like