π Introduction
Real-world applications often deal with multiple values β like a list of names, scores, or dates. Java provides powerful tools to handle these:
- Arrays β fixed-size collections of the same type.
- Strings β sequences of characters (like words or sentences).
Letβs dive into both with simple examples and tips!
π’ Java Arrays β Store Multiple Values
π What is an Array?
An array is a container object that holds a fixed number of values of the same type.
β Declaring and Initializing Arrays
int[] numbers = new int[5]; // creates an array with 5 elements
Or directly initialize:
int[] numbers = {10, 20, 30, 40, 50};
π Accessing Array Elements
Arrays are zero-indexed: the first element is at index 0
.
System.out.println(numbers[0]); // prints 10
numbers[1] = 25; // updates second value
π Looping Through Arrays
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
π‘ Enhanced For-Loop (For-Each)
for (int num : numbers) {
System.out.println(num);
}
π Common Array Example: Find Maximum
int[] nums = {3, 7, 2, 9, 4};
int max = nums[0];
for (int n : nums) {
if (n > max) max = n;
}
System.out.println("Max: " + max);
β¨ Java Strings β Working with Text
π What is a String?
A String in Java is an object that represents a sequence of characters.
String name = "Raaz";
Java stores Strings as immutable objects β their values cannot be changed after creation.
π§ͺ Common String Methods
String s = "Hello World";
System.out.println(s.length()); // 11
System.out.println(s.toUpperCase()); // HELLO WORLD
System.out.println(s.toLowerCase()); // hello world
System.out.println(s.charAt(0)); // H
System.out.println(s.substring(6)); // World
System.out.println(s.contains("World")); // true
System.out.println(s.equals("hello")); // false
π Concatenation
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // John Doe
π Converting Between String and Numbers
String str = "100";
int num = Integer.parseInt(str); // string β int
int age = 25;
String ageStr = String.valueOf(age); // int β string
π§ͺ Practice Challenge
Create a program that counts how many vowels are in a given string:
public class VowelCounter {
public static void main(String[] args) {
String text = "Hello Java World!";
int count = 0;
for (char c : text.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) != -1) {
count++;
}
}
System.out.println("Vowel count: " + count);
}
}
β What You Learned
- Arrays are used to store multiple values of the same type
- Looping through arrays and finding data
- Strings are powerful and immutable
- Common string methods and conversions