0

count[str1.charAt(i)]

charAt() returns char type. How can char type be used as index in array

7
  • Why do you need it? Commented Apr 6, 2019 at 6:38
  • 1
    I saw this on geeksforgeeks, I wanted to understand how is this possible Commented Apr 6, 2019 at 6:40
  • Char can be converted to int. Commented Apr 6, 2019 at 6:40
  • 2
    A char is an integral type. Yes, that is legal. Commented Apr 6, 2019 at 6:40
  • charAt() returns the ascii value ? Commented Apr 6, 2019 at 6:46

1 Answer 1

3

YES! It is possible. It is a basic rule of java. We can assign char value to int type of variable. Now that int type variable will not store a character but its ASCII value. See the example

class Test{
    public static void main(String[] args){
        int num='a';
        System.out.println(num);//97
    }
}

you can see i've assigned 'a' into int type of variable.

In same case, whenever we pass char as index value, always ASCII value will be passed. As we know, 97 is the ASCII value of a.

So if we access an array by passing 'a', internally 97th index of array will be called.

int num='a';
System.out.println(args[num]);//AIOOBE 

Here we got Exception like

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 97 at Test.main(Test.java:4)

Program is compiled fine, but we got exception at runtime because args is empty array right now.

Sign up to request clarification or add additional context in comments.

2 Comments

A char value is not an ASCII value, but rather "A char value [...] represents Basic Multilingual Plane (BMP) code points, including the surrogate code points, or code units of the UTF-16 encoding. " -- docs.oracle.com/javase/9/docs/api/java/lang/Character.html
@ErwinBolwidt Thank you for your suggestion. I am not saying a char value is an ASCII value, but i mentioned that every char value can be represented by an ASCII value or every character has its own ASCII code. Yes but i am sorry, i shouldn't use the word ASCII since unlike C or C++ , Java supports UNICODE character set.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.