Strings in Java
This article contains information on strings, the String class, and how to handle text values in Java.
There are 2 ways to use and manipulate text data:
As string literals.
Using the
String
class.
String literal
We can declare a string directly. The variable containing the string data has the type String
. When a string is declared like this, it's a string literal. It's literally a string, not code. A string is always written in double quotes "
Example:
class Strings {
public static void main(String args[]) {
String greeting;
greeting = "Hello,";
System.out.println(greeting + " java");
}
}
String
class
In Java, classes contain methods specific to that class and can be used to make objects defined by the class.
The String
class is no different: it provides some methods that are useful for Strings
, and it defines a String
data type that you can use to make string objects i.e. individual strings.
Let’s look at the methods first.
The String
class is contained somewhere in a Java file called String.java
. The in-built java.lang.String class provides a lot of built-in static methods that are used to manipulate strings in Java. You can call a static method of a class like this: Classname.methodname()
e.g. String.charAt()
Static methods do not need access to a particular string object’s data. The static charAt()
method takes a parameter that is not a String
, and creates a String
. Static methods are just like functions in Javascript, C, or Python. Java just uses classes to organize these functions.
Usually, before using the static methods of a class, you need to import that class, but String
is built-in so you don't need to import it.
Static method
Let's look at one static method. charAt()
takes in a single parameter, an int
. It then returns the character value (char
) at that particular index.
Example:
class StaticMethodExample {
public static void main(String args[]) {
String str = "Hello, Java";
char result = str.charAt(8);
System.out.println(result);
}
}
String
objects.
A class in Java allows you to create objects of that class. An object stores values. For a String
, it can store each character value (char
) in the string or the length of the string. Some things you can do with objects are:
Declare a variable to store a reference to an object of the class eg
String str
.Create a new object of that type:
str = "Showwcase";
Note:Strings
are special in Java; other types of objects are created using special method calls.Access or change data from the object, using dot notation to get at object variables.
Call non-static methods on an object; these methods have access to the data within an object:
System.out.println(str.toLowerCase());
Example:
class StringObjects {
public static void main(String[] args) {
String str;
str = "ShowwCase Mafia";
System.out.println(str.length());
System.out.println(str.toLowerCase());
System.out.println("The character at index 11 is: " + s.charAt(11));
}
}
Non-static methods require a string as input, and instead of passing that string as a parameter, dot-notation is used: str.toLowerCase()
. It’s possible that there might be other methods named toLowerCase()
out there. However, Java knows which method to call because Java knows that str
is a String
, so Java looks in String.java
for the method.
Difference between String
and char
Although the String
data type is built-in, the String
data type is not primitive: it is defined by a class, with methods and an internal representation defined by that class.
Examples of primitive data types are integers, floats, boolean.
char
is a primitive data type, representing a single character of text.
To distinguish between String
and char
data, Java uses single quotes for character literals and double quotes for Strings
.
Example:
class DiffExample {
public static void main(String[] args) {
char letterR = 'R';
String str = "Showwcase Mafia";
char randomLetter = str.charAt(12);
System.out.println(letterR + randomLetter);
}
}
The code above prints out 184.
The +
operator concatenates strings, but characters are internally represented using numbers, with a code called Unicode, so the +
operator adds the two up and returns an int
.
However, you can concatenate a character to a string easily with +
, since the +
operator converts both operands to strings if one of the operands is a string.
String
immutability
In Java, strings are immutable. This means that once a string is created, its contents cannot be changed. This is in contrast to primitive types, such as integers and floats, whose values can be changed.
Variables do not actually hold objects but references to objects. A reference may be loosely thought of as the address of the data storing the object in memory.
You can safely pass a reference to a string to a method without worrying that the String
will be changed. Notice that the toLowerCase()
method we saw above does not change the string: it just creates a new string that is lowercased and returns the result.
If strings were mutable, it would be possible for a method to accidentally change the contents of a string that was passed to it. This could lead to bugs and security vulnerabilities. This improves the safety and security of the software you write.
Another reason for immutability is to improve performance. When a string is immutable, the Java compiler can optimize the code that uses it. This can lead to faster execution times.
There are a few ways to work around the limitations of immutable strings. One way is to use the StringBuffer
class. The StringBuffer
class allows you to create mutable strings. However, it is important to note that StringBuffer
objects are not thread-safe. This means that they cannot be used safely in multithreaded applications.
Another way to work around the limitations of immutable strings is to use regular expressions. Regular expressions allow you to search for and replace text within a string. This can be useful for tasks such as formatting text or removing unwanted characters.
Overall, the immutability of strings in Java is a design decision that has both benefits and drawbacks. It is important to understand these benefits and drawbacks in order to make informed decisions about how to use strings in your code.
Conclusion
Knowing how to use and manipulate strings is a critical skill for developers to have. I hope you now have a better understanding of how you can work with strings in your Java programs. Feel free to reach out if you have any questions or comments. Happy coding! 🎉