Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 1, 2020 01:28 pm GMT

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'};

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";

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 = StringBuffer("string");

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");

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


Original Link: https://dev.to/rakshakannu/java-4-ways-to-create-a-string-1i0o

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To