Java Basics: Characters and Strings

The char data type is used to represent a single character. Character literals are enclosed in single quotes. ``` char a = 'A'; char b = '4'; char c = '\u041'; // Unicode for A


String literals must be enclosed in double quotes, while character literals are single characters enclosed in single quotes. Thus, "A" is a string, and 'A' is a character. ### 1.1 Encoding

Common character ASCII codes: <table> <thead> <tr> <th>Character</th> <th>Decimal Value</th> <th>Unicode Value</th> </tr> </thead> <tbody> <tr> <td>'0'~'9'</td> <td>48~57</td> <td>u0030~u0039</td> </tr> <tr> <td>'A'~'Z'</td> <td>65~90</td> <td>u0041~u005A</td> </tr> <tr> <td>'a'~'z'</td> <td>97~122</td> <td>u0061~u007A</td> </tr> </tbody></table>

Increment and decrement operators can also be applied to char variables, resulting in the preceding or following Unicode character. ### 1.2 Escape Characters

<table> <thead> <tr> <th>Escape Sequence</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>\\b</td> <td>Backspace</td> </tr> <tr> <td>\\t</td> <td>Tab</td> </tr> <tr> <td>\\n</td> <td>Newline</td> </tr> <tr> <td>\\f</td> <td>Form feed</td> </tr> <tr> <td>\\r</td> <td>Carriage return</td> </tr> <tr> <td>\\\\</td> <td>Backslash</td> </tr> <tr> <td>"</td> <td>Double quote</td> </tr> </tbody></table>

### 1.3 Type Conversion for char

// When converting an integer to char, only the lower 16 bits are used. char ch = (char)0XAB0041; // 0041, which is A

// When converting a floating point value to char, it first converts to int, then to char. char ch = (char)65.25; // 65, which is A

// When converting a char to a numeric type, the Unicode of the character is converted. int i = (int)'A'; // 65

// If the result fits into the target variable, implicit conversion can be used; otherwise, explicit conversion is required. byte b = 'a'; int i = 'a';

// However, since the Unicode code \uFFF4 exceeds the byte range, the following conversion is incorrect: byte b = '\uFFF4'; // To force assignment, use explicit conversion. byte b = (byte)'\uFFF4';


All numeric operators can be used with char operands. If another operand is a number or a character, the char operand is automatically converted to a number. If another operand is a string, the character is concatenated with the string. ### 1.4 Comparing Characters

Two characters can be compared using relational operators, similar to comparing numbers. This is done by comparing their Unicode values. ```
if(ch >= 'A' && ch <= 'Z')
  System.out.println(ch + " is an uppercase letter");
else if(ch >= 'a' && ch <= 'z')
  System.out.println(ch + " is a lowercase letter");
else if(ch >= '0' && ch <= '9')
  System.out.println(ch + " is a numeric character");

1.5 The Character Class

  1. String Type

The char type represents a single character. To represent a sequence of characters, use the String data type. ``` String message = "Hello World";


### 2.1 Common Methods for String Objects:

<table> <thead> <tr> <th>Instance Method (called from a specific string instance)</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>length()</td> <td>Returns the number of characters in the string</td> </tr> <tr> <td>charAt(index)</td> <td>Returns the character at the specified position in the string</td> </tr> <tr> <td>concat(s1)</td> <td>Concatenates this string with the string s1, returning a new string</td> </tr> <tr> <td>toUpperCase()</td> <td>Returns a new string with all letters capitalized</td> </tr> <tr> <td>toLowerCase()</td> <td>Returns a new string with all letters lowercased</td> </tr> <tr> <td>trim()</td> <td>Returns a new string with leading and trailing whitespace removed</td> </tr> </tbody></table>

In addition to the concat method, the plus (+) operator can be used to concatenate two or more strings. For the plus operator to work, atleast one operand must be a string. If one operand is not a string (e.g., an int or char), the non-string value is converted to a string and concatenated with the other string. If neither operand is a string, the plus operator acts as an addition operator. The enhanced += operator can also be used for string concatenation. ### 2.2 Reading a String from the Console

To read a string from the console, call the next() method on a Scanner object. ```
Scanner input = new Scanner(System.in);
String s1 = input.next();

