Java String


The String Constructors

The String class supports several constructor. To create an empty String, call the default constructor.

String s = new String();

You will want to create a String that has the initial value. Provides different constructors to handle String classes. Starting with an array of characters to create a String.

Program
public class Main
{
	public static void main(String[] args) 
	{
		char chars[] = {'a','b','c','d'};
		String s=new String(chars);
		System.out.println(s);
	}
}
Run

String Length

The length of a string is the number of characters in it. To get this value, call the length() method.

Program
public class Main
{
	public static void main(String[] args) 
	{
		String s="Hello";
		System.out.println(s.length());
	}
}
Run

Special String Operations

Java has more special support for many string operations among the syntax of the language. These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation.

String Literals

Java mechanically constructs a String object. Thus, you'll be able to use a string literal to initialize a String object. as an example, the subsequent code fragment creates 2 equivalent strings:

Program
char c[] = {'b','c','d'};
String s = new String(c);

String s1 = "bcd"; //use string literal

String Concatenation

Java doesn't permit operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows to chain together a series of + operations.

Program
String age = "20";
String concate = "He is "+ age + " years old.";
System.out.println(concate);
Run

String Conversion and toString()

When java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf() defined by String. valueOf() is overloaded for all the primitive types and for type Object. For the primitive types, valueOf() returns a string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf() calls the toString() method on the object.

Program
public class Main
{
    String _name;
    int _roll;
    float _marks;
    Main(String name, int roll,float marks)
    {
        this._name=name;
        this._roll=roll;
        this._marks=marks;
    }
    public String toString()
    {
        return "Name: "+this._name+"\n"+"Roll: "+this._roll+"\n"+"Marks: "+this._marks;
    }
	public static void main(String[] args) 
	{
	    Main m1=new Main("chandan",1,95.05F);
	    System.out.println(m1.toString());
	}
}
Run