0% found this document useful (0 votes)
13 views11 pages

Java Arrays and String Handling Guide

Uploaded by

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

Java Arrays and String Handling Guide

Uploaded by

dassomenath157
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PAPER NAME: OBJECT ORIENTED PROGRAMMING WITH JAVA

PAPER CODE: BCAC502


MODULE NO: 05

ARRAYS AND STRINGS

1. INTRODUCTION TO ARRAYS

An array is a data structure that stores a fixed-size sequence of elements of the same data
type.
It is used when we need to store multiple values of the same type together instead of declaring
separate variables for each value.

It allows random access to elements using an index.

 Arrays in Java are objects that store multiple variables of the same type.
 Each element in the array is accessed by an index number starting from 0.

Syntax:

datatype[] arrayName = new datatype[size];

For example:
Instead of declaring:

int mark1, mark2, mark3, mark4, mark5;

we can declare:

int[] marks = new int[5];

Arrays make code simpler, easier to manage, and faster to access.

Key Points:

 Arrays in Java are objects.


 The index starts from 0.
 Each element is accessed using an index number.
 The length of the array is fixed once created.
Syntax:

dataType[] arrayName = new dataType[size];

or

dataType[] arrayName = {value1, value2, value3, ...};

Example:

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


[Link](numbers[2]); // Output: 30

2. SINGLE-DIMENSIONAL ARRAY

A single-dimensional array is the simplest form of array. It represents a list of elements


arranged in a single row.

Key Points:

 Marks. Length gives the number of elements in the array.


 The elements are accessed using index positions like marks[0], marks[1], etc.

Declaration and Initialization:


int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

or

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


Accessing Elements:

You can access array elements using the index:

[Link](arr[1]); // Output: 20
Traversing an Array:
for(int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + arr[i]);
}
Advantages:

 Easy to store multiple values.


 Random access of elements using index.
 Code efficiency and simplicity.

Disadvantages:

 Fixed size (cannot grow or shrink).


 Only stores same type of data.
 Insertion/deletion is difficult.

3. MULTI-DIMENSIONAL ARRAYS

A multi-dimensional array is an array of arrays.


The most common is the two-dimensional (2D) array, which can represent a table or matrix.

Declaration:
dataType[][] arrayName = new dataType[rows][columns];
Initialization:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements:
[Link](matrix[0][2]); // Output: 3
Traversing 2D Array:
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
Example Output:
123
456
789
3D Arrays (Example):
int[][][] cube = new int[3][3][3];
cube[0][1][2] = 10;
4. USE OF ARRAYS CLASS ([Link])

Java provides a utility class called [Link] to perform common array operations easily
and efficiently.

Common Methods:
Method Description Example
[Link](array) Converts array to [Link]([Link](arr));
readable string
[Link](array) Sorts the array in [Link](arr);
ascending order
[Link](array, Searches for element int index = [Link](arr,
key) using binary search 10);
(array must be sorted)
[Link](arr1, arr2) Checks if two arrays [Link](a1, a2);
are equal
[Link](array, value) Fills array with [Link](arr, 0);
specified value
[Link](arr, Copies one array into int[] b = [Link](a, 5);
newLength) another

Example:

import [Link];
class ArrayDemo {
public static void main(String[] args) {
int[] arr = {4, 2, 9, 1, 5};

[Link]("Original: " + [Link](arr));


[Link](arr);
[Link]("Sorted: " + [Link](arr));

int index = [Link](arr, 5);


[Link]("Element 5 found at index: " + index);
}
}

Output:

Original: [4, 2, 9, 1, 5]
Sorted: [1, 2, 4, 5, 9]
Element 5 found at index: 3
5. STRING HANDLING IN JAVA

A String in Java is a sequence of characters enclosed in double quotes (" "). Strings are
immutable, meaning once created, their value cannot be changed.

Declaration and Initialization:


String str1 = "Hello";
String str2 = new String("World");
String Concatenation:
String result = str1 + " " + str2;
[Link](result); // Output: Hello World
Important String Methods:
Method Description Example Output
length() Returns length of [Link]() 5
string
charAt(index) Returns character [Link](1) 'e'
at given index
concat(str) Joins two strings [Link](str2) HelloWorld
equals(str) Compares two [Link]("Hello") true
strings
equalsIgnoreCase(str) Ignores case while "HELLO".equalsIgnoreCase("hello") true
comparing
toUpperCase() Converts to upper [Link]() HELLO
case
toLowerCase() Converts to lower [Link]() hello
case
substring(start, end) Extracts part of [Link](1,4) ell
string
trim() Removes spaces " hi ".trim() hi
replace('a','e') Replaces "java".replace('a','e') jeve
characters
split(" ") Splits string "A B C".split(" ") [A, B, C]

Example:

String s = "Java Programming";


[Link]([Link]());
[Link]([Link](5, 16));
[Link]([Link]());
[Link]([Link]("Java", "Advanced Java"));