The next() method reads a string ending with a whitespace character (' ', '\t', '\f', '\r', or '\n'). The nextLine() method reads a string ending with a newline character. - next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble() are called token-based input because they read individual elements separated by whitespace. - nextLine() is called line-based input, reading a string ending with a newline. - Avoid errors by not using line-based input after token-based input. ### 2.3 Reading a Character from the Console

To read a character from the console, call nextLine() to read a string, then call charAt(0) on the string to return a character. ``` Scanner input = new Scanner(System.in); String s = input.nextLine(); char ch = s.charAt(0);


### 2.4 Comparing Strings

<table> <thead> <tr> <th>Method</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>equals(s1)</td> <td>Returns true if the string equals s1</td> </tr> <tr> <td>equalsIgnoreCase(s1)</td> <td>Returns true if the string equals s1, ignoring case</td> </tr> <tr> <td>compareTo(s1)</td> <td>Returns an integer greater than, equal to, or less than zero, indicating whether the string is greater than, equal to, or less than s1</td> </tr> <tr> <td>compareToIgnoreCase(s1)</td> <td>Same as compare, but the comparison is case-insensitive</td> </tr> <tr> <td>startsWith(prefix)</td> <td>Returns true if the string starts with a specific prefix</td> </tr> <tr> <td>endsWith(suffix)</td> <td>Returns true if the string ends with a specific suffix</td> </tr> <tr> <td>contains(s1)</td> <td>Returns true if s1 is a substring of the string</td> </tr> </tbody></table>

- The == operator only checks if string1 and string2 refer to the same object, not if their contents are the same. - The actual value returned by the compareTo method is based on the difference between the first different characters in s1 and s2. For example, if s1 is "abc" and s2 is "abg", then s1.compareTo(s2) returns -4. First, compare the first characters (a and a). Since they are equal, compare the second characters (b and b). They are also equal, so compare the third characters (c and g). Since c is 4 less than g, the result is -4. - Using operators like &gt;, &gt;=, &lt;, or &lt;= to compare two strings results in a syntax error. ### 2.5 Substrings and Characters

<table> <thead> <tr> <th>Method</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>substring(beginIndex)</td> <td>Returns a substring starting from the specified index to the end of the string</td> </tr> <tr> <td>substring(beginIndex, endIndex)</td> <td>Returns a substring starting from the specified beginIndex to the character before endIndex (if beginIndex == endIndex, returns an empty string. If beginIndex &gt; endIndex, a runtime error occurs.)</td> </tr> <tr> <td>indexOf(ch)</td> <td>Returns the index of the first occurrence of ch. Returns -1 if no match is found.</td> </tr> <tr> <td>indexOf(ch, fromIndex)</td> <td>Returns the index of the first occurrence of ch after fromIndex. Returns -1 if no match is found.</td> </tr> <tr> <td>indexOf(s)</td> <td>Returns the index of the first occurrence of s. Returns -1 if no match is found.</td> </tr> <tr> <td>indexOf(s, fromIndex)</td> <td>Returns the index of the first occurrence of s after fromIndex. Returns -1 if no match is found.</td> </tr> <tr> <td>lastIndexOf(ch)</td> <td>Returns the index of the last occurrence of ch. Returns -1 if no match is found.</td> </tr> <tr> <td>lastIndexOf(ch, fromIndex)</td> <td>Returns the index of the last occurrence of ch before fromIndex. Returns -1 if no match is found.</td> </tr> <tr> <td>lastIndexOf(s)</td> <td>Returns the index of the last occurrence of s. Returns -1 if no match is found.</td> </tr> <tr> <td>lastIndexOf(s, fromIndex)</td> <td>Returns the index of the last occurrence of s before fromIndex. Returns -1 if no match is found.</td> </tr> </tbody></table>

### 2.6 String Conversinos

- A numeric string can be converted to a number. If the string is not numeric, the conversion will cause a runtime error. - To convert a string to an int, use Integer.parseInt. To convert to a double, use Double.parseDouble. ```
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
  • If the string is not numeric, the conversion will cause a runtime error. The Integer and Double classes are in the java.lang package and are automatically imported. - To convert a number to a string, simply use the string concatenation operator with an empty string. ``` String s = number + "";

### 2.7 Formatting Console Output

You can use System.out.printf to display formatted output on the console. ```
double amount = 12618.98;
double interestRate = 0.0013;
double interest = amount * interestRate;
System.out.printf("Interest is $ %4.2f", interest);

