Friday, 2 August 2013

Java Strings

Java strings are objects designed to represent a sequence of characters. Because character strings are commonly used in programs, Java supports the ability to declare String constants and perform concatenation of Strings directly without requiring access to methods of the String class. This additional support provided for Java Strings allows programmers to use Strings in a similar manner as other common programming languages.

Creating a String

The simplest method to create a String object is to enclose the string literal in quotes and assign the value to a String object. Creation of a String through assignment does not require the use of the new operator, for example
String str = "abc";
String language = "Java";

Alternatively, String objects can be created through constructors. The following constructors are supported:

public String()

Constructs a new String with the value "" containing no characters. The value is not null.

public String( String value )

Constructs a new String that contains the same sequence of characters as the specified String argument.

public String( char[] value )

Constructs a new String containing the same sequence of characters contained in the character array argument.

Differences between String and StringBuffer in Java

Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method.

No comments:

Post a Comment