DEV Community

Cover image for Java: 4 ways to create a String! 💡
Raksha Kannusami
Raksha Kannusami

Posted on

Java: 4 ways to create a String! 💡

The String Datatype:

A string is nothing but a collection of characters. In java, Strings are immutable. Immutable simply means unmodifiable or unchangeable. Once a string object is created its data or state can't be changed but a new string object is created.

You can create a String using 4 ways in Java:

1. Using a character array

Character Array is a sequential collection of data type char.

char[] array = {'s','t','r','i','n','g'};
Enter fullscreen mode Exit fullscreen mode

2. Using String class

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

String str = "string";
Enter fullscreen mode Exit fullscreen mode

3. Using StringBuffer

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

StringBuffer  str = new StringBuffer("string");
Enter fullscreen mode Exit fullscreen mode

4. Using StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

StringBuilder str = new StringBuilder("string");
Enter fullscreen mode Exit fullscreen mode

Now you know how to create a String, In the upcoming article I will be covering all the String methods that can be used to format Strings.

... To be continued 🎉
keep learning, keep growing 💖

Discussion (1)

Collapse
ip127001 profile image
Rohit Kumawat

Does immutable means I can't set value of name[Below code]?

   String name = "Rick";
   name = "Morty";

If not, can you explain immutability in String via an example? That would be helpful.

Thanks