Unit-III, P1
Unit-III, P1
UNIT-III, PART-I
Introduction to Array:
Array is a structures of data in Java, that allow us to store multiple values of the
same type in a single variable. They are useful for managing collections of same
types data i.e., int, float, string etc. We can store only a fixed set of elements in a
Java array.
In a single line array can be defined as, Array is a collection of similar types of
data in a single variable. Each value of an array is known as element of the array.
Each element of the array is identified by its index value. Index value is unique
value that is started from 0 (zero).
JAVA(UGCA-1932)
UNIT-III, PART-I
Declaring an Array:
To declare an array in JAVA, we write the data type of elements that array will stored, followed
by square brackets [ ], and then name of the array. Name of the Array can be written before or
after the square bracket i.e. int my_aaray[]; or int[] my_array;
Initializing an Array:
We can initialize an array either at the time of declaring it or later.
Example:
// Declaration without initialization
int[] numbers;
Looping an Array:
We can loop or iterate an array using a for loop or enhanced for loop (also called for-each loop)
provided by JAVA.
1.for loop:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Access an element
System.out.println("First element: " + numbers[0]);
// Modify an element
numbers[2] = 10;
System.out.println("Modified array ");
// Iterate over the array
System.out.print("Array elements: ");
for (int number : numbers) {
System.out.print(number + " ");
}
}
}
JAVA(UGCA-1932)
UNIT-III, PART-I
OUTPUT
OUTPUT
Explanation:
The method createArray() creates an array numbers and returns it.
In the main method, the returned array is stored in the variable resultArray, and its
elements are printed.
// Call the method with the array and get the modified array
int[] modifiedArray = modifyArray(numbers);
}
}
}
OUTPUT
Array of Objects:
The array of Objects, the name itself suggests that it stores multiple objects in an array. Just like
the other array stores values like String, integer, etc. An array of Object stores objects it means
objects are stored as elements of an array.
When we require a single object to perform specified method in the program, we do it with an
object variable. But When we deal with numerous objects, then it is preferred to use an array of
objects.
1. Declare an array of objects: The syntax for declaring an array of objects is similar to
declaring an array of primitives.
class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
JAVA(UGCA-1932)
UNIT-III, PART-I
Explanation:
1. We create a class Person with attributes name and age and a method display() to print
the details.
2. We declare an array of Person objects: Person[] persons = new Person[3];.
JAVA(UGCA-1932)
UNIT-III, PART-I
3. For each element in the array, we instantiate a Person object and assign it to the
respective array index.
4. Finally, we use a loop to access and display each Person object's details.
class Car {
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
2D Arrays:
In Java, a 2D array is an array of arrays, which means each element of a 2D array is another. A 2D
array is commonly used to represent data in a table or matrix form, where each row of the array is
similar to a row in the matrix and each column is similar to a column in the matrix.
The syntax for declaring a 2D array is as follows:
dataType[][] arrayName;
Initializing a 2D Array:
1. Using new keyword: You can create a 2D array by specifying the number of rows and
columns.
// 3 rows, 4 columns
2. Directly initializing with values: You can initialize a 2D array by specifying the values
for each row.
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
matrix[0][1] = 20;
// Modifies the element at row 0, column 1
JAVA(UGCA-1932)
UNIT-III, PART-I
Example:
// Accessing an element
// System.out.println("Element at row 1, column 2: " + matrix[1][2]);
// Output: 7
// Modifying an element
// matrix[0][0] = 100;
// System.out.println("Modified element at row 0, column 0: " + matrix[0][0]);
// Output: 100
Using new keyword: You can initialize a multidimensional array by specifying the size of
each dimension.
Direct initialization with values: You can directly initialize a multidimensional array with
values.
int[][][] array3D = {
{
{1, 2, 3}, {4, 5, 6}
},
{
{7, 8, 9}, {10, 11, 12}
},
{
{13, 14, 15}, {16, 17, 18}
}
};
Accessing and Modifying Elements in a Multidimensional Array:
Each additional dimension requires an extra index to access specific elements (like; for 2D 2
indexes, for 3D 3 indexes and so on) . For a 3D array, you need three indices: one for the "layer",
one for the "row", and one for the "column".
JAVA(UGCA-1932)
UNIT-III, PART-I
You can also modify elements by assigning a new value using the same index notation.
array3D[2][1][0] = 100;
// Modifies the element at layer 2, row 1, column 0
};
OUTPUT
If you need more dimensions, you can declare arrays with 4, 5, or more dimensions. Here's an
example of a 4D array:
// elements input
a[0][0][0][0] = 1;
a[0][0][0][1] = 2;
a[0][0][1][0] = 3;
a[0][1][0][0] = 4;
a[1][0][0][0] = 5;
}
}
JAVA(UGCA-1932)
UNIT-III, PART-I
OUTPUT
String Class:
String:
Generally, a String is a sequence of characters. But in Java, a string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
In Java, the String class is used to represent and manipulate sequences of characters. Strings are
one of the most commonly used classes in Java, and they are immutable, meaning that once String
object is created, its value cannot be changed.
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Creating a String
There are two main ways to create a string in Java:
1. Using string literals: When a string is created using double quotes, it is automatically
stored in the string pool.
String str1 = "Hello"; // String literal
JAVA(UGCA-1932)
UNIT-III, PART-I
2. Using the new keyword: When a string is created using the new keyword, it creates a new
String object in the heap, even if the same string already exists in the pool.
6. concat(String str): Concatenates the specified string to the end of the current
string.
11. indexOf(String str): Returns the index of the first occurrence of the specified
substring. Returns -1 if the substring is not found.
13. trim(): Removes any leading and trailing whitespace from the string.
14. split(String regex): Splits the string into an array of substrings based on a
regular expression (regex).
// Modify str1
str1 = str1.concat(" World");
In this example, you can see that str1 was modified to "Hello World", but str2 (which was
initially pointing to the same string as str1) still holds "Hello". This demonstrates that strings
are immutable.
Summary:
The String class in Java is immutable, meaning any modification results in a new string
being created.
Strings are stored in a special memory area called the string pool for optimization
purposes.
The String class provides many methods for string manipulation such as length(),
substring(), toUpperCase(), concat(), and replace().
String objects are compared using either the == operator (reference comparison) or the
equals() method (content comparison).
Comparing Strings:
1. == operator: Compares the references (memory addresses) of the two string objects. It
checks if both strings point to the same memory location.
Syntax:
Str2.equalsIgnoreCase(str1);
String Concatenation:
String concatenation in Java refers to combining two or more strings into a single string. Java
provides several ways to concatenate strings, including using the + operator, the concat()
method, and the StringBuilder or StringBuffer classes for more efficient concatenation
in loops or complex operations.
The most common and simplest way to concatenate strings in Java is by using the + operator.
The concat() method is another way to join two strings. It is part of the String class and
can only concatenate one string to another.
Note: The concat() method doesn't add spaces between strings, so you need to manually
include them where necessary.
StringBuilder is faster than + and concat() when performing many concatenations because
it does not create new objects for every concatenation.
After concatenation, you can use the toString() method to convert the StringBuilder to a
String.
Summary of Methods
1. + Operator:
o Simple and commonly used.
o Suitable for small concatenations.
JAVA(UGCA-1932)
UNIT-III, PART-I
Substring in Java:
In Java, the substring() method is part of the String class and is used to extract a portion of a string.
There are two different way of the substring() method, each allowing you to specify either a
starting index or both starting and ending indices.
1. substring(int beginIndex):
This method extracts a substring starting from the specified index to the end of the string.
This method extracts a substring between the specified beginIndex and endIndex.
Key Points:
Indexing in Java strings is zero-based, meaning the first character is at index 0.
The beginIndex is inclusive, meaning the character at beginIndex is included in the
substring.
The endIndex is exclusive, meaning the character at endIndex is not included in the
substring.
If beginIndex is equal to endIndex, the result is an empty string ("").
If beginIndex is negative or greater than the string's length, or if beginIndex is greater
than endIndex, the method throws a StringIndexOutOfBoundsException.
What is StringBuffer?
StringBuffer is the equivalent class of the class string. The class StringBuffer provides more
functionality than the other class strings. We can make changes here because the StringBuffer is
mutable.
S. No. String StringBuffer
3 Here the length of the string class Here the length can be modified whenever
is static. required, as it is dynamic in behavior.
6 It utilizes a pool ( part of the It prefers heap memory to store the objects.
memory) to store the values.
JAVA(UGCA-1932)
UNIT-III, PART-I
It's generally recommended to use the split() method of the String class or Scanner class, as they
are more flexible and easier to use.
3. nextToken(String delim): Returns the next token using the specified delimiter
instead of the default one.
import java.util.StringTokenizer;
// Count tokens
System.out.println("NumberOfToken:" + st.countTokens());
OUTPUT
JAVA(UGCA-1932)
UNIT-III, PART-I
Conclusion: