Strings in Java
In this guide, we’ll explore how to handle text in Java using the String
class. Contrary to what one might assume, String
is not a primitive data type but a specialized class designed to work with text, offering unique features for efficient text management.
The String
class is part of the java.lang
package and is in the JRE and JDK by default. A String
object’s default value is null
, consistent with the initialization behavior of all non-primitive types in Java.
Here’s a simple example:
public class StringObjects {
public static void main(String[] args) {
String text = "Learning Java!";
String numbers = "12345";
String character = "a";
}
}
Key Notes:
- Strings are initialized with double quotes (
"
), unlike the char type, which uses single quotes ('
). - Strings in Java are defined using the keyword
String
, which always starts with an uppercase "S."
To combine multiple strings, use the concatenation operator (+
), as shown below:
public class StringObjects {
public static void main(String[] args) {
String text = "Learning Java!";
String numbers = "12345";
String character = "a";
String finalText = text + " " + numbers + " " + character;
System.out.println(finalText);
}
}
To reassign a new value to a string, you can simply overwrite it:
public class StringObjects {
public static void main(String[] args) {
String text = "Learning Java!";
text = "Now learning C#!";
System.out.println(text);
}
}
Arrays in Java
Arrays are data structures that store collections of elements, all of the same type. The size of an array must be defined at creation, and each element within the array is accessed via its index.
Here’s an example of an integer array:
public class Arrays {
public static void main(String[] args) {
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println(numbers[2]); // Outputs 30
}
}
Key Notes:
- Arrays in Java start at index
0
and end atlength - 1
. - If you try to access an index beyond the array’s bounds (e.g.,
numbers[5]
in the example above), you’ll encounter anArrayIndexOutOfBoundsException
.
Multidimensional Arrays and More
Java also supports multidimensional arrays, often referred to as matrices. Here’s an example:
public class MultiDimensionalArrays {
public static void main(String[] args) {
int[][] matrix = new int[2][3];
matrix[0][0] = 5;
matrix[1][2] = 15;
String[] words = {"Learning", "Java", "is", "fun!"};
System.out.println(matrix[0][0]); // Outputs 5
System.out.println(matrix[1][2]); // Outputs 15
System.out.println(words[0] + " " + words[1]); // Outputs "Learning Java"
}
}
Top comments (0)