Concepts of Classes and Objects in Java
Concepts of Classes and Objects in Java
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 {
Directory.
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;
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
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.
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:
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:
Benefits:
Example in Java:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
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:
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!");
}
}
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
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
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:
Java Example:
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.
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.
Java Example:
Definition: Reference types refer to objects and arrays. They store references (or memory
addresses) to the actual data rather than the data itself.
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.
1. Arithmetic Operators
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
java
java
oolean result = (5 > 3 || 8 < 6); // true
java
boolean result = !(5 > 3); // false
4. Bitwise Operators
java
int result = 5 & 3; // 1 (binary 0101 & 0011 = 0001)
java
int result = 5 | 3; // 7 (binary 0101 | 0011 = 0111)
java
int result = 5 ^ 3; // 6 (binary 0101 ^ 0011 = 0110)
java
int result = ~5; // -6 (binary ~0101 = 1010)
java
int result = 5 << 1; // 10 (binary 0101 << 1 = 1010)
Unsigned Right Shift (>>>): Shifts bits to the right and fills the leftmost bits with zeros.
java
int result = 5 >>> 1; // 2
5. Assignment Operators
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
java
int x = +5; // 5
java
int x = -5; // -5
java
int x = 5;
x++; // x is now 6
java
int x = 5;
x--; // x is now 4
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.
java
String str = "Hello";
boolean result = str instanceof String; // true
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;
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;
System.out.println(num);
The Random class in Java provides methods for generating random numbers. Here are
some of the most commonly used methods:
The BigInteger and BigDecimal classes in Java provide support for arbitrary-precision
arithmetic. Here are some of the most commonly used methods:
import java.math.BigDecimal;
This code creates two BigDecimal objects, performs arithmetic operations using
the add, subtract, multiply, and divide methods, and prints the results to the
console.
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:
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
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!
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:
Syntax:
while (condition) {
// code to be executed
}
Example:
Syntax:
// code to be executed
Example:
1. Break Statement
The break statement is used to exit a loop or a switch statement.
Syntax:
break;
Example:
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;
}
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:
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.
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.
int[] arr = {10, 20, 30, 40, 50}; // Declare and initialize the array
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:
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;
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:
import java.util.Arrays;
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
Bubble sorting:
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:
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.
import java.util.Scanner;
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.
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();
// 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];
}
}
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();
// 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();
}
}
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;
// 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();
// 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();
}
}
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;
// Input dimensions
System.out.print("Enter the size of the square matrix: ");
int size = scanner.nextInt();
// 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();
}
}
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:
// 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.
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;
String class:
// Convert to uppercase
System.out.println("Uppercase: " + str.toUpperCase()); //
Output: "JAVA PROGRAMMING"
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.
// 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.
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.
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.