The Wayback Machine - https://web.archive.org/web/20241004201702/https://www.geeksforgeeks.org/java-lang-character-class-methods-set-1/
Open In App

java.lang.Character class methods | Set 1

Last Updated : 19 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

java.lang.Character class methods

lang.Character class wraps the value of a primitive data type – char to an object of datatype char and this object contains a single field having the data type – char. This class provides no. of methods regarding character manipulations like converting them from lowercase to uppercase. Character class is based on

Unicode

Standards to provide character information. Class Declaration:

public final class Character
extends Object
implements Serializable, Comparable

Following methods of Character class are discussed here :

1. charCount() :

java.lang.charCount() method uses Unicode point to return the number of char values to represent the argument char values. A Unicode code point is used for character values in the range between U+0000 and U+10FFFF and for 16-bit char values that are code units of the UTF-16 encoding. Syntax :

public static int charCount(int argchar)

Parameters :
argchar : char i.e. it's Unicode point to be counted

Return :
2 if the character is valid i.e. > or = to 0X1000(supplementary character); else 1

2. charValue() :

java.lang.charValue() method returns primitive character value of defined char Object. Syntax :

public char charValue()

Return :
primitive character value of defined char Object.

3. codePointAt() :

java.lang.Character.codePointAt(char[ ] array, int position) method returns Unicode Point of the character array present at the argumented position.

Syntax :

public static int codePointAt(char[] array, int position)

Parameters :
array : character array
position : array index of character whose Unicode Point value you need.

Return :
Unicode point of the character array present at the given position

Java code explaining use of charCount(), charValue(), codePointat() methods

JAVA




// Java program explaining Character class methods
// charCount(), charValue(), codePointat()
import java.lang.Character;
public class NewClass {
    public static void main(String[] args)
    {
        // Use of charCount() method
        int geek = 0x9999, // < 0x10000
            geek1 = 0x10000, // = 0x10000
            geek2 = 0x10001; // > 0x10000
 
        int check = Character.charCount(geek);
        int check1 = Character.charCount(geek1);
        int check2 = Character.charCount(geek2);
 
        if (check == 2) // Checking for geek
            System.out.println("Valid Character geek");
        else
            System.out.println("Invalid Character geek");
 
        if (check1 == 2) // Checking for geek1
            System.out.println("Valid Character geek1");
        else
            System.out.println("Invalid Character geek1");
 
        if (check2 == 2) // Checking for geek2
            System.out.println("Valid Character geek2");
        else
            System.out.println("Invalid Character geek2");
 
        System.out.println("");
 
        // Use of charValue() method
        Character m; // Character object m
 
        m = new Character('g'); // Assigning value g to m;
 
        char gfg;
        gfg = m.charValue();
        System.out.println("Primitive value of gfg : "
                           + gfg);
        System.out.println("");
 
        // Use of codePointAt()
        char[] arg = new char[] { 'g', 'e', 'e', 'k', 's' };
        int val, val1, position = 3;
 
        val = Character.codePointAt(arg, position);
        val1 = Character.codePointAt(arg, 0);
 
        System.out.println("Unicode code point at "
                           + position + " : " + val);
        System.out.println("Unicode code point at 0 : "
                           + val1);
    }
}


Output

Invalid Character geek
Valid Character geek1
Valid Character geek2

Primitive value of gfg : g

Unicode code point at 3 : 107
Unicode code point at 0 : 103

4. codePointBefore() :

java.lang.Character.codePointBefore(char[ ] array, int position) method returns Unicode Point of the character array present before the argumented position.

Syntax :

public static int codePointBefore(char[] array, int position)
or
public static int codePointBefore(char[] array, int position, int start)
Parameters :
array : character array
position : array index of character following the Unicode Point value you need.
start : start index of the character array
Return :
Unicode point of the character array present before the given position

5. codePointCount() :

java.lang.Character.codePointCount() method returns no. of Unicode Point of the sub-character array.

Syntax :

