SlideShare a Scribd company logo
Arrays in Java
An array is a data structure that can hold multiple values of the same type. It's useful when you need to
store a collection of data, but you don't want to create a variable for each element.
Creating an Array
To create an array in Java, you need to:
1. Declare the array.
2. Instantiate the array.
3. Initialize the array elements.
Example:
// Step 1: Declare an array
Datatype arrayname[];
Datatype[] arrayname;
int[] myArray;
int rollno[];
// Step 2: Instantiate the array(Creation of Memory location)
Arrayname= new datatype[size];
Rollno= new int[30];
Name = new char[30];
myArray = new int[5];
// Step 3: Initialize the array elements
myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
myArray[3] = 40;
myArray[4] = 50;
You can also combine the declaration, instantiation, and initialization in one line
int[] myArray = {10, 20, 30, 40, 50};
int myArray[]={10,20,30,40,50};
Types of Arrays
1. One-Dimensional Arrays A one-dimensional array is a list of elements of the same type. It's the
simplest form of an array.
Example:
int[] numbers = {1, 2, 3, 4, 5};
int number[]={1,2,3,4,5}
2. Two-Dimensional Arrays A two-dimensional array is an array of arrays, creating a matrix-like
structure.
Example:
// Declare a 2D array
int[][] matrix = new int[3][3];
// Initialize the 2D array
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
You can also initialize a 2D array directly:
1
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Strings in Java
Strings in Java are objects that represent sequences of characters. The String class is used to create and
manipulate strings.
Creating a String
You can create a string in several ways:
1. Using string literals:
String str1 = "Hello, World!";
2. Using the new keyword:
String str2 = new String("Hello, World!");
Common String Methods
The String class provides many methods for string manipulation. Here are some commonly used ones:
 length(): Returns the length of the string.
int length = str1.length();
 charAt(int index): Returns the character at the specified index.
char ch = str1.charAt(0); // 'H'
 substring(int beginIndex, int endIndex): Returns a substring from the specified start index to the
end index.
String sub = str1.substring(0, 5); // "Hello"
 contains(CharSequence s): Checks if the string contains the specified sequence of characters.
boolean contains = str1.contains("World"); // true
 replace(CharSequence target, CharSequence replacement): Replaces each occurrence of the
specified sequence with another sequence
String replaced = str1.replace("World", "Java"); // "Hello, Java!"
StringBuffer Class
The StringBuffer class is used to create mutable strings. Unlike String, which is immutable, StringBuffer
allows modification of strings without creating new objects.
Creating a StringBuffer:
StringBuffer sb = new StringBuffer("Hello");
Common Methods of StringBuffer:
 append(String str): Appends the specified string to this character sequence.
sb.append(", World!"); // "Hello, World!"
 insert(int offset, String str): Inserts the specified string at the specified position.
sb.insert(5, " Java"); // "Hello Java, World!"
 replace(int start, int end, String str): Replaces the characters in a substring of this sequence with
characters in the specified string.
sb.replace(6, 10, "Earth"); // "Hello Earth, World!"
 delete(int start, int end): Removes the characters in a substring of this sequence.
sb.delete(5, 11); // "Hello World!"
 reverse(): Reverses the sequence of characters.
sb.reverse(); // "!dlroW ,olleH"
Summary
 Arrays are used to store multiple values of the same type and can be one-dimensional or two-
dimensional.
2
 Strings are immutable objects used to represent sequences of characters, with many built-in
methods for manipulation.
 StringBuffer is a mutable sequence of characters, allowing in-place modification of the string.
Understanding these fundamental concepts and their respective methods is crucial for effective Java
programming.
X-X-X-X-X-X-X-X-X-X
Arrays in Java
An array is a container object that holds a fixed number of values of a single type. The length of an array
is established when the array is created. After creation, its length is fixed.
Types of Arrays
1. One-Dimensional Arrays
2. Two-Dimensional Arrays
3. One-Dimensional Arrays
A one-dimensional array is like a list of elements. It is the simplest form of an array.
Example and Explanation:
public class OneDimensionalArrayExample
{
public static void main(String[] args)
{
// Declare an array of integers
int[] array = new int[5];
// Initialize the array with values
array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;
// Print the elements of the array
for (int i = 0; i < array.length; i++) {
System.out.println("Element at index " + i + ": " + array[i]);
}
}
}
Explanation:
 int[] array = new int[5]; declares an array of integers with a size of 5.
 array[0] = 10; initializes the first element of the array with the value 10.
 A for loop is used to iterate through the array and print each element.
2. Two-Dimensional Arrays
A two-dimensional array is like a table with rows and columns. It is often used to represent a matrix.
Example and Explanation:
public class TwoDimensionalArrayExample
{
public static void main(String[] args)
{
// Declare a 2D array of integers
int[][] array = new int[3][3];
// Initialize the 2D array with values
int value = 1;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
3
array[i][j] = value++;
}
}
// Print the elements of the 2D array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // Print a new line after each row
}
}
}
Explanation:
 int[][] array = new int[3][3]; declares a 2D array of integers with 3 rows and 3 columns.
 Nested for loops are used to initialize the array with values starting from 1.
 Another set of nested for loops is used to print the elements of the 2D array, displaying the array
