javacodex.com
Java Examples
Java Examples
memu home questions

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

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

It is not possible for an int[] to know if its data was written as a character or as a number in the source code. You need a different data structure if you wish to keep that kind of information.

Source: (Example.java)

public class Example {
 
    public static void main(String[] args) {
 
        // I don't think there is any way to do it with int[]
        int array1[] = {'a', 98};
        for (int num : array1) {
            System.out.println(num);
        }
 
        // But you can create Object[] to achieve it.
        Object array2[] = {'a', 98};
        for (Object o : array2) {
            if (o instanceof Character){
                System.out.println("Character: " + o);
            } else if (o instanceof Integer){
                System.out.println("Integer: " + o);
            }
        }
 
    }
}
 

Output:

# java Example
97
98
Character: a
Integer: 98

Questions answered by this page:

Is it possible to differentiate between character and integer stored in the same integer array? Storing character and integer in the same array with Java Differentiate between character and integer stored in an array




Contact: javacodex@yahoo.com