public static int codePointCount(char[] array, int start, int len)
Parameters :
array : character array
start : starting index of the array
length : length of the character sub-array
Return :
no. of Unicode Point of the sub-character array.
Exception :
--> NullPointerException
--> IndexOutOfBoundsException

6. compareTo() :

java.lang.Character.compareTo(Character argChar) method compares given character with argumented character.

Syntax :

public int compareTo(Character argChar)

Parameters :
argChar : character to be compared with

Return :
= 0 : if both characters are equal
> 0 : if given this character is greater
< 0 : if argumented character is greater

Java code explaining use of codePointBefore(), codePointCount(), compareTo() methods

JAVA




// Java program explaining Character class methods
// codePointBefore(), codePointCount(), compareTo()
import java.lang.Character;
public class NewClass
{
    public static void main(String[] args)
    {
        // Use of codePointBefore()
        char[] arg = new char[] { 'g', 'e', 'e', 'k', 's' };
        int position  = 4;
 
        int val = Character.codePointBefore(arg, position);
        int val1 = Character.codePointBefore(arg, 1);
        int val2 = Character.codePointBefore(arg, 3, 1);
 
        System.out.println( "Unicode code point before " + position +
                                                       " : " + val );
        System.out.println( "Unicode code point before 1 : " + val1 );
        System.out.println( "Unicode code point before 3 to 1 : "
                                                              + val2);
        System.out.println("");
 
        // Use of codePointCount()
        int count = Character.codePointCount(arg, 1,3 );
 
        System.out.println("No. of Unicode points : " + count);
        System.out.println("");
 
        // Use of compareTo()
        Character g1 = new Character('g');
        Character g2 = new Character('o');
 
        int check = g1.compareTo(g2);
        System.out.println("g1 < g2 : " + check);
        int check1 = g2.compareTo(g1);
        System.out.println("g2 > g1 : " + check1);
        int check2 = g2.compareTo(g2);
        System.out.println("g2 = g2 : " + check2);
    }
}


Output

Unicode code point before 4 : 107
Unicode code point before 1 : 103
Unicode code point before 3 to 1 : 101

No. of Unicode points : 3

g1 < g2 : -8
g2 > g1 : 8
g2 = g2 : 0

7. equals() :

java.lang.Character.equals() method compares the present char object with the argumented char object.

Syntax :

public boolean equals(Object charObj)

Parameters :
charObj : char object to compare with

Return :
true if both the objects are equal, else false.

8. getNumericValue() :

java.lang.Character.getNumericValue(char arg) method returns int value for the specific Unicode character. A – Z value ranges u0041 to u005A a -z value ranges u0061 to u007A

Syntax :

public static int getNumericValue(char arg)

Parameters :
arg : char value

Return :
int value for the specific Unicode character.
if Unicode value doesn't exists -1 is returned.

9. getType() :

java.lang.Character.getType(char arg) method identifies the general type of character A – Z value ranges u0041 to u005A a -z value ranges u0061 to u007A

Syntax :

public static int getType(char arg)

Parameters :
arg : char value

Return :
int value for the argumented character representing its general type category.

Java code explaining use of equals(), getNumericValue(), getType() methods

JAVA




// Java program explaining Character class methods
// equals(), getNumericValue(), getType()
import java.lang.Character;
public class NewClass
{
    public static void main(String[] args)
    {
        // Use of equals() method
        Character g1 = new Character('g');
        Character g2 = new Character('O');
 
        boolean check = g1.equals(g2);
        boolean check1 = g1.equals(g1);
        System.out.println("Are g and o equal? : " + check);
        System.out.println("Are g and g equal? : " + check1);
        System.out.println("");
 
        // Use of getNumericValue() method
        int c = Character.getNumericValue(g1);
        int c1 = Character.getNumericValue(g2);
        System.out.println("Int value for g : " + c);
        System.out.println("Int value for A : " + c1);
        System.out.println("");
 
        // Use of getType() method
        Character g3 = new Character('$');
        Character g4 = new Character('6');
 
        int r1 = Character.getType(g1);
        int r2 = Character.getType(g2);
        int r3 = Character.getType(g3);
        int r4 = Character.getType(g4);
 
        System.out.println("Type for lowercase : " + r1);
        System.out.println("Type for uppercase : " + r2);
        System.out.println("Type for currency  : " + r3);
        System.out.println("Type for numeric   : " + r4);
    }
}