as a matrix.
X-X-X-X-X-X-X-X-X-X-X
Example 1: Initialize and Print Array Elements
public class Main {
public static void main(String[] args) {
// Declare and initialize an array of 5 integers
int[] array = {10, 20, 30, 40, 50};
// Print the elements of the array
System.out.println("Elements of the array are:");
for (int i = 0; i < array.length; i++) {
System.out.println("array[" + i + "] = " + array[i]);
}
}
}
Output
Elements of the array are:
array[0] = 10
array[1] = 20
array[2] = 30
array[3] = 40
array[4] = 50
Example 2: Find the Sum of Array Elements
public class Main {
public static void main(String[] args) {
// Declare and initialize an array of 5 integers
int[] array = {10, 20, 30, 40, 50};
// Calculate the sum of the elements of the array
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
// Print the sum of the elements
4
System.out.println("Sum of the array elements is: " + sum);
}
}
Output
Sum of the array elements is: 150
Example 3: Find the Maximum Element in an Array
public class Main {
public static void main(String[] args) {
// Declare and initialize an array of 5 integers
int[] array = {10, 20, 30, 40, 50};
// Find the maximum element in the array
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
// Print the maximum element
System.out.println("Maximum element in the array is: " + max);
}
}
Output
Maximum element in the array is: 50
Example 4: Reverse the Elements of an Array
public class Main {
public static void main(String[] args) {
// Declare and initialize an array of 5 integers
int[] array = {10, 20, 30, 40, 50};
// Reverse the elements of the array
int n = array.length;
for (int i = 0; i < n / 2; i++) {
int temp = array[i];
array[i] = array[n - 1 - i];
array[n - 1 - i] = temp;
}
// Print the reversed array
System.out.println("Reversed array elements are:");
for (int i = 0; i < array.length; i++) {
System.out.println("array[" + i + "] = " + array[i]);
}
}
}
Output
Reversed array elements are:
array[0] = 50
array[1] = 40
array[2] = 30
array[3] = 20
5
array[4] = 10
X-X-X-X-X-X-X-X-X-X-X
Example 1: Initialize and Print 2D Array Elements
public class Main {
public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print the elements of the 2D array
System.out.println("Elements of the 2D array are:");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
Output
Elements of the 2D array are:
1 2 3
4 5 6
7 8 9
Example 2: Sum of All Elements in a 2D Array
public class Main {
public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Calculate the sum of all elements in the 2D array
int sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
}
// Print the sum of all elements
System.out.println("Sum of all elements in the 2D array is: " + sum);
}
}
Output
Sum of all elements in the 2D array is: 45
6
Example 3: Transpose of a 2D Array
public class Main {
public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Transpose the 2D array
int[][] transpose = new int[array[0].length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
transpose[j][i] = array[i][j];
}
}
// Print the transposed array
System.out.println("Transpose of the 2D array is:");
for (int i = 0; i < transpose.length; i++) {
for (int j = 0; j < transpose[i].length; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}
Output
Transpose of the 2D array is:
1 4 7
2 5 8
3 6 9
Example 4: Multiplication of Two 2D Arrays
public class Main {
public static void main(String[] args) {
// Declare and initialize two 2D arrays
int[][] array1 = {
{1, 2, 3},
{4, 5, 6}
};
int[][] array2 = {
{7, 8},
{9, 10},
{11, 12}
};
// Multiply the two 2D arrays
int[][] product = new int[array1.length][array2[0].length];
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2[0].length; j++) {
for (int k = 0; k < array1[0].length; k++) {
7
product[i][j] += array1[i][k] * array2[k][j];
}
}
}
// Print the product of the two arrays
System.out.println("Product of the two 2D arrays is:");
for (int i = 0; i < product.length; i++) {
for (int j = 0; j < product[i].length; j++) {
System.out.print(product[i][j] + " ");
}
System.out.println();
}
}
}
Output
Product of the two 2D arrays is:
58 64
139 154
X-X-X-X-X-X-X-X-X-X-X
Array Length:
In Java, the length of an array is determined using the length property. Here's a simple explanation and an
example demonstrating how to get the length of both 1D and 2D arrays.
Example: Getting the Length of 1D and 2D Arrays
public class Main {
public static void main(String[] args) {
// Declare and initialize a 1D array
int[] oneDArray = {1, 2, 3, 4, 5};
// Get and print the length of the 1D array
System.out.println("Length of the 1D array: " + oneDArray.length);
// Declare and initialize a 2D array
int[][] twoDArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Get and print the number of rows in the 2D array
System.out.println("Number of rows in the 2D array: " + twoDArray.length);
// Get and print the number of columns in each row of the 2D array
for (int i = 0; i < twoDArray.length; i++) {
System.out.println("Number of columns in row " + i + ": " + twoDArray[i].length);
}
}
}
Output
Length of the 1D array: 5
Number of rows in the 2D array: 3
Number of columns in row 0: 3
Number of columns in row 1: 3
Number of columns in row 2: 3
8
Explanation
1. 1D Array Length:
o The length property of the array oneDArray returns the number of elements in the 1D
array.
o oneDArray.length is 5 because the array contains 5 elements.
2. 2D Array Length:
o For a 2D array, length gives the number of rows in the array.
o twoDArray.length is 3 because there are 3 rows in the 2D array.
o To get the number of columns in each row, we use twoDArray[i].length, where i is the
index of the row.
X-X-X-X-X-X-X-X-X-X-X
String Arrays in Java
A string array is an array of objects where each element is a reference to a String object.
Example and Explanation:
public class StringArrayExample {
public static void main (String[] args) {
// Declare and initialize a String array
String[] fruits = {"Apple", "Banana", "Cherry"};
// Print the elements of the String array
for (int i = 0; i < fruits.length; i++) {
System.out.println("Element at index " + i + ": " + fruits[i]);
}
}
}
Explanation:
 String[] fruits = {"Apple", "Banana", "Cherry"}; declares and initializes a String array with three
