CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2012
    Location
    toronto
    Posts
    13

    access array[i] outside of a method context; not possible?

    This code compiles without error:
    Code:
    public class hello {
     public static void main(String[] args){
       int[] vector = new int[10];
       vector[0]=3;
     }
    }
    Whereas this code does not compile and generates several errors:
    Code:
    public class hello {
     int[] vector = new int[10];
     vector[0]=3;
     public static void main(String[] args){
     }
    }
    The errors i get are just like this one:
    Code:
    >./hello.java:3: error: ']' expected
    >vector[0]=3;
    >       ^
    So i feel tempted to conclude that an expression of the form array[i] outside of any method context is illegal?

  2. #2
    Join Date
    Jan 2012
    Location
    toronto
    Posts
    13

    Re: access array[i] outside of a method context; not possible?

    oh i just remembered that with a static initialization block it would work:
    Code:
    public class hello {
     static {
       int[] vector = new int[10];
       vector[0]=3;
     }
     public static void main(String[] args){
     }
    }
    so i guess have to reformulate my question as outside of any static initialization block and outside of any method, in general are expressions like array[i]=x illegal?

  3. #3
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: access array[i] outside of a method context; not possible?

    so i guess have to reformulate my question as outside of any static initialization block and outside of any method, in general are expressions like array[i]=x illegal?
    Basically yes, although there are also instance initializer blocks which you can do this in. The only time you can assign values to an array outside a method or initializer is if you do it at declaration ie
    Code:
    String s = new String[]{"a", "b", "c"};
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  4. #4
    Join Date
    Jan 2012
    Location
    toronto
    Posts
    13

    Re: access array[i] outside of a method context; not possible?

    Quote Originally Posted by keang View Post
    Basically yes, although there are also instance initializer blocks which you can do this in. The only time you can assign values to an array outside a method or initializer is if you do it at declaration ie
    Code:
    String s = new String[]{"a", "b", "c"};
    thanks for confirmation!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured