The string class in Java is not just a mere container for characters. It's designed for efficient text manipulation, packed with built-in methods that elevate it beyond basic character arrays.
To peek at the String class's structure, open IntelliJ IDEA, hit 'Shift' twice, search for 'String', and voila! You're greeted with a plethora of methods like length()
, charAt()
, and concat()
that showcase its power in text manipulation.
String firstName = "John";
The text "John", encased in double quotes, is our string literal, recognized by Java as a string. This principle holds true for initializing strings and when they're utilized within methods.
Concatenation is about merging strings, a basic yet essential skill. Let's concatenate the first name "John" and last name "Mark", ensuring a space in between for a full name.
String firstName = "John";
String lastName = "Mark";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
This operation yields 'John Mark', a simple demonstration of concatenation in action.
Creating strings with the 'new' keyword signals Java to explicitly forge a new string object, diverging from direct string literal assignment.
String firstName = new String("John");
This method is a clear nod to object-oriented programming, explicitly creating a distinct string object.
Java handles memory differently based on whether you use string literals or the 'new' keyword. Using literals allows for string pooling, a memory-efficient technique. Conversely, 'new' creates a new string object every time, even if an identical string exists in the pool, affecting performance and memory usage.