character
Generally, when we process characters, we use the original data type char.
Example
char ch = 'a';// Unicode for uppercase Greek omega characterchar uniChar = '/u039A'; // an array of charschar[] charArray ={ 'a', 'b', 'c', 'd', 'e' };However, in development, we will encounter situations where we need to use objects instead of primitive data types. To meet this need. Java provides a wrapper class Character for the original data type char.
The Character class provides a series of useful classes (for example: static classes). You can create a Character object with the help of the Character constructor.
Character ch = new Character('a');The Java compiler will also be able to create a Character object for you in some cases. For example: If you transfer a raw char to a method that can be expected, the compiler will automatically convert the char to a Character for you. If the conversion takes place in the opposite direction, this feature is called automatic packing or unboxing.
Example
// Here following primitive char 'a'// is boxed into the Character object chCharacter ch = 'a';// Here primitive 'x' is boxed for method test,// return is unboxed to char 'c'char c = test('x'); Escape sequence
The character with a backslash (/) before is an escape sequence and has special meaning for the compiler.
Line breaks (/n) are often used in the System.out.println() statement, and line breaks after strings are printed.
The following table shows the Java escape sequence:
| Escape sequence | describe |
|---|---|
| /t | Insert a label in the text. |
| /b | Insert a backspace into the text. |
| /n | Insert a newline character into the text. |
| /r | Insert a carriage return in the text. |
| /f | Insert a page change into the text. |
| /' | Insert a single quote character into the text. |
| // | Insert a backslash character into the text. |
Example
If you want to put quotes inside, you must use escape sequences, /" , quote internally:
public class Test { public static void main(String args[]) { System.out.println("She said /"Hello!/" to me."); }}This will produce the following results:
She said "Hello!" to me.
Character Methods The following list is an important example method that implements all subclasses of the Character class:
| SN | Method Description |
|---|---|
| 1 | isLetter() Determine the specific char value is a letter |
| 2 | isDigit() Determine the specific char value is a number |
| 3 | isWhitespace() Determine the specific char value is a space |
| 4 | isUpperCase() Determine the specific char value is a capital letter |
| 5 | isLowerCase() Determine the specific char value is a lowercase letter |
| 6 | toUpperCase() Returns the capitalization form of the specified character value |
| 7 | toLowerCase() Returns the lowercase form of the specified character value |
| 8 | toString() Returns a String object representing the specified character value, that is, a character string |
String
String, which is widely used in Java programming, is a sequence of characters. In the Java programming language, strings are objects.
The Java platform provides String classes to create and manipulate strings.
Create a string
The most direct way to create a string is written like this:
String greeting = "Hello world!";
When you create a string, the compiler creates a String object with its value in this case, such as: "Hello world!'.
Any other object can be created by using the new keyword and by constructor. The String class has 11 constructors that provide initial values using different types of strings, such as an array of characters.
public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println( helloString ); }}This will produce the following results:
hello.
Note The String class is immutable, so once a String object is created, it cannot be changed. If you need to modify a string with a large number of characters, you should use the StringBuffer & StringBuilder class.
String length
The method used to obtain information about an object is called an access method. One access method that can be used with a string is length() , which returns the number of characters contained in a string object.
After the following two lines of code are executed, len equals 17:
public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); }}This will produce the following results:
String Length is : 17
Connection string
The String class includes methods for concatenating two strings:
string1.concat(string2);
This returns a new string, which adds string2 at the end of string1. You can also use the concat() method to concatenate strings, such as:
"My name is ".concat("Zara");Strings are more often concatenated with the "+" operator, such as:
"Hello," + " world" + "!"
This will produce:
"Hello, world!"
Take a look at the following example:
public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); }}This will produce the following results:
Dot saw I was Tod
Create a formatted string
There are already printf() and format() methods to print out the output format numbers. The String class has an equivalent method format(), which returns a String object instead of a PrintStream object.
The static format() method using strings allows the creation of reusable formatted strings instead of a one-time print statement. For example, if instead of the following method:
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 write this way:
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
Here is a list of methods supported by the String class:
| SN | Methods and descriptions |
|---|---|
| 1 | char charAt(int index) Returns the character at the specified index. |
| 2 | int compareTo(Object o) Compare this string to another object. |
| 3 | int compareTo(String anotherString) Compare the dictionary order of two strings. |
| 4 | int compareToIgnoreCase(String str) Compare the two strings in dictionary order, case-insensitive differences. |
| 5 | String concat(String str) Concatenate the specified string to the end of this string. |
| 6 | boolean contentEquals(StringBuffer sb) Returns true if and only if the string represents the same character sequence as the specified StringBuffer. |
| 7 | static String copyValueOf(char[] data) Returns a string representing the sequence of characters in the specified array. |
| 8 | static String copyValueOf(char[] data, int offset, int count) Returns a string representing the sequence of characters in the specified array. |
| 9 | boolean endsWith(String suffix) Tests whether this string ends with the specified suffix. |
| 10 | boolean equals(Object anObject) Compare this string to the specified object. |
| 11 | boolean equalsIgnoreCase(String anotherString) Compare this string to another string, ignoring case considerations. |
| 12 | byte getBytes() Decode this String using the platform's default character set and store the result into a sequence of bytes in a new byte array. |
| 13 | byte[] getBytes(String charsetName Decodes this String byte sequence using the specified character set and stores the result to a new byte array. |
| 14 | void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copy characters from this string to the target character array. |
| 15 | int hashCode() Returns a hash code for this string. |
| 16 | int indexOf(int ch) Returns the index at which the first occurrence of the character specified in this string. |
| 17 | int indexOf(int ch, int fromIndex) Return to the first occurrence of the specified character in the index string, and start searching at the specified index. |
| 18 | int indexOf(String str) Returns the index at the first occurrence of this string's specified substring. |
| 19 | int indexOf(String str,int fromIndex) Returns the index at the first occurrence of the specified substring in this string, starting from the specified index. |
| 20 | String intern() Returns a normalized representation of a string object. |
| twenty one | int lastIndexOf(int ch) Returns the index at which the last occurrence of the specified character of this string is. |
| twenty two | int lastIndexOf(int ch, int fromIndex) Returns the index at the last occurrence of the specified character of this string, searching backwards from the specified index. |
| twenty three | int lastIndexOf(String str) Returns the index at the rightmost occurrence of this string specified substring. |
| twenty four | int lastIndexOf(String str, int fromIndex) Returns the last occurrence of the specified substring in the index string, and searches backward from the beginning of the specified index. |
| 25 | int length() Returns the length of this string. |
| 26 | boolean matches(String regex) Determines whether this string matches the given regular expression. |
| 27 | boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Test that the region of two strings is equal. |
| 28 | boolean regionMatches(int toffset, String other, int ooffset, int len) Test that both strings are equal. |
| 29 | String replace(char oldChar, char newChar) Returns the newChar replacement of oldChar all occurrences in this string to produce a new string. |
| 30 | String replaceAll(String regex, String replacement Replaces each substring whose given regular expression in this string matches the given replacement. |
| 31 | String replaceFirst(String regex, String replacement) Replace this string matches the given regular expression given replace the first substring. |
| 32 | String[] split(String regex) Split this string that is matched around the given regular expression. |
| 33 | String[] split(String regex, int limit) Split this string that is matched around the given regular expression. |
| 34 | boolean startsWith(String prefix) Tests whether this string begins with the specified prefix. |
| 35 | boolean startsWith(String prefix, int toffset) Tests whether this string starts with the specified prefix that starts with the specified index. |
| 36 | CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence, a subsequence of this sequence. |
| 37 | String substring(int beginIndex) Returns a new string, which is a substring of this string. |
| 38 | String substring(int beginIndex, int endIndex) Returns a new string, which is a substring of this string. |
| 39 | char[] toCharArray() This string is converted to a new character array. |
| 40 | String toLowerCase() Use all characters in this string to lowercase the rules of the default locale. |
| 41 | String toLowerCase(Locale locale) Use all characters in this string to lowercase the rule of the given Locale. |
| 42 | String toString() This object (it is already a string!) returns the string form (here it is itself). |
| 43 | String toUpperCase() Use the rules of the default locale to convert all characters in this String to uppercase. |
| 44 | String toUpperCase(Locale locale) Convert all characters in this String to uppercase using the rules for the given Locale. |
| 45 | String trim() Returns a copy of the string, with spaces at the beginning and end removed. |
| 46 | static String valueOf(primitive data type x) Returns the string representation of the passed data type parameter. |