Tuesday, December 29, 2009

Strings in Java

The String class, is one of the special classes in Java. It's is high utility class.

A String object can be created in many ways, with the help of the many constructors of String class. The most simple methods are:
String greeting = "Hello world!";

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);

Some useful features of String are:
  • String Length: The length of String or the number of characters in the String object can be known easily with help of length() method.
  • charAt() method: The charAt(int index) is used to return the character at a specific location in a String.
  • getChars() method: The getChars() method is used to convert a string or substring into a character array.
  • Concatenating Strings: Two strings can be joined to one string in the following ways:
    1. String1.concat(String2);
    2. "My name is ".concat("Rumplestiltskin");
    3. "Hello," + " world" + "!"
  • Creating Format Strings: The String class has a static format() method, that allows you to create a formatted string that can be re-used.
    Example:
       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);


tutorials

No comments:

Post a Comment