Home > Back-end >  How an array is object in Java programming language?
How an array is object in Java programming language?

Time:11-30

int[] arr={2,4,5,0,77,9};

How this array is an object type as we are not using new keyword here. Please explain.

CodePudding user response:

There are only 8 primitive data types in Java (listed here), that are:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

The thing that confuses you is that you don't see the "new" word here. But the answer is simple - an array is a container object (basic collection), so it is not a primitive type, but it is still one of the basic types that are built into the platform.

In your case, there is also syntax sugar. If you compile your code and open the .class file, you'll see that after compilation it probably looks like this:

int[] var10000 = new int[]{2, 4, 5, 0, 77, 9};

There are several more confusing types that are in the java standard class library for so long, that there is a syntax sugar that allows invoking the constructor without the "new" keyword. For example:

String myString = "My string";
Long myLongObj = 100L;
Boolean myBooleanObject = true;

although String, Long and Boolean are objects of java.lang.* classes.

CodePudding user response:

This is syntactic sugar. Java recognizes the type and creates the object for you. There are several (primitive) objects that are created this way. For example:

String str = "Hey I am a new String";
// But this can also be done this way:
String str1 = new String("hey");

Integer nrInt = 1;
Integer nrInt1 = new Integer(2); // Very unusual though

// Same story with Double, Long, int[], double[]...

CodePudding user response:

Please keep in mind that this: int[] arr={2,4,5,0,77,9};

is just a shorter way of writing:

int[] arr = new int[6];
arr[0] = 2;
arr[1] = 4;
arr[2] = 5;
arr[3] = 0;
arr[4] = 77;
arr[5] = 9;

Java provides several ways to write certain things. The version with ... = new int[5]; comes in handy if you don't know up front what the values will be, but why would you have to do this, if you do know the values?

CodePudding user response:

You seem to think that new is the only way to create an object in Java. It isn't, objects can also be created:

  • using boxing; e.g. Integer i = 42;
  • using a class literal; e.g. Class<?> c = Something.class;
  • using a string literal; e.g. String s = "abc";
  • via an enum class ... since each enum value is an object.
  • using reflection; e.g. Constructor::newInstance
  • using Object::clone

... and so on.

There are many ways to create objects that don't involve the new keyword.

In fact an array is an object (or more precisely an instance of a reference type) because the JLS specifies that it is. End of story ...

  • Related