Java check if the type is primitive


How to check in Java a primitive we have or an object?... ..The task in general from the book, Here is this: "Write a program that determines whether the char array is a primitive type or a "real" object.

Author: Kompot, 2016-10-04

1 answers

Let's dot the i. The formulation

Whether the char array is a primitive type or a "real" object.

Is incorrect, since an array in Java is the most common object inherited from Object.

Then we will answer the question -

How do I determine if the elements of a given array are objects or primitive types?

Let's do some research and run a simple code

 String[] strArr = {"one", "two"};
 int[] intArr = {1, 2};
 System.out.println(strArr);
 System.out.println(intArr);

We will get the following conclusion:

[Ljava.lang.String;@6d06d69c                                                                                                                                                                       
[I@7852e922 

Arrays in Java, unlike collections, do not know how to just print out their elements in the toString () method, but the name of the array class can tell us something useful. We can see that for an array of String objects, the output starts with [Ljava.lang.String, and for primitive int objects, it starts with [I. (Default object output without redefining toString() - classname@hash) If you go into the documentation, you can see that the first the characters in the string representation of the array correspond to the following types:

  • [Z = boolean
  • [B = byte
  • [S = short
  • [I = int
  • [J = long
  • [F = float
  • [D = double
  • [C = char
  • [L = any non-primitives(Object)

(I copied this list from of this post)

And this is the first way to find out whether a given array is an array of primitives or not: see where it starts the name of the array class.

myArray.getClass().getName()

The second - the correct way - was suggested in a comment to the post by the user
@Sergey.

myArray.getClass().getComponentType().isPrimitive()

The getComponentType() method returns an object of type Class corresponding to the class of array elements, if it was called for an object of type Class of the array itself, otherwise null. (it was a complicated sentence. But, as an example of incorrect usage: "Hello". getClass().getComponentType() returns null) An object of type Class has a method isPrimitive(), the purpose of which, I think, is clear from the name-checking whether the corresponding element is primitive.

 3
Author: Nikolay Romanov, 2020-06-12 12:52:24