Java String Class Tutorial

The Java String class serves as a representation of character strings. It is part of the java.lang package and offers a wide range of methods to manipulate strings. Unlike primitive data types such as int and long, Java String is an object type that represents a sequence of char values. Essentially, it can be viewed as an array of characters, functioning similarly to a Java string, enabling various operations on text-based data.

char[] chr={'W','E','L','C','O','M','E'};

How to create a Java String object?

There are two ways to create Java String object:

  1. By string literal
  2. By new keyword

String Literal

Java String literal is created by using double quotes.

String s="Java Tutorial";

By using new keyword

String str = new String("Java Tutorial");

Difference between String literal and New String object

When you use the constructor new String("Java Tutorial"), it creates a distinct and separate instance of a String object, which is unique and refers to a different memory location. It becomes an independent instance of the java.lang.String class. On the other hand, when you use the assignment String s = "Java Tutorial", the string may be taken from the string constant pool in Java heap memory if an identical string is available. This concept is known as string interning, where string literals are stored in a pool to optimize memory usage and enhance performance. In this way, string literals can be reused, making it a Java language feature.

Example:
String a = "JAVA"; String b = "JAVA"; System.out.println(a == b);

The output of the above program is 'true' .

String c = new String("JAVA"); String d = new String("JAVA"); System.out.println(c == d);

The output of the above program is 'false' .

Using string literal notation whenever possible is recommended because it improves code readability and allows the compiler to optimize the program's performance. However, when passing a null argument to a String constructor or method, it can lead to a NullPointerException being thrown, so it is crucial to handle null values appropriately.

In terms of good coding practice, it's advisable not to use the == operator to check for String equality since it compares references rather than the actual content of the strings. Instead, you should use the .equals() method, which compares the content of the strings, ensuring accurate comparison results. Following these best practices contributes to writing robust and reliable Java code.

First-Class Objects

Strings are indeed considered first-class objects. This means that strings are treated as full-fledged objects in the language, and they can be passed as arguments, returned from methods, assigned to variables, and stored in data structures just like any other object.

On the other hand, in programming languages like 'C' and 'C++', strings are conventionally represented as null-terminated arrays of characters. In these languages, there is no built-in string data type like in Java. Instead, a string is essentially a sequence of characters stored in an array, terminated with a null character ('\0') to indicate the end of the string. But in Java, strings are first-class objects and it provides several advantages to the developers, they are:

  1. The manner in which you obtain strings and elements of strings is consistent across all strings and all systems.
  2. Because of the programming interface for the String classes is well-defined, Java Strings function predictably every time.
  3. The Java String class does extensive runtime checking for boundary conditions and catches errors.

Thread-safe

Strings in Java are immutable, meaning once a string object is created, its state cannot be changed. When you perform operations on a string, you are creating new string objects rather than modifying the original one. This immutability ensures that strings maintain their values throughout their lifetime, making them thread-safe and suitable for use in multi-threaded environments. Since no thread can modify the content of a string, there is no risk of data corruption or inconsistencies in concurrent scenarios, contributing to a more reliable and stable application.

Escape Characters

Strings literals in Java accepts a set of escape characters which are translated into special characters in the created String. They are:

\\ Translated into a single \ character \t Translated into a single tab character \r Translated into a single carriage return character \n Translated into a single new line character
Example:
String path = "D:\\Java\\JavaProjects";

Innstead of '\' use '\\'

String str = "\tJava Tutorial\r\n";

The above String starts with a tab character and ends with a carriage return and a new line character.

String is immutable or final

Because String is immutable or final , there are several advantage in programming.

  1. String is safe to use in multi-threading programming and developers don't need any synchronization.
  2. Because of String immutability, string pool is possible.
  3. Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

Conclusion

While Java treats strings as first-class objects with built-in string handling capabilities, 'C' and 'C++' use null-terminated character arrays to represent strings, without a dedicated string data type.