简体   繁体   中英

Java, what is the point of creating new objects?

I am fairly new to Java and was wondering what the difference between the two is. For this example I used arrays:

class testpile {

public static void main(String[] args)
{
int[] a = {1,2,3,4,5,6}; //First array
int[] b = new int[5];  //Second Array
b[0] = 7;
b[1] = 8;
b[2] = 9;
b[3] = 10;
b[4] = 11;

print(a); 
print(b); 

} 

public static void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println(); 
} 


} 

I understand that using "new" creates a unique object but what are the advantages of using one over the other?

In your example there's no real difference between the two. The first is mostly just "syntactic sugar" for the latter. In both cases the array is allocated on the heap.

Both of the code creating a int array of size 5/6

In the first case the array is initialized with vale at the time of creation

In second case the value is assigned latter

that's the difference

In this example there is no difference b/w these two.

In the first case the array is initialized at the time of creation
 In second case the value is assigned latter whenever you want...  

But in both cases it will get m/m into heap..

I understand that using "new" creates a unique object but what are the advantages of using one over the other?

Both constructs do exactly the same thing (with different data, though): Creating an array and filling it with data. In particular, both these arrays are "unique objects".

You'd use the "less literal" one when you do not know the size and the initial values for the element at compile-time.

int[] a = {1,2,3,4,5,6}; //First array
int[] b = new int[5];  //Second Array

They are just two different ways of creating an array. There isn't really any OOP involved here.

The first one is better when you know the values before hand, otherwise the second is better.

The first statement is called array initialization where six int variables are created and each variable is assigned. In second statement, the new keyword create 5 int variables whose initial value is zero.

Using new keyword, you may instantiate an array whenever you require.

int []a=new int[5];

for(int i:a)
  System.out.println(i);

a=new int[]{11,22,33};

for(int i:a)
  System.out.println(i);

I think the result is same.

But when you create a array with "new" clause, You should assign a specify length of the array.

e.g  int[] b = new int[**5**];

And in this sample, you can also assign the value for b[5]. there shouldn't produce compilation error.But the error should occur in the runtime.

In regard to the another method, the length of the array don't need specify. It depend on the element count of array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM