Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying Char And Integer Together

My code is in Java. I have a char array that has int values as well as char values. When I print, I get its values related to ASCII. But when I convert output to int, my character value changes to its ASCII value.

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

arr[0]='@';

for(int i=0;i<5;i++)                
{
    System.out.println(arr[i]);
}

Or converting to int:

for(int i=0;i<5;i++)                
{
   System.out.println((int)arr[i]);
}

My output is

64 2 3 4 5

or

@

depending on which code I use. However, I want the output as

@ 2 3 4 5

I tried using method overloading to separate integers and characters, but that didn't work.

Is there a condition for int like below?

if(arr[i]==int)

The code doesn't work but is there some thing similar to it or any other solution?

like image 907
Chromeium Avatar asked Jul 01 '26 08:07

Chromeium


1 Answers

It doesn't work, because as far a Java is concerned, a char primitive is just a 16 bit unsigned integer value. To demonstrate:

System.out.println('A' == 65); // prints true

One way to work around this would be to declare an object array, and rely on auto-boxing to have Java automatically convert your primitive value to an Integer or Character wrapper object:

Object arr[] = new Object[2];
arr[0] = '@'; // stores '@' as a Character wrapper object
arr[1] = 1; // stores 1 as an Integer wrapper object

for (Object o : arr) {
    System.out.println(o);
}

Unlike primitives, wrapper objects are aware of their type, so this prints out:

@ // by calling Character.toString()
1 // by calling Integer.toString()

Note that you lose some compile-time checking in the process. Your object array will not only accept Character and Integer values, but also any other value.

like image 129
Robby Cornelissen Avatar answered Jul 03 '26 22:07

Robby Cornelissen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!