In this post we're going to talk about the strings in Java. A string, in Java, is an object that represents a sequence of characters. Although we use it like a primitive data. Actually, it is a class from the java.lang
packet.
String variable = "Hello, world!";
📌 Main Features.
They are immutable: When we create a string, we can't modify it. Methods like
toUpperCase()
orreplace()
don't change the original variable; they make a new one.Simplified syntax: You can create a string directly with two quotes, and then Java automatically makes it into an
string
object.Intern pool: Java automatically saves literal strings in a "pool" to save memory. If two strings have the same value, point at the same object (if you use literals).
In Java, pool are like a memory special place where are stored reutilizable objects, to not make an unnecessary new instance.
So, as we recently saw, in Java you have two different ways to make a string.
Literals:
String literalString = "Hello";
With new
:
String newString = new String("Hello");
This second way forces the creation of a new object, even if a similar one already exists in a pool.
🔧 Utils methods.
String text = “Java is cool.”
text.length(); // Returns length
text.charAt(2); // Returns character at index 2
text.substring(5); // Returns “it's cool”.
text.contains(“cool”); // true
text.equals(“JAVA”); // false (case sensitive)
text.equalsIgnoreCase(“JAVA”); // true
text.toUpperCase(); // “JAVA IS COOL”; // “JAVA IS COOL”.
text.replace(“great”, “powerful”); // “Java is powerful”.
Compare Strings
Be careful!
Using ==
compares references, not content:
String a = “hello”;
String b = new String(“hello”);
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
🔄 Concatenation
String name = “Juan”;
String salutation = “Hello ” + name; // Concatenation with +
Or with the concat() method:
String new = “Hello ‘.concat(’John”);
📏 Efficiency: StringBuilder and StringBuffer
When you need to modify a string many times (for example, in loops), it is better to use:
StringBuilder
: unsynchronized (faster on a single thread).StringBuffer
: synchronized (for threads)
StringBuilder sb = new StringBuilder(“Hello”);
sb.append(“ world”); // “Hello world”.
Strings in Java are more than just sequences of characters—they are powerful, immutable objects that come with a rich set of methods and memory optimization mechanisms like the String pool.
Understanding how they work, how they are created, and how to manipulate them efficiently is fundamental to writing clean and effective Java code.
Whether you're using simple literals or working with StringBuilder
for performance, mastering Strings is an essential step in your Java journey.
See you!
🐱👤
Top comments (0)