Many programs process text not numbers. Text consists of characters: letters, numbers, punctuation, spaces and so on. A String is a sequence of characters.
The String Type
You can declare variables that hold strings:
String name = "Harry";
name: String variable
"Harry" : string literal
The number of characters in a string is called the length of the string.
You can compute the length of a string with the length method.
int n = name.length();
A string of length 0 is called the empty string. It contains no characters and is written as "".
Concatenation
Use the + operator to concatenate strings, that is to put them together to yield a longer string.
String fName = "Harry";
String lName = "Potter";
String fullName = fName + " " + lName; // will return "Harry Potter"
When the expression to the left or the right of a + operator is a string, the other one is automatically forced to become a string as well, and both strings are concatenated.
String countryAndCode = "India" + " " + 91;
String Input
You can read string from console:
Use the next method of the Scanner class to read a string containing a single word.
String name = in.next();
Escape sequences
To include a quotation mark in a literal string, precede it with a backslash(\).
Ex: String quoteString = "He said, \"Hello\" ";
\n - new line character
\r - carriage return
Strings and Characters
Strings are a sequence of unicode characters. In Java, a character is a value of type char. Characters have numeric values.
'H' - character literal
"H" - string literal
The charAt method returns a char value from string. The first string position is labeled at 0, the second one 1, and so on.
String name = "Harry";
char start = name.charAt(0); // returns H
char last = name.charAt(4); // returns y
Substrings
Once you have a string, you can extract substrings by using the substring() method.
Syntax: str.substring(start, pastEnd);
returns a string that is made up of the characters in the string str, starting at position start, and containing all characters up to, but not including, the position pastEnd.
Ex:
String greeting = "Hello World!";
String sub = greeting.substring(0, 5); // returns Hello
If you omit the end position when calling the substring method, then all characters from the starting position to the end of the string are copied.
Note: The last character in string has position str.length() - 1
No comments:
Post a Comment