elements.
 A for loop is used to iterate through the array and print each fruit.
Summary
 One-Dimensional Arrays: Simple list of elements, easy to use for basic storage and access.
 Two-Dimensional Arrays: Represented as a table with rows and columns, useful for matrix
operations.
 String Arrays: Array of String objects, useful for storing a list of strings.
Arrays in Java provide a way to store multiple values in a single variable, which can be useful for
handling large amounts of data efficiently.
X-X-X-X-X
Strings in Java
Strings in Java are objects that represent sequences of characters. They are immutable, meaning once a
string is created, it cannot be changed. The String class is used to create and manipulate strings.
Creating Strings
There are several ways to create strings in Java:
1. Using string literals: When a string is created using double quotes, it is stored in the string pool.
2. Using the new keyword: This creates a new string object in the heap.
Examples and Explanations
1. Creating Strings
Example:
public class StringExample {
public static void main(String[] args) {
// Using string literals
9
String str1 = "Hello";
String str2 = "World";
// Using the new keyword
String str3 = new String("Hello");
String str4 = new String("World");
// Printing the strings
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println("str4: " + str4);
}
}
Explanation:
 String str1 = "Hello"; creates a string literal and stores it in the string pool.
 String str3 = new String("Hello"); creates a new string object in the heap.
 System.out.println("str1: " + str1); prints the value of str1.
2. String Methods
The String class provides many methods to manipulate and work with strings.
Example:
public class StringMethodsExample {
public static void main(String[] args) {
String str = "Hello, World!";
// Length of the string
int length = str.length();
System.out.println("Length: " + length);
// Character at a specific index
char charAt2 = str.charAt(2);
System.out.println("Character at index 2: " + charAt2);
// Substring
String substr = str.substring(7, 12);
System.out.println("Substring (7, 12): " + substr);
// Replace
String replacedStr = str.replace("World", "Java");
System.out.println("Replaced: " + replacedStr);
// To Uppercase
String upperStr = str.toUpperCase();
System.out.println("Uppercase: " + upperStr);
// To Lowercase
String lowerStr = str.toLowerCase();
System.out.println("Lowercase: " + lowerStr);
// Trim
String trimmedStr = " Hello ".trim();
System.out.println("Trimmed: '" + trimmedStr + "'");
// Split
String[] splitStr = str.split(", ");
for (String s : splitStr) {
System.out.println("Split: " + s);
}
}
}
10
Explanation:
 str.length() returns the length of the string.
 str.charAt(2) returns the character at index 2.
 str.substring(7, 12) returns the substring from index 7 to 11.
 str.replace("World", "Java") replaces "World" with "Java".
 str.toUpperCase() converts the string to uppercase.
 str.toLowerCase() converts the string to lowercase.
 " Hello ".trim() removes leading and trailing spaces.
 str.split(", ") splits the string by ", " and returns an array of strings.
3. StringBuffer and StringBuilder
While String objects are immutable, StringBuffer and StringBuilder are mutable and can be modified
without creating new objects.
 StringBuffer is thread-safe and synchronized.
 StringBuilder is not thread-safe but faster.
Example:
public class StringBufferExample {
public static void main(String[] args) {
// Using StringBuffer
StringBuffer buffer = new StringBuffer("Hello");
buffer.append(" World");
System.out.println("StringBuffer: " + buffer);
// Using StringBuilder
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World");
System.out.println("StringBuilder: " + builder);
}
}
Explanation:
 StringBuffer buffer = new StringBuffer("Hello"); creates a StringBuffer object.
 buffer.append(" World"); appends " World" to the buffer.
 StringBuilder builder = new StringBuilder("Hello"); creates a StringBuilder object.
 builder.append(" World"); appends " World" to the builder.
Summary
 String: Immutable sequences of characters.
 String methods: Provide various operations like length, charAt, substring, replace, toUpperCase,
toLowerCase, trim, and split.
 StringBuffer and StringBuilder: Mutable sequences of characters, with StringBuffer being
thread-safe and StringBuilder being faster but not thread-safe.
Understanding these concepts and methods allows for effective manipulation and handling of strings in
Java.
X-X-X-X-X-X
StringBuffer Class in Java
The StringBuffer class in Java is used to create mutable (modifiable) string objects. Unlike the String
class, StringBuffer objects can be modified without creating new objects. This class is thread-safe,
meaning it is synchronized and can be used in a multithreaded environment.
Key Features of StringBuffer:
 Mutable: StringBuffer objects can be changed after they are created.
 Thread-safe: Methods of StringBuffer are synchronized, making it safe to use in concurrent
