Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to differentiate between character and integer stored in the same integer array?

Tags:

java

My code is

int array[] = {'a',98};
for(int num:array) {
    System.out.println(num);
}

If I print this, I'll get o/p as 97 98.

If I print (char) num then o/p will be a b.

Is it possible to print the array as a 98? My guess is as array will store integer values of the array elements, it is not possible. But any solution here?

like image 368
Audumbar Avatar asked Apr 21 '16 09:04

Audumbar


1 Answers

I don't think there is any way to do it with int[]. But you can create Object[] to achieve this.

Here is the code snippet:

public static void main (String[] args) throws Exception {
    Object array[] = {'a',98};
    for(Object o : array){
        System.out.println(o);
    }
}

Output:

a
98
like image 133
user2004685 Avatar answered Sep 28 '22 05:09

user2004685