W.Jack W.Jack - 1 year ago 57
Java Question

Why i can't declare and then assign value to a variable in a class without any method IN JAVA

It may sounds crazy but what i really want to do is just declare and initialize a member variable within a public class and then re-assign this variable with another value which is quite realistic in C. But it fails in Java.

public class App {

public int id=6; // got an error of "Syntax error on token ";", , expected"


But this could be done within a method. For example:

public class App {

public int id=6;


public void method() {

id=7; // that's okay

So, what really perplexing to me is that what makes the difference of using a method there in stead of re-assigning the member variable in the next line. I'm really looking forward to learn the insight conception of it if there exists any.

Answer Source

Generally, in object oriented programming the 'class' represents a description of a particular object. If we use the analogy of a car, think of it as the 'blueprint'.

The blueprint does a number of things:

  • Describes what kind of properties the object can have (so a car might have color and speed)
  • Describes what things the object can do (its 'methods')
  • Describes what the initial state of the object is each time it is created

The line public int id=6 does the first and the last of these. It says that any App object must have an id property, and its initial state is the value 6. If you then put the line id=7 in the class definition this isn't part of the blue print - it doesn't make sense to say that the default value of id is 6, and then decide it is 7 - so this is an error.

In Java, as with many object oriented languages, actual code that modifies state MUST take place inside a 'method', since every time something is happening in OOP, it is an 'object' doing something.


Your error is

Syntax error on token ";", , expected

This makes sense - it sees the following code

 public int id=6;


And thinks what you really meant to do was

 public int id=6,


Which would be the same as

 public int id=6, id=7; 

Of course this would generate another error probably unless you changed the name of the second definition.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download