Java Character CodePointAt Char Int Int Method

JavaJavaBeginner
Practice Now

Introduction

The Java codePointAt() method is a part of the Character class. It returns the Unicode code point of the character at the specified index in a char array. This lab will guide you through the process of using the codePointAt() method in Java.

Create a char array

In this step, we will create a char array to work with.

char[] arr = {'h', 'e', 'l', 'l', 'o'};

Get the code point at an index

In this step, we will use the codePointAt() method to get the code point of the character at a specific index in the char array.

int index = 2; // index of the third element (l)
int codepoint = Character.codePointAt(arr, index);
System.out.println("Code point at index " + index + " is " + codepoint);

Get the code point at an index within a limit

In this step, we will use the codePointAt() method with a limit parameter to get the code point of the character at a specific index in the char array within a certain limit.

int startIndex = 1; // start at index 1 (e)
int limitIndex = 3; // stop at index 3 (first l)
int codepoint2 = Character.codePointAt(arr, startIndex, limitIndex);
System.out.println("Code point at index " + startIndex + " within limit " + limitIndex + " is " + codepoint2);

Create a user input example

In this step, we will create a user input example that allows the user to enter a char array, an index, and a limit, and displays the code point of the character at the given index within the limit.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter char array: ");
String input = scanner.nextLine();
char[] arr2 = input.toCharArray();

System.out.print("Enter index: ");
int index2 = scanner.nextInt();

System.out.print("Enter limit: ");
int limit2 = scanner.nextInt();

int codepoint3 = Character.codePointAt(arr2, index2, limit2);
System.out.println("Code point at index " + index2 + " within limit " + limit2 + " is " + codepoint3);

Compile and run the code

In this step, we will compile the CharCodepoint.java file and run it in the terminal.

Compile the code using the following command:

javac CharCodepoint.java

Run the code using the following command:

java CharCodepoint

The output should look like the following example:

Code point at index 2 is 108
Code point at index 1 within limit 3 is 101
Enter char array: world
Enter index: 3
Enter limit: 5
Code point at index 3 within limit 5 is 100

Summary

In this lab, we learned how to use the Java codePointAt() method to get the Unicode code point of a character at a specific index of a char array. We also learned how to use the codePointAt() method with a limit to obtain the code point of a character within a specified range. Finally, we created a user input example to practice using the method with dynamic data.

Other Java Tutorials you may like