Output

Are g and o equal? : false
Are g and g equal? : true

Int value for g : 16
Int value for A : 24

Type for lowercase : 2
Type for uppercase : 1
Type for currency  : 26
Type for numeric   : 9



Previous Article
Next Article

Similar Reads

java.lang.Character class - methods | Set 2
java.lang.Character class - methods | Set 1 Following methods of Character class are discussed here : toUpperCase() : java.lang.toUpperCase(char arg) method converts given character in argument to its Upper case based on Unicode values. Syntax : public static char toUpperCase(char arg) Parameters : arg : character to be converted to Upper case Retu
4 min read
Java.lang.Character.Subset Class in Java
Character.Subset Class represents particular subsets of the Unicode(standards using hexadecimal values to express characters - 16bit) character set. The subset, it defines in Character set is UnicodeBlock. Declaration : public static class Character.Subset extends Object Constructors : protected Character.Subset(String str) : Constructs new subset
2 min read
Java.lang.Character.UnicodeBlock Class in Java
Character.UnicodeBlock Class represents particular Character blocks of the Unicode(standards using hexadecimal values to express characters - 16 bit) specifications. Character Blocks define characters used for specific purpose. Declaration : public static final class Character.UnicodeBlock extends Character.Subset Methods of Character.UnicodeBlock
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
java.lang.Boolean class methods
About : java.lang.Boolean class wraps primitive type boolean value in an object.Class Declaration public final class Boolean extends Object implements Serializable, Comparable Constructors : Boolean(boolean val) : Assigning Boolean object representing the val argument. Boolean(String str) : Assigning Boolean object representing the value true or fa
5 min read
Java.lang.Integer class and its methods
java.lang.Integer wraps integer data type to an object containing a single field having datatype is int. Constructors : Integer (int arg) : Constructs integer object representing an int value.Integer (String arg) : Constructs string object representing a string value.Integer class methods: toBinaryString() : java.lang.Integer.toBinaryString() metho
6 min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
Java.lang.Math Class in Java | Set 2
Java.lang.Math Class in Java | Set 1 More Methods: cosh() : java.lang.Math.cosh() method returns the hyperbolic cosine of the argument passed. Special cases : Result is NaN, if argument is NaN. Result is 1.0, if the argument is zero. Result is +ve infinity, if argument is infinite. Syntax: public static double cosh(double arg) Parameters: arg - The
6 min read
Java.lang.StrictMath class in Java | Set 1
StrictMath Class methods helps to perform the numeric operations like square, square root, cube, cube root, exponential and trigonometric operations Declaration : public final class StrictMath extends Object NaN argument?A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.longBitsToDouble(0
8 min read
Java.lang.String class in Java | Set 2
Java.lang.String class in Java | Set 1 In this article we would be discussing different constructor and methods provided by java.lang.String. Strings in java are immutable. Now lets discuss some of the methods provided by String class. Methods: public int codePointAt(int index) - It takes as parameter a index which must be from 0 to length() - 1. a
5 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
java.lang.MethodType Class in Java
MethodType is a Class that belongs to java.lang package. This class consists of various types of methods that help in most of cases to find the method type based on the input object, or parameters of the method. All the instances of methodType are immutable. This means the objects of the methodType class cannot be overridden by any other objects da
4 min read
java.lang.ref.WeakReference Class In Java
When we create an object in Java, an object isn't weak by default. To create a Weak Reference Object, we must explicitly specify this to the JVM. Why Weak Reference Objects are used: Unlike C/C++, Java supports Dynamic Garbage Collection. This is performed when the JVM runs the Garbage Collector. In order to not waste space, the garbage collector d
3 min read
java.lang.reflect.Parameter Class in Java
java.lang.reflect.Parameter class provides Information about method parameters, including their name and modifiers. It also provides an alternate means of obtaining attributes for the parameter. Some useful methods of Parameter class are: public int getModifiers(): It returns the modifier flags for the parameter represented by this Parameter object
4 min read
java.lang.ref.SoftReference Class in Java
When we create an object in Java, an object isn't soft by default. To create a Soft Reference Object, we must explicitly specify this to the JVM. In Soft reference, even if the object is free for garbage collection then also it's not garbage collected until JVM is in need of memory badly. The objects get cleared from the memory when JVM runs out of
3 min read
java.lang.reflect.Constructor Class in Java
java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will have one Constructor instance for each public constru
4 min read
java.lang.ref.ReferenceQueue Class in Java
A ReferenceQueue is a simple data structure onto which the garbage collector places reference objects when the reference field is cleared (set to null). You would use a reference queue to find out when an object becomes softly, weakly, or phantom reachable, so your program can take some action based on that knowledge. For example, a program might p
3 min read
java.lang.reflect.Method Class in Java
java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method). This class allows broadening of conversions to occur when matching the actual parameters to call th
3 min read
java.lang.reflect.ReflectPermission Class in Java
ReflectPermission class extends BasicPermission class. It is a “named” permission i.e it contains a name but no action. It may implement actions on top of BasicPermission, if desired. It is used to get information about the behaviour of Constructors. ConstructorsDescriptionReflectPermission(String name)It is used to create a ReflectPermission with
2 min read
java.lang.reflect.Modifier Class in Java
The java.lang.reflect.Modifier class contains methods used to get information about class, member and method access modifiers. The modifiers are represented as int value with set bits at distinct positions. The int value represents different modifiers. These values are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of The JVM Specificatio
7 min read
java.lang.reflect.Field Class in Java
The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather than at compile time .Java, like many other languag
5 min read
java.lang.management.ThreadInfo Class in Java
java.lang.management.ThreadInfo class contains methods to get information about a thread. This information includes: Thread IDThread NameState of the ThreadStack trace of the ThreadThe object upon which the Thread is blockedList of object monitors that are blocked by the ThreadList of ownable synchronizers blocked by the ThreadNumber of times the T
4 min read
java.lang.management.ManagementPermission Class in Java
java.lang.ManagementPermission Class contains abstract methods to determine access to a system resource. Every object has some name. Most permission object also has some "actions" associated with it that tells which activities are permitted by this permission object. Class declaration : public final class ManagementPermission extends BasicPermissio
3 min read
java.lang.ref.PhantomReference Class in Java
When we create an object in Java, an object is strong by default. To create a Phantom Reference Object, we must explicitly specify this to the JVM. Phantom Reference Objects are created as phantom reference object is eligible for garbage collection, but it is not collected instantly. Instead, it is pushed into a ReferenceQueue so that all such enqu
4 min read
java.lang.ref.Reference Class in Java
java.lang.ref.Reference Class is an abstract base class for reference object. This class contains methods used to get information about the reference objects. This class is not a direct subclass because the operations on the reference objects are in close co-operation with the garbage collector. Class declaration: prevent public abstract class Refe
3 min read
Java.lang.Number Class in Java
Most of the time, while working with numbers in java, we use primitive data types. But, Java also provides various numeric wrapper sub classes under the abstract class Number present in java.lang package. There are mainly six sub-classes under Number class.These sub-classes define some useful methods which are used frequently while dealing with num
9 min read
Java.lang.Boolean Class in Java
Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolea
8 min read
Java.Lang.Double Class in Java
Double class is a wrapper class for the primitive type double which contains several methods to effectively deal with a double value like converting it to a string representation, and vice-versa. An object of the Double class can hold a single double value. Double class is a wrapper class for the primitive type double which contains several methods
4 min read
Article Tags :
Practice Tags :