web
 

Java Strings Class


Strings are a sequence of characters.



Strings

String greeting = "Hello Java!";
compiler creates a String object with its value in this case, "Hello Java!'.
The String class has 11 constructors that allow you to provide the initial value of the string using array of characters.
Example
public class StringDemo {

   public static void main(String args[]) {
      char[] finalArray = { 'j', 'a', 'v', 'a', '!', '.' };
      String finalString = new String(finalArray);  
      System.out.println( finalString );
   }
}

Run example »
output
java!.

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method.which returns the number of characters contained in the string object.

Example

public class StringDemo {

   public static void main(String args[]) {
      String palindrome = "ohh look at this face";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}


output String Length is : 21

Concatenating Strings

a method for concatenating two strings −
string1.concat(string2);
You can also use the concat() method with string literals, as in −
"My name is ".concat("Jhonson");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " Java" + "!"
which results in −
"Hello, Java!"
see this example

Example

 

public class StringDemo {

   public static void main(String args[]) {
      String string1 = "look at this ";
      System.out.println("ohh " + string1 + " face");
   }
}


OUTPUT
ohh look at this  face



Format Strings

The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of
System.out.printf("The value of the float variable is " +
                  "%f, while the value of the integer " +
                  "variable is %d, and the string " +
                  "is %s", floatVar, intVar, stringVar);
you can also write
String fs;
fs = String.format("The value of the float variable is " +
                   "%f, while the value of the integer " +
                   "variable is %d, and the string " +
                   "is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String method