The Artima Developer Community
Sponsored Link

Java Answers Forum
On Array creation

1 reply on 1 page. Most recent reply: Jan 16, 2003 6:27 AM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Ugo Posada

Posts: 37
Nickname: binaryx
Registered: Dec, 2002

On Array creation Posted: Jan 15, 2003 8:44 PM
Reply to this message Reply
Advertisement
Hello

Recently trying to code a little little program I came up with an error that made me feel like a stupid. What bothers me is that I don{t know why the Java compiler acts like this so I?ll show you what happened and I expect a trusthworthy and complete answer from you folks:

This compiles

public class pruebaArrays {
    private int[] myArray = {1,2,3,4,5};
    pruebaArrays() {
    	System.out.println(myArray);
    }
    
    public static void main(String[] args) {
        pruebaArrays pA = new pruebaArrays();        	
    }	
}
 


This does not compile

public class pruebaArrays {
    private int[] myArray;
    pruebaArrays() {
        myArray = {1,2,3,4,5};
    	System.out.println(myArray);
    }
    
    public static void main(String[] args) {
        pruebaArrays pA = new pruebaArrays();        	
    }	
}
 


Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: On Array creation Posted: Jan 16, 2003 6:27 AM
Reply to this message Reply
The syntax you are using is only for initialization of an array and for assignment. It means you can comma separated values to initialize the array elements only at the time when you declare the array. Since your declaration and assignment have been separated in two statements you are getiing array.
You can always do this:
int[] myArray = {1,2,3,4,5};

You cannot do this:
int[] myArray ;
myArray = {1,2,3,4,5};

Thanks
Kishori

Flat View: This topic has 1 reply on 1 page
Topic: how to ping IPv6 with java Previous Topic   Next Topic Topic: Monitors in java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use