6. STRINGBUFFER

A StringBuffer is a mutable (modifiable) sequence of characters.


It is used when we need to modify a string frequently (e.g., appending, inserting, deleting text).
It is synchronized, hence thread-safe.

Syntax:
StringBuffer sb = new StringBuffer("Hello");
Common Methods:
Method Description Example Output
append(String s) Adds text at the end [Link](" Java") Hello Java
insert(int index, String s) Inserts text at position [Link](5, " Hello World
World")
replace(int start, int end, Replaces part of string [Link](0,5,"Hi") Hi World
String s)
delete(int start, int end) Deletes characters [Link](0,3) lo World
reverse() Reverses string [Link]() dlroW iH
capacity() Shows capacity of [Link]() Default
buffer 16+length
length() Returns length [Link]() —

Example:

StringBuffer sb = new StringBuffer("Java");


[Link](" Programming");
[Link](0, "Welcome to ");
[Link](0, 7, "Hi");
[Link]();
[Link](sb);

7. STRINGBUILDER

StringBuilder is almost identical to StringBuffer, but it is not synchronized.


It is faster and used in single-threaded applications.

Syntax:
StringBuilder sb = new StringBuilder("Data");
[Link](" Structure");
[Link](sb);
Methods of StringBuilder

It supports the same methods as StringBuffer:


append(), insert(), replace(), delete(), reverse(), capacity(), etc.

ARRAYS CLASS, STRING HANDLING, STRINGBUFFER, AND STRINGBUILDER

1. USE OF ARRAYS CLASS

In Java, the [Link] class provides static utility methods to perform common
operations on arrays such as printing, sorting, and searching.

You must import the class before using it:

import [Link];

(a) PRINTING AN ARRAY

Normally, printing an array directly gives a memory address (e.g., [I@15db9742]).


To print the array elements properly, we use the [Link]() method.

Example:

import [Link];

class PrintArray {
public static void main(String[] args) {
int[] arr = {5, 10, 15, 20};
[Link]("Array Elements: " + [Link](arr));
}
}

Output:

Array Elements: [5, 10, 15, 20]

(b) SORTING AN ARRAY

The [Link]() method sorts the elements of an array in ascending order (by default).

Example:

import [Link];
class SortArray {
public static void main(String[] args) {
int[] arr = {40, 10, 30, 20};
[Link](arr);
[Link]("Sorted Array: " + [Link](arr));
}
}

Output:

Sorted Array: [10, 20, 30, 40]

(c) SEARCHING AN ELEMENT

The [Link]() method is used to find the index of a specific element in a sorted
array.
If the element is not found, it returns a negative value.

Example:

import [Link];

class SearchArray {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int index = [Link](arr, 30);
[Link]("Element 30 found at index: " + index);
}
}

Output:

Element 30 found at index: 2

2. STRING HANDLING

A String in Java is a sequence of characters enclosed in double quotes (" ").


Strings are immutable, which means once created, their value cannot be changed.

Example:

String s1 = "Java";
String s2 = "Programming";
String s3 = s1 + " " + s2;
[Link](s3);
Output:

Java Programming
Common String Methods
Method Description Example Output
length() Returns length of string "Hello".length() 5
charAt(int index) Returns character at "Hello".charAt(1) e
index
concat(String s) Concatenates two "Java".concat(" Code") Java
strings Code
equals(String s) Compares two strings "Hi".equals("hi") false
equalsIgnoreCase(String Ignores case while "Hi".equalsIgnoreCase("hi") true
s) comparing
substring(int start, int Extracts substring "Programming".substring(0,4) Prog
end)
toUpperCase() Converts to uppercase "java".toUpperCase() JAVA
toLowerCase() Converts to lowercase "JAVA".toLowerCase() java
trim() Removes " Hello ".trim() Hello
leading/trailing spaces
replace(char old, char Replaces characters "banana".replace('a','e') benene
new)

Example:

String name = " Java Language ";


[Link]([Link]());
[Link]([Link]());
[Link]([Link]("Java", "Python"));

3. STRINGBUFFER

A StringBuffer is a mutable (modifiable) sequence of characters.


It allows changes such as append, insert, delete, or reverse without creating new objects.
It is thread-safe (synchronized), meaning it can be safely used by multiple threads.

Syntax:

StringBuffer sb = new StringBuffer("Java");


