An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To