programming.
 Dynamic: The buffer size can grow automatically if needed.
11
Common Methods of StringBuffer:
 append(String s): Appends the specified string to this sequence.
 insert(int offset, String s): Inserts the specified string at the specified position.
 replace(int start, int end, String str): Replaces the characters in a substring of this sequence with
characters in the specified string.
 delete(int start, int end): Removes the characters in a substring of this sequence.
 reverse(): Reverses the sequence of characters.
 toString(): Converts the StringBuffer to a String.
Example and Explanation:
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer object with an initial string
StringBuffer buffer = new StringBuffer("Hello");
// Appending strings
buffer.append(" World");
buffer.append("!");
// Inserting a string at a specific position
buffer.insert(6, "Java ");
// Replacing a part of the string
buffer.replace(6, 10, "Beautiful");
// Deleting a part of the string
buffer.delete(17, 18);
// Reversing the string
buffer.reverse();
// Converting to a string and printing
String result = buffer.toString();
System.out.println("Final string: " + result);
}
}
Explanation:
1. Creating a StringBuffer object:
StringBuffer buffer = new StringBuffer("Hello");
This creates a StringBuffer object with the initial content "Hello".
2. Appending strings:
buffer.append(" World");
buffer.append("!");
The append method is used to add " World" and "!" to the existing string. The buffer now contains "Hello
World!".
3. Inserting a string:
buffer.insert(6, "Java ");
The insert method adds "Java " at position 6. The buffer now contains "Hello Java World!".
4. Replacing a part of the string:
buffer.replace(6, 10, "Beautiful");
The replace method replaces the substring from index 6 to 10 with "Beautiful". The buffer now contains
"Hello Beautiful World!".
5. Deleting a part of the string:
buffer.delete(17, 18);
The delete method removes the character at index 17 (the exclamation mark). The buffer now contains
"Hello Beautiful World".
6. Reversing the string:
12
buffer.reverse();
The reverse method reverses the sequence of characters. The buffer now contains "dlroW lufituaeB
olleH".
7. Converting to a string:
String result = buffer.toString();
System.out.println("Final string: " + result);
The toString method converts the StringBuffer to a String object, which is then printed.
Summary
The StringBuffer class provides a flexible way to manipulate strings in a multithreaded environment due
to its mutability and thread-safety. Understanding and using the various methods provided by
StringBuffer allows for efficient and effective string manipulation in Java.
X-X-X-X-X-X-X-X-X-X-X-X-X-X-X
StringBuffer Class:
The term "string buffer" in computing generally refers to a data structure used to build and manipulate
strings of characters efficiently. Specifically, in Java, StringBuffer is a class that provides methods to
work with strings that can be modified after they are created.
Here's a breakdown of the term "string buffer":
1. String: A sequence of characters, often used to represent text.
2. Buffer: A temporary storage area typically used to hold data while it is being transferred from one
place to another.
Combining these concepts, a string buffer is a buffer that holds a sequence of characters (a string) and
allows for efficient manipulation of this sequence. This includes operations such as appending, inserting,
deleting, and reversing characters in the sequence.
Characteristics of StringBuffer in Java
 Mutable: Unlike String objects, which are immutable (cannot be changed once created),
StringBuffer objects can be modified. This means that operations like appending and inserting
characters do not create new objects but modify the existing one.
 Thread-safe: The methods of StringBuffer are synchronized, which makes it safe to use in a
multithreaded environment without additional synchronization.
Usage
When performing multiple operations on strings, such as concatenation in loops, using a StringBuffer can
be more efficient than using String. This is because modifying a String object repeatedly creates new
objects each time, which can be resource-intensive. In contrast, StringBuffer allows for these
modifications within the same object.
Example
Here's a simple example to illustrate the use of StringBuffer in Java:
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer buffer = new StringBuffer("Hello");
// Appending a string
buffer.append(" World");
// Inserting a string at a specific position
buffer.insert(6, "Java ");
// Replacing a part of the string
buffer.replace(6, 10, "Beautiful");
// Deleting a part of the string
buffer.delete(17, 18);
// Reversing the string
buffer.reverse();
13
// Converting to a string and printing
String result = buffer.toString();
System.out.println("Final string: " + result); // Output: dlroW lufituaeB olleH
}
}
In this example, various operations such as appending, inserting, replacing, deleting, and reversing are
performed on a StringBuffer object. These operations modify the content of the buffer directly,
demonstrating the mutability of StringBuffer.
Summary
The term "string buffer" refers to a structure used for the efficient manipulation of strings. In Java, the
StringBuffer class provides this functionality, allowing strings to be modified safely in a multithreaded
environment and avoiding the inefficiencies associated with creating multiple immutable String objects.
14
Ad

More Related Content

Similar to Arrays in Java with example and types of array.pptx (20)

Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Kashif Nawab
 
ARRAYS
ARRAYSARRAYS
ARRAYS
muniryaseen
 
17-Arrays en java presentación documento
17-Arrays en java presentación documento17-Arrays en java presentación documento
17-Arrays en java presentación documento
DiegoGamboaSafla
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
Abed Bukhari
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
rohassanie
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
Debasish Pratihari
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
Array properties
Array propertiesArray properties
Array properties
Shravan Sharma
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
 