Common Methods of StringBuffer
Method Description Example Output
append(String s) Adds string to end [Link](" Java Language
Language")
insert(int index, String s) Inserts text at given [Link](4, " is") Java is
index Language
replace(int start, int end, Replaces characters [Link](0, 4, Python
String s) "Python") Language
delete(int start, int end) Deletes characters [Link](0, 7) Language
reverse() Reverses content [Link]() egaugnaL
capacity() Returns total capacity [Link]() 16 + string
length

Example:

StringBuffer sb = new StringBuffer("Hello");


[Link](" Java");
[Link]();
[Link](sb);

Output:

avaJ olleH

4. STRINGBUILDER

StringBuilder is similar to StringBuffer, but it is not synchronized (not thread-safe).


It provides better performance in single-threaded environments.

Syntax:

StringBuilder sb = new StringBuilder("Data");


[Link](" Structure");
[Link](sb);

Output:

Data Structure
Common Methods of StringBuilder

Same as StringBuffer:

 append()
 insert()
 replace()
 delete()
 reverse()
 capacity()
 length()

8. DIFFERENCE BETWEEN STRING, STRINGBUFFER AND STRINGBUILDER

Feature String StringBuffer StringBuilder


Mutability Immutable Mutable Mutable
Thread Safe (immutable) Thread-safe Not thread-safe
Safety (synchronized)
Performance Slow Slower than Fastest
StringBuilder
Package [Link] [Link] [Link]
Use Case When value never When multi-threading When single-threaded and
changes needed frequent modification

Common questions

Powered by AI

StringBuffer in Java ensures thread safety by synchronizing its methods, meaning that only one thread can call a method of a StringBuffer object at a time, avoiding concurrent modifications. This makes StringBuffer safe for use in multi-threaded programming scenarios where strings are modified frequently. For example, a StringBuffer can be initialized and used as follows: StringBuffer sb = new StringBuffer("Hello"); sb.append(" Java"); This ensures that complex modifications (e.g., append, insert, delete) are handled safely across threads, although it results in some performance overhead compared to non-synchronized alternatives .

The advantages of using arrays in Java include the ability to easily store multiple values of the same type and to access elements directly using an index, which enhances code efficiency and simplicity. However, arrays have fixed sizes, meaning they cannot grow or shrink, and they can only store elements of the same data type, limiting flexibility. Additionally, operations such as insertion and deletion can be difficult to perform on arrays .

The Arrays.sort() method in Java sorts the elements of an array in ascending order by default. It efficiently organizes the array elements, typically using the dual-pivot Quicksort algorithm for primitive types, which is a faster hybrid of quicksort and other sorting algorithms, ensuring optimal performance for a wide variety of data .

The immutability of the String class can lead to performance optimization in Java memory management through the concept of string literals pooling. When a String object is created, it is placed in a special memory region called the "string pool." If a String with the same content is subsequently created, it will reference the existing String in the pool instead of creating a new object, based on string interning. This reduces memory overhead by reusing instances, but requires effectively managing the lifecycle and usage of string data to fully leverage these efficiencies .

The Arrays.copyOf() method is used to create a copy of an array with a specified new length. It is commonly used when an array's size must be altered, such as when growing the array or trimming it. This method can be beneficial when implementing dynamic data structures or algorithms that require extensive resizing of collections, providing a straightforward approach to alter the array's length while preserving its contents up to the new length .

The Arrays.binarySearch() method is used to find the index of a specific element in a sorted array. The array must be sorted in ascending order before binary search is applied; otherwise, the result will be undefined. This method performs the binary search algorithm, which efficiently locates the target value by repeatedly dividing the search interval in half .

A single-dimensional array in Java is a linear list of elements, represented in a single row, which is accessed using a single index. It is suitable for storing simple lists of values. A multi-dimensional array, such as a two-dimensional array, represents data in a tabular format akin to a table or matrix and is accessed using multiple indices (e.g., [i][j] for a 2D array). This structure is used for more complex data organizations, like representing grids or chessboards, where relationships between data elements must be maintained in more than one direction .

Strings in Java are immutable; once created, they cannot be changed. They are thread-safe because immutability ensures the original string cannot be altered. StringBuffer, on the other hand, is mutable and allows modifications to the character sequence, such as appends or replacements, making it suitable for multi-threaded environments due to its synchronized nature, although this means it is slower than StringBuilder. StringBuilder is also mutable but not synchronized, which allows for better performance in single-threaded applications when frequent modifications to strings are necessary. Choosing between them depends on the need for mutability and thread safety—use String for unchanging sequences, StringBuffer for thread-safe manipulations, and StringBuilder for efficient changes in a single-thread context .

The immutability of Java strings means that any modification to a String object results in the creation of a new String object, which can lead to increased memory usage especially in operations with frequent string concatenations or modifications, as each modification generates a new object. This can degrade performance in scenarios such as loops where strings are repeatedly altered. However, immutability enhances security and thread safety, as it ensures that the same String instance can be safely shared between tasks without the risk of changes .

StringBuilder is preferred over StringBuffer in scenarios where string modifications are frequent and occur in a single-threaded environment, due to its non-synchronized nature, which provides better performance and efficiency. The lack of synchronization makes StringBuilder faster than StringBuffer as it eliminates unnecessary overhead from synchronization when thread safety is not a concern .

You might also like