The f in printf stands for format, indicating that the method will print in a specific format. The syntax for calling this method is: ``` System.out.printf(format, item1, item2, ..., itemk);


Format specifiers determine how each item should be displayed. Items can be numeric, character, boolean, or string values. Simple format specifiers start with a percent sign (%). <table> <thead> <tr> <th>Specifier</th> <th>Output</th> </tr> </thead> <tbody> <tr> <td>%b</td> <td>Boolean value</td> </tr> <tr> <td>%c</td> <td>Character</td> </tr> <tr> <td>%d</td> <td>Decimal integer</td> </tr> <tr> <td>%f</td> <td>Float</td> </tr> <tr> <td>%e</td> <td>Number in scientific notation</td> </tr> <tr> <td>%s</td> <td>String</td> </tr> </tbody></table>

Examples: <table> <thead> <tr> <th>Example</th> <th>Output</th> </tr> </thead> <tbody> <tr> <td>%5c</td> <td>Prints the character with four spaces before it</td> </tr> <tr> <td>%6b</td> <td>Prints the boolean value with one space before false and two spaces before true</td> </tr> <tr> <td>%5d</td> <td>Prints the integer with a minimum width of 5. If the number has fewer than 5 digits, spaces are added before the number. If the number has more than 5 digits, the width increases automatically</td> </tr> <tr> <td>%10.2f</td> <td>Prints the float with a minimum width of 10, including the decimal point and two decimal places. Seven digits are allocated before the decimal point. If the number has fewer than seven digits before the decimal, spaces are added before the number. If the number has more than seven digits, the width increases automatically</td> </tr> <tr> <td>%10.2e</td> <td>Prints the float with a minimum width of 10, including the decimal point, two decimal places, and the exponent part. If the number of digits is less than 10, spaces are added before the number</td> </tr> <tr> <td>%12s</td> <td>Prints the string with a minimum width of 12 characters. If the string has fewer than 12 characters, spaces are added before the string. If the string has more than 12 characters, the width increases automatically</td> </tr> </tbody></table>

// To display a number with commas, add a comma before the numeric specifier. System.out.printf("%,8d%,10.1f\n", 12345678, 12345678.263); // 12,345,678 12,345.678.3

// To pad with zeros instead of spaces, add a 0 before the numeric specifier. System.out.printf("%08d %08.1f\n", 1234, 5.63); // 00001234 000005.6

// By default, output is right-aligned. Add a minus sign (-) in the format specifier to left-align the item in the field. System.out.printf("%-8d%-8s%-8.1fn", 1234, "Java", 5.63); System.out.printf("%8d%8s%8.1f\n", 1234, "Java", 5.63); //1234 Java 5.6
// 1234 Java 5.6

// The item must strictly match the type of the format specifier. The item corresponding to %f or %e must be a float value, such as 40.0, not 40. Therefore, an int variable cannot match %f or %e. Use %.2f to specify a float with two decimal places, and %0.2f is incorrect. // Use %% to output a literal % in the format string.


</div></div>

Tags: java char string unicode escape-sequence

Posted on Fri, 15 May 2026 15:18:46 +0000 by davey_b_