SessionPlans_f3efa1.6 Array in java.pptx
SessionPlans_f3efa1.6 Array in java.pptxSessionPlans_f3efa1.6 Array in java.pptx
SessionPlans_f3efa1.6 Array in java.pptx
businessmarketing100
 
Arrays
ArraysArrays
Arrays
Notre Dame of Midsayap College
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
manish kumar
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
soniya555961
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 

Recently uploaded (20)

Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Ad

Arrays in Java with example and types of array.pptx

  • 1. Arrays in Java An array is a data structure that can hold multiple values of the same type. It's useful when you need to store a collection of data, but you don't want to create a variable for each element. Creating an Array To create an array in Java, you need to: 1. Declare the array. 2. Instantiate the array. 3. Initialize the array elements. Example: // Step 1: Declare an array Datatype arrayname[]; Datatype[] arrayname; int[] myArray; int rollno[]; // Step 2: Instantiate the array(Creation of Memory location) Arrayname= new datatype[size]; Rollno= new int[30]; Name = new char[30]; myArray = new int[5]; // Step 3: Initialize the array elements myArray[0] = 10; myArray[1] = 20; myArray[2] = 30; myArray[3] = 40; myArray[4] = 50; You can also combine the declaration, instantiation, and initialization in one line int[] myArray = {10, 20, 30, 40, 50}; int myArray[]={10,20,30,40,50}; Types of Arrays 1. One-Dimensional Arrays A one-dimensional array is a list of elements of the same type. It's the simplest form of an array. Example: int[] numbers = {1, 2, 3, 4, 5}; int number[]={1,2,3,4,5} 2. Two-Dimensional Arrays A two-dimensional array is an array of arrays, creating a matrix-like structure. Example: // Declare a 2D array int[][] matrix = new int[3][3]; // Initialize the 2D array matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3; matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6; matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9; You can also initialize a 2D array directly: 1
  • 2. int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; Strings in Java Strings in Java are objects that represent sequences of characters. The String class is used to create and manipulate strings. Creating a String You can create a string in several ways: 1. Using string literals: String str1 = "Hello, World!"; 2. Using the new keyword: String str2 = new String("Hello, World!"); Common String Methods The String class provides many methods for string manipulation. Here are some commonly used ones:  length(): Returns the length of the string. int length = str1.length();  charAt(int index): Returns the character at the specified index. char ch = str1.charAt(0); // 'H'  substring(int beginIndex, int endIndex): Returns a substring from the specified start index to the end index. String sub = str1.substring(0, 5); // "Hello"  contains(CharSequence s): Checks if the string contains the specified sequence of characters. boolean contains = str1.contains("World"); // true  replace(CharSequence target, CharSequence replacement): Replaces each occurrence of the specified sequence with another sequence String replaced = str1.replace("World", "Java"); // "Hello, Java!" StringBuffer Class The StringBuffer class is used to create mutable strings. Unlike String, which is immutable, StringBuffer allows modification of strings without creating new objects. Creating a StringBuffer: StringBuffer sb = new StringBuffer("Hello"); Common Methods of StringBuffer:  append(String str): Appends the specified string to this character sequence. sb.append(", World!"); // "Hello, World!"  insert(int offset, String str): Inserts the specified string at the specified position. sb.insert(5, " Java"); // "Hello Java, World!"  replace(int start, int end, String str): Replaces the characters in a substring of this sequence with characters in the specified string. sb.replace(6, 10, "Earth"); // "Hello Earth, World!"  delete(int start, int end): Removes the characters in a substring of this sequence. sb.delete(5, 11); // "Hello World!"  reverse(): Reverses the sequence of characters. sb.reverse(); // "!dlroW ,olleH" Summary  Arrays are used to store multiple values of the same type and can be one-dimensional or two- dimensional. 2
  • 3.  Strings are immutable objects used to represent sequences of characters, with many built-in methods for manipulation.  StringBuffer is a mutable sequence of characters, allowing in-place modification of the string. Understanding these fundamental concepts and their respective methods is crucial for effective Java programming. X-X-X-X-X-X-X-X-X-X Arrays in Java An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Types of Arrays 1. One-Dimensional Arrays 2. Two-Dimensional Arrays 3. One-Dimensional Arrays A one-dimensional array is like a list of elements. It is the simplest form of an array. Example and Explanation: public class OneDimensionalArrayExample { public static void main(String[] args) { // Declare an array of integers int[] array = new int[5]; // Initialize the array with values array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50; // Print the elements of the array for (int i = 0; i < array.length; i++) { System.out.println("Element at index " + i + ": " + array[i]); } } } Explanation:  int[] array = new int[5]; declares an array of integers with a size of 5.  array[0] = 10; initializes the first element of the array with the value 10.  A for loop is used to iterate through the array and print each element. 2. Two-Dimensional Arrays A two-dimensional array is like a table with rows and columns. It is often used to represent a matrix. Example and Explanation: public class TwoDimensionalArrayExample { public static void main(String[] args) { // Declare a 2D array of integers int[][] array = new int[3][3]; // Initialize the 2D array with values int value = 1; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { 3
  • 4. array[i][j] = value++; } } // Print the elements of the 2D array for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); // Print a new line after each row } } } Explanation:  int[][] array = new int[3][3]; declares a 2D array of integers with 3 rows and 3 columns.  Nested for loops are used to initialize the array with values starting from 1.  Another set of nested for loops is used to print the elements of the 2D array, displaying the array as a matrix. X-X-X-X-X-X-X-X-X-X-X Example 1: Initialize and Print Array Elements public class Main { public static void main(String[] args) { // Declare and initialize an array of 5 integers int[] array = {10, 20, 30, 40, 50}; // Print the elements of the array System.out.println("Elements of the array are:"); for (int i = 0; i < array.length; i++) { System.out.println("array[" + i + "] = " + array[i]); } } } Output Elements of the array are: array[0] = 10 array[1] = 20 array[2] = 30 array[3] = 40 array[4] = 50 Example 2: Find the Sum of Array Elements public class Main { public static void main(String[] args) { // Declare and initialize an array of 5 integers int[] array = {10, 20, 30, 40, 50}; // Calculate the sum of the elements of the array int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } // Print the sum of the elements 4
  • 5. System.out.println("Sum of the array elements is: " + sum); } } Output Sum of the array elements is: 150 Example 3: Find the Maximum Element in an Array public class Main { public static void main(String[] args) { // Declare and initialize an array of 5 integers int[] array = {10, 20, 30, 40, 50}; // Find the maximum element in the array int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } // Print the maximum element System.out.println("Maximum element in the array is: " + max); } } Output Maximum element in the array is: 50 Example 4: Reverse the Elements of an Array public class Main { public static void main(String[] args) { // Declare and initialize an array of 5 integers int[] array = {10, 20, 30, 40, 50}; // Reverse the elements of the array int n = array.length; for (int i = 0; i < n / 2; i++) { int temp = array[i]; array[i] = array[n - 1 - i]; array[n - 1 - i] = temp; } // Print the reversed array System.out.println("Reversed array elements are:"); for (int i = 0; i < array.length; i++) { System.out.println("array[" + i + "] = " + array[i]); } } } Output Reversed array elements are: array[0] = 50 array[1] = 40 array[2] = 30 array[3] = 20 5
  • 6. array[4] = 10 X-X-X-X-X-X-X-X-X-X-X Example 1: Initialize and Print 2D Array Elements public class Main { public static void main(String[] args) { // Declare and initialize a 2D array int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Print the elements of the 2D array System.out.println("Elements of the 2D array are:"); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); } } } Output Elements of the 2D array are: 1 2 3 4 5 6 7 8 9 Example 2: Sum of All Elements in a 2D Array public class Main { public static void main(String[] args) { // Declare and initialize a 2D array int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Calculate the sum of all elements in the 2D array int sum = 0; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { sum += array[i][j]; } } // Print the sum of all elements System.out.println("Sum of all elements in the 2D array is: " + sum); } } Output Sum of all elements in the 2D array is: 45 6
  • 7. Example 3: Transpose of a 2D Array public class Main { public static void main(String[] args) { // Declare and initialize a 2D array int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Transpose the 2D array int[][] transpose = new int[array[0].length][array.length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { transpose[j][i] = array[i][j]; } } // Print the transposed array System.out.println("Transpose of the 2D array is:"); for (int i = 0; i < transpose.length; i++) { for (int j = 0; j < transpose[i].length; j++) { System.out.print(transpose[i][j] + " "); } System.out.println(); } } } Output Transpose of the 2D array is: 1 4 7 2 5 8 3 6 9 Example 4: Multiplication of Two 2D Arrays public class Main { public static void main(String[] args) { // Declare and initialize two 2D arrays int[][] array1 = { {1, 2, 3}, {4, 5, 6} }; int[][] array2 = { {7, 8}, {9, 10}, {11, 12} }; // Multiply the two 2D arrays int[][] product = new int[array1.length][array2[0].length]; for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array2[0].length; j++) { for (int k = 0; k < array1[0].length; k++) { 7
  • 8. product[i][j] += array1[i][k] * array2[k][j]; } } } // Print the product of the two arrays System.out.println("Product of the two 2D arrays is:"); for (int i = 0; i < product.length; i++) { for (int j = 0; j < product[i].length; j++) { System.out.print(product[i][j] + " "); } System.out.println(); } } } Output Product of the two 2D arrays is: 58 64 139 154 X-X-X-X-X-X-X-X-X-X-X Array Length: In Java, the length of an array is determined using the length property. Here's a simple explanation and an example demonstrating how to get the length of both 1D and 2D arrays. Example: Getting the Length of 1D and 2D Arrays public class Main { public static void main(String[] args) { // Declare and initialize a 1D array int[] oneDArray = {1, 2, 3, 4, 5}; // Get and print the length of the 1D array System.out.println("Length of the 1D array: " + oneDArray.length); // Declare and initialize a 2D array int[][] twoDArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Get and print the number of rows in the 2D array System.out.println("Number of rows in the 2D array: " + twoDArray.length); // Get and print the number of columns in each row of the 2D array for (int i = 0; i < twoDArray.length; i++) { System.out.println("Number of columns in row " + i + ": " + twoDArray[i].length); } } } Output Length of the 1D array: 5 Number of rows in the 2D array: 3 Number of columns in row 0: 3 Number of columns in row 1: 3 Number of columns in row 2: 3 8
  • 9. Explanation 1. 1D Array Length: o The length property of the array oneDArray returns the number of elements in the 1D array. o oneDArray.length is 5 because the array contains 5 elements. 2. 2D Array Length: o For a 2D array, length gives the number of rows in the array. o twoDArray.length is 3 because there are 3 rows in the 2D array. o To get the number of columns in each row, we use twoDArray[i].length, where i is the index of the row. X-X-X-X-X-X-X-X-X-X-X String Arrays in Java A string array is an array of objects where each element is a reference to a String object. Example and Explanation: public class StringArrayExample { public static void main (String[] args) { // Declare and initialize a String array String[] fruits = {"Apple", "Banana", "Cherry"}; // Print the elements of the String array for (int i = 0; i < fruits.length; i++) { System.out.println("Element at index " + i + ": " + fruits[i]); } } } Explanation:  String[] fruits = {"Apple", "Banana", "Cherry"}; declares and initializes a String array with three elements.  A for loop is used to iterate through the array and print each fruit. Summary  One-Dimensional Arrays: Simple list of elements, easy to use for basic storage and access.  Two-Dimensional Arrays: Represented as a table with rows and columns, useful for matrix operations.  String Arrays: Array of String objects, useful for storing a list of strings. Arrays in Java provide a way to store multiple values in a single variable, which can be useful for handling large amounts of data efficiently. X-X-X-X-X Strings in Java Strings in Java are objects that represent sequences of characters. They are immutable, meaning once a string is created, it cannot be changed. The String class is used to create and manipulate strings. Creating Strings There are several ways to create strings in Java: 1. Using string literals: When a string is created using double quotes, it is stored in the string pool. 2. Using the new keyword: This creates a new string object in the heap. Examples and Explanations 1. Creating Strings Example: public class StringExample { public static void main(String[] args) { // Using string literals 9
  • 10. String str1 = "Hello"; String str2 = "World"; // Using the new keyword String str3 = new String("Hello"); String str4 = new String("World"); // Printing the strings System.out.println("str1: " + str1); System.out.println("str2: " + str2); System.out.println("str3: " + str3); System.out.println("str4: " + str4); } } Explanation:  String str1 = "Hello"; creates a string literal and stores it in the string pool.  String str3 = new String("Hello"); creates a new string object in the heap.  System.out.println("str1: " + str1); prints the value of str1. 2. String Methods The String class provides many methods to manipulate and work with strings. Example: public class StringMethodsExample { public static void main(String[] args) { String str = "Hello, World!"; // Length of the string int length = str.length(); System.out.println("Length: " + length); // Character at a specific index char charAt2 = str.charAt(2); System.out.println("Character at index 2: " + charAt2); // Substring String substr = str.substring(7, 12); System.out.println("Substring (7, 12): " + substr); // Replace String replacedStr = str.replace("World", "Java"); System.out.println("Replaced: " + replacedStr); // To Uppercase String upperStr = str.toUpperCase(); System.out.println("Uppercase: " + upperStr); // To Lowercase String lowerStr = str.toLowerCase(); System.out.println("Lowercase: " + lowerStr); // Trim String trimmedStr = " Hello ".trim(); System.out.println("Trimmed: '" + trimmedStr + "'"); // Split String[] splitStr = str.split(", "); for (String s : splitStr) { System.out.println("Split: " + s); } } } 10
  • 11. Explanation:  str.length() returns the length of the string.  str.charAt(2) returns the character at index 2.  str.substring(7, 12) returns the substring from index 7 to 11.  str.replace("World", "Java") replaces "World" with "Java".  str.toUpperCase() converts the string to uppercase.  str.toLowerCase() converts the string to lowercase.  " Hello ".trim() removes leading and trailing spaces.  str.split(", ") splits the string by ", " and returns an array of strings. 3. StringBuffer and StringBuilder While String objects are immutable, StringBuffer and StringBuilder are mutable and can be modified without creating new objects.  StringBuffer is thread-safe and synchronized.  StringBuilder is not thread-safe but faster. Example: public class StringBufferExample { public static void main(String[] args) { // Using StringBuffer StringBuffer buffer = new StringBuffer("Hello"); buffer.append(" World"); System.out.println("StringBuffer: " + buffer); // Using StringBuilder StringBuilder builder = new StringBuilder("Hello"); builder.append(" World"); System.out.println("StringBuilder: " + builder); } } Explanation:  StringBuffer buffer = new StringBuffer("Hello"); creates a StringBuffer object.  buffer.append(" World"); appends " World" to the buffer.  StringBuilder builder = new StringBuilder("Hello"); creates a StringBuilder object.  builder.append(" World"); appends " World" to the builder. Summary  String: Immutable sequences of characters.  String methods: Provide various operations like length, charAt, substring, replace, toUpperCase, toLowerCase, trim, and split.  StringBuffer and StringBuilder: Mutable sequences of characters, with StringBuffer being thread-safe and StringBuilder being faster but not thread-safe. Understanding these concepts and methods allows for effective manipulation and handling of strings in Java. X-X-X-X-X-X StringBuffer Class in Java The StringBuffer class in Java is used to create mutable (modifiable) string objects. Unlike the String class, StringBuffer objects can be modified without creating new objects. This class is thread-safe, meaning it is synchronized and can be used in a multithreaded environment. Key Features of StringBuffer:  Mutable: StringBuffer objects can be changed after they are created.  Thread-safe: Methods of StringBuffer are synchronized, making it safe to use in concurrent programming.  Dynamic: The buffer size can grow automatically if needed. 11
  • 12. Common Methods of StringBuffer:  append(String s): Appends the specified string to this sequence.  insert(int offset, String s): Inserts the specified string at the specified position.  replace(int start, int end, String str): Replaces the characters in a substring of this sequence with characters in the specified string.  delete(int start, int end): Removes the characters in a substring of this sequence.  reverse(): Reverses the sequence of characters.  toString(): Converts the StringBuffer to a String. Example and Explanation: public class StringBufferExample { public static void main(String[] args) { // Creating a StringBuffer object with an initial string StringBuffer buffer = new StringBuffer("Hello"); // Appending strings buffer.append(" World"); buffer.append("!"); // Inserting a string at a specific position buffer.insert(6, "Java "); // Replacing a part of the string buffer.replace(6, 10, "Beautiful"); // Deleting a part of the string buffer.delete(17, 18); // Reversing the string buffer.reverse(); // Converting to a string and printing String result = buffer.toString(); System.out.println("Final string: " + result); } } Explanation: 1. Creating a StringBuffer object: StringBuffer buffer = new StringBuffer("Hello"); This creates a StringBuffer object with the initial content "Hello". 2. Appending strings: buffer.append(" World"); buffer.append("!"); The append method is used to add " World" and "!" to the existing string. The buffer now contains "Hello World!". 3. Inserting a string: buffer.insert(6, "Java "); The insert method adds "Java " at position 6. The buffer now contains "Hello Java World!". 4. Replacing a part of the string: buffer.replace(6, 10, "Beautiful"); The replace method replaces the substring from index 6 to 10 with "Beautiful". The buffer now contains "Hello Beautiful World!". 5. Deleting a part of the string: buffer.delete(17, 18); The delete method removes the character at index 17 (the exclamation mark). The buffer now contains "Hello Beautiful World". 6. Reversing the string: 12
  • 13. buffer.reverse(); The reverse method reverses the sequence of characters. The buffer now contains "dlroW lufituaeB olleH". 7. Converting to a string: String result = buffer.toString(); System.out.println("Final string: " + result); The toString method converts the StringBuffer to a String object, which is then printed. Summary The StringBuffer class provides a flexible way to manipulate strings in a multithreaded environment due to its mutability and thread-safety. Understanding and using the various methods provided by StringBuffer allows for efficient and effective string manipulation in Java. X-X-X-X-X-X-X-X-X-X-X-X-X-X-X StringBuffer Class: The term "string buffer" in computing generally refers to a data structure used to build and manipulate strings of characters efficiently. Specifically, in Java, StringBuffer is a class that provides methods to work with strings that can be modified after they are created. Here's a breakdown of the term "string buffer": 1. String: A sequence of characters, often used to represent text. 2. Buffer: A temporary storage area typically used to hold data while it is being transferred from one place to another. Combining these concepts, a string buffer is a buffer that holds a sequence of characters (a string) and allows for efficient manipulation of this sequence. This includes operations such as appending, inserting, deleting, and reversing characters in the sequence. Characteristics of StringBuffer in Java  Mutable: Unlike String objects, which are immutable (cannot be changed once created), StringBuffer objects can be modified. This means that operations like appending and inserting characters do not create new objects but modify the existing one.  Thread-safe: The methods of StringBuffer are synchronized, which makes it safe to use in a multithreaded environment without additional synchronization. Usage When performing multiple operations on strings, such as concatenation in loops, using a StringBuffer can be more efficient than using String. This is because modifying a String object repeatedly creates new objects each time, which can be resource-intensive. In contrast, StringBuffer allows for these modifications within the same object. Example Here's a simple example to illustrate the use of StringBuffer in Java: public class StringBufferExample { public static void main(String[] args) { // Creating a StringBuffer object StringBuffer buffer = new StringBuffer("Hello"); // Appending a string buffer.append(" World"); // Inserting a string at a specific position buffer.insert(6, "Java "); // Replacing a part of the string buffer.replace(6, 10, "Beautiful"); // Deleting a part of the string buffer.delete(17, 18); // Reversing the string buffer.reverse(); 13
  • 14. // Converting to a string and printing String result = buffer.toString(); System.out.println("Final string: " + result); // Output: dlroW lufituaeB olleH } } In this example, various operations such as appending, inserting, replacing, deleting, and reversing are performed on a StringBuffer object. These operations modify the content of the buffer directly, demonstrating the mutability of StringBuffer. Summary The term "string buffer" refers to a structure used for the efficient manipulation of strings. In Java, the StringBuffer class provides this functionality, allowing strings to be modified safely in a multithreaded environment and avoiding the inefficiencies associated with creating multiple immutable String objects. 14