-5

This is a part of code i was working on .. but the compiler showed an error on line 1. (Syntax error on token";", , expected). Why is that error coming??

public class variable 
{

           int[] nums;
           nums= new int[7];
}
4
  • 2
    You're trying to use an assignment statement outside a method/constructor. Either just use int[] nums = new int[7]; or put the assignment in a constructor. Commented Jun 20, 2016 at 10:23
  • no methods in class variable? Commented Jun 20, 2016 at 10:23
  • In Java instructions can be only in methods. Not directly in class body. Commented Jun 20, 2016 at 10:24
  • But you can use initilizers like: int[] num = new int[7]; Commented Jun 20, 2016 at 10:24

2 Answers 2

2

You have to initialize the Array in same line as the declaration

public class variable 
{

           int[] nums = new int[7];
}

or you have to initialize it in a method or constructor:

 public class variable 
{

   int[] nums;
   public variable(){

           nums= new int[7];
   }
}

Hint: read about Java naming conventions. Class names should start with uppercase character.

Sign up to request clarification or add additional context in comments.

Comments

1

You should use assignment inside a method or a constructor. Or you can instantiate it class level but you have to initialize it same line with declaration.

Eg: Class level instantiation.

public class Variable {
    int[] nums = new int[7];
}

Use inside a method.

public class Variable {
    int[] nums;
    public void method(){            
        nums = new int[7];
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.