toString(): This method is available in java.lang.Character class of Java.
Approach 1: When the method does not take any argument.
Syntax:
String java.lang.Character.toString()
This method returns a String object representing this Character's value. The result is a string of length 1 whose sole component is the primitive char value represented by this Character object.
Returns: a string representation of this object.
Exceptions: NA
Java
public class CharactertoString {public static void main(String[] args) {Character c = 'a';System.out.println(c.toString());}}
Output:
a
Approach 2: When the method takes an argument of type char.
Syntax:
String java.lang.Character.toString(char c)
This method takes one argument of type char as its parameter. This method returns a String object representing the specified char. The result is a string of length1 consisting solely of the specified char.
Parameters: One parameter is required for this method.
c: the char to be converted.
Returns: the string representation of the specified char.
Exceptions: NA
Java
public class CharactertoString2 {public static void main(String[] args) {char c = 'a';System.out.println(Character.toString(c));}}
Output:
Approach 3: When the method takes an argument of type int.
Syntax:
String java.lang.Character.toString(int codePoint)
This method takes one argument of type int as its parameter. This method returns a String object representing the specified character (Unicode code point). The result is a string of length 1 or 2, consisting solely of the specified codePoint.
Parameters: One parameter is required for this method.
codePoint: the codePoint to be converted.
Returns: the string representation of the specified codePoint.
Throws:
IllegalArgumentException - if the specified codePoint is not a valid Unicode code point.
Java
public class CharactertoStringint {public static void main(String[] args) {int codePoint = 'A';System.out.println(Character.toString(codePoint));}}
Output:
Approach 3.1: IllegalArgumentException
Java
public class CharactertoStringint {public static void main(String[] args) {int codePoint = -1;System.out.println(Character.toString(codePoint));}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Not a valid Unicode code point: 0xFFFFFFFF at java.base/java.lang.String.valueOfCodePoint(String.java:3760) at java.base/java.lang.Character.toString(Character.java:8651)
No comments:
Post a Comment