Array and Strings in Java
Array and Strings in Java
• Creating an Array:
• numbers = new int[5]; // Creating an array of size 5
• Initialization of an Array:
• int[] numbers = {1, 2, 3, 4, 5}; // Initializing an array directly
• Accessing Array Elements:
• int firstNumber = numbers[0]; // Access the first element (index 0)
System.out.println(firstNumber); // Output: 1
Example Programs
• Simple Array Declaration and Access
Output
First element: 10
Last element: 50
Iterating Over an Array Using a Loop
public class ArrayIteration {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25}; // Declare and initialize array // Using a for loop to
iterate over the array
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
Output
Element at index 0: 5
Element at index 1: 10
Element at index 2: 15
Element at index 3: 20
String in Java
• String is a sequence of characters.
• Strings are immutable, meaning once a string is created, it cannot be
changed.
• Strings are objects, but can be represented using string literals.
• Example
• String name = "Java";
Declaring and Initializing Strings
String Methods
• toLowerCase(): Converts string to lowercase
String lowerStr = str.toLowerCase();
toUpperCase(): Converts string to uppercase
String upperStr = str.toUpperCase();
substring(start, end): Extracts a part of the string.
String subStr = str.substring(0, 5); // "Hello"
replace(old, new): Replaces characters in a string
String replacedStr = str.replace("Java", "World");
String Comparison
• equals(): Checks if two strings are equal.
• Example
String str = "Hello";
str = str + " World"; // Creates a new string object, old string remains unchanged.