- The String data type is used to store a sequence or array of characters (text). But in Java, a string is an object that represents an array or sequence of characters.
- The java.lang.String is the class is used for creating a string object.
- String literals should be enclosed within double-quotes. The difference between a character array and a string is that in the string a special character ‘\0’ is present
- Strings are immutable. This means that it is not possible to change the values of the characters within a String.
String <String_variable_name> = “<sequence_of_strings>"
Two ways of creating string:
- using string literal
String myString = “Hello World” - using new keyword
String myLine = **new** String(“Hello World!!!”);
String methods:
String word = "Hello world";
// String methods
// character at a given indes
System.out.println(word.charAt(0)); // H
// length of the string
System.out.println(word.length()); // 11
// substring
System.out.println(word.substring(2,7); // llo w
// get index of a character
System.out.println(word.indexOf('l'); // 2
System.out.println(word.indexOf('a'); // -1
System.out.println(word.indexOf("world"); // 6
System.out.println(word.indexOf("mello"); // -1
System.out.println(word.startsWith("hello"); // true
// compareT0 => -ve (smaller) 0 (equal) +ve (greater)
System.out.println(word.compareTo("abc")); // +ve
System.out.println("a".compareTo("b")); // -ve
System.out.println("b".compareTo("b")); // 0
// split operation
String[] arr = "hello there,Bob".split(" "); //["hello","there,Bob"]
// split with multiple delimiters separate with pipe "|" operator
String[] arr1 = "hello there,Bob".split(" |,");// ["hello", "there", "Bob"]
// for using dot (.) as a delimiter. use \\.
String t = "Hello,strings can be fun. They have many uses.";
String[] result = t.split(",| |\\. |\\."); // ["Hello", "strings", "can", "be", "fun", "They", "have", "many", "uses"]Formatting String.
| Specifier | Value |
|---|---|
| %b | boolean |
| %c | character |
| %d | decimal integer |
| %f | float |
| %e | number in scientific notation |
| %s | string |
String newStr = String.format("you owe me $%f",200.54f);
System.out.println(newStr);
System.out.printf("you owe me $%.2f",345.44f);