Chromeium
Chromeium

Reputation: 264

Char array having integer values In Java

I am using JAVA for coding. My Aim is to put Location of array into that position of array and it has to be a char array My current Code:-

    char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]=i+1+'0';
    }

or

    char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]=i+1;
    }

Is not working for java and am getting error "Cannot convert int to char". I have tried finding out about it but i only received solution for c++ and that code dosent work in Java giving the same error.

Upvotes: 1

Views: 507

Answers (3)

ControlAltDel
ControlAltDel

Reputation: 35011

You just need to cast the value you are trying to put into the array as a char. The reason for this is that char is a 16 bit number and int is 32 bits

   char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]=(char) (i+1+'0');
    }

or

    char arr[]=new char [16];
    for(int i=0;i<16;i++)
    {
        arr[i]= (char)(i+1);
    }

Upvotes: 1

Socal Coder
Socal Coder

Reputation: 21

Because you are trying to assign an integer value to a char! Cast it to char first.

Upvotes: 0

Wietlol
Wietlol

Reputation: 1071

Try to cast it explicitly to a char.

arr[i] = (char)i + 1;

or maybe

arr[i] = (char)((char)i + 1);

If the output of char + char gives an int (because of whatever reason you can think of).

Upvotes: 0

Related Questions