user3257390
user3257390

Reputation: 11

Arrays: Objects or Variables

Online, the question of whether arrays are objects or variables is conflicting. Are arrays objects, or variables?

Blue Pelican Java book claims that they are variables, but they must be instantiated, so I'm not sure.

Upvotes: 0

Views: 102

Answers (7)

Mladen P
Mladen P

Reputation: 176

when you ask "Are arrays objects, or variables?" I think you mean "Are arrays objects, or primitive data types?"

Arrays are objects and refer to a collection of primitive data types or other objects.

Arrays can store two types of data:

  • A collection of primitive data types
  • A collection of objects

Upvotes: 1

ADTC
ADTC

Reputation: 10086

In simple terms, a variable is how you declare an object and access it. So they are not two mutually exclusive things.

An array is an object, and you can use a variable to access it. While an array is an object, it may hold values of primitive types (example int[]) or it may hold objects of a class type (example String[])

int[] arr1 = new int[2];
System.out.println(arr1[0]); //output: 0

This will create an array object that can hold two values of primitive type int. The array object can be accessed using the variable arr1. Since the array holds primitives, they will be initialized to the default value 0 (or false for boolean).

String[] arr2 = new String[2];
System.out.println(arr2[0]); //output: null

This will create an array object that holds two objects of class type String. The array object can be accessed using the variable arr2. Since the array holds objects, it will initially hold null, which means no object.

More about arrays from The Java Tutorials

Upvotes: 0

Andres
Andres

Reputation: 10717

First, an instance of an array is a full right object in Java.

Second, an array may be the type of a variable (but not a variable). In that case, when the variable is instantiated, it will point to an array instance (which is an object).

Upvotes: 1

SSB
SSB

Reputation: 789

Try this code to check whether array is object or not .

 String[] str=new String[] {"A","B","X"};
 if (str instanceof Object){
     System.out.println("Yes!");
}else{
   System.out.println("No!");
}

Upvotes: 0

Arunprasad
Arunprasad

Reputation: 577

Array is purely object.according to java doc

Upvotes: 0

Saif Asif
Saif Asif

Reputation: 5658

I think the JavaDocs clear that up in a single sentence

An array is a container object that holds a fixed number of values of a single type

Upvotes: 2

Joofe Kopp
Joofe Kopp

Reputation: 123

I think that arrays are objects.

Upvotes: 1

Related Questions