Java Arrays and Strings Explained in Depth with Examples
Java Arrays and Strings Explained in Depth
Author: Gursehbaj Singh | Blog: DevMode
Arrays and Strings are two of the most important topics in Java. They are used to store multiple values and text data. In this guide, you will learn them deeply with simple explanations and examples.
What is an Array?
An array is a collection of similar data stored in one variable.
int[] numbers = {10, 20, 30, 40, 50};
Accessing Array Elements
System.out.println(numbers[0]); // 10
System.out.println(numbers[3]); // 40
Array Using Loop
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Two-Dimensional Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
What is a String?
A String is a sequence of characters.
String name = "DevMode";
Common String Methods
String text = "Java Programming";
System.out.println(text.length());
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(text.charAt(0));
System.out.println(text.contains("Java"));
Comparing Strings
String a = "Java";
String b = "Java";
System.out.println(a.equals(b));
String Concatenation
String first = "Hello";
String second = "World";
String result = first + " " + second;
StringBuilder (Mutable String)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
System.out.println(sb.toString());
Conclusion
Arrays help you store multiple values, and Strings help you work with text. Mastering them is very important for building real Java programs.
Comments
Post a Comment