Arrays in Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

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
1. 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:
123
456
789
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:
147
258
369
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

You might also like