class level error : <identifier> expected in java - java

when I am coding this at class level
int a;
a=5;
it throws error : "identifier expected"
But when I declare it as a local variable like
void m1() {
int a;
a=5;
}
No error is thrown.

When you're doing this at class level, you're allowed to combine declaration and assignment in just one statement, like:
class A {
int a = 5;
}
Otherwise, you have to wrap the assignment withing a block (constructor, method, initializer block). For example:
class A {
int a;
public A() { a = 5; } //via constructor
void setA() { a = 5; } //via method
{ a = 5; } //via initializer block
}

Assigning a value to variable is called as expression. We could not write any expression in a class. We could do the same in method bodies. Basically we could right expressions when scope is defined and hence allowed in method.

The reason following:
int a=5;
declared at class level does not produce compile time error when:
void m1() {
int a;
a=5;
}
is declared because m1() has its own scope.
For instance, if don't declare and access variable a, it would refer to class's field, where as when you declare a locally, you'd always refer to one declared inside a.
PS : You cannot do following at class level:
int a;
a=5;
You'd have to:
int a=5;

You can not write code into the class, only in method, constructor or into initializer {} block. That is why you get syntax error.
Probably you want to use initializer block like this:
class my{
int a;
{
a=1;
}
}

Related

passing value to member variable in java

Why can we do this:
class A{int a=5;}
but are not allowed to do this:
class A {
int a;
a=5;
}
just put it inside a block then.
class A {
int a;
{a=5;}
}
An initialization block will run every time you make in instance of the class e.g.
new A();
this is of course between two other initializations related to creating a new instance.
first is the field's initializations like when you declare a field with a value.
int a = 25;
then the block initialization
{
a = 5;
}
then the constructor:
A() {
a = 6;
}

Declaration & Initialisation of instance variables in java [duplicate]

when I am coding this at class level
int a;
a=5;
it throws error : "identifier expected"
But when I declare it as a local variable like
void m1() {
int a;
a=5;
}
No error is thrown.
When you're doing this at class level, you're allowed to combine declaration and assignment in just one statement, like:
class A {
int a = 5;
}
Otherwise, you have to wrap the assignment withing a block (constructor, method, initializer block). For example:
class A {
int a;
public A() { a = 5; } //via constructor
void setA() { a = 5; } //via method
{ a = 5; } //via initializer block
}
Assigning a value to variable is called as expression. We could not write any expression in a class. We could do the same in method bodies. Basically we could right expressions when scope is defined and hence allowed in method.
The reason following:
int a=5;
declared at class level does not produce compile time error when:
void m1() {
int a;
a=5;
}
is declared because m1() has its own scope.
For instance, if don't declare and access variable a, it would refer to class's field, where as when you declare a locally, you'd always refer to one declared inside a.
PS : You cannot do following at class level:
int a;
a=5;
You'd have to:
int a=5;
You can not write code into the class, only in method, constructor or into initializer {} block. That is why you get syntax error.
Probably you want to use initializer block like this:
class my{
int a;
{
a=1;
}
}

Why forward referencing only possible in methods

What is happening in the compiler when we do forward referencing methods, how does it assign the value of another variable which is not declared? And can we use that inside methods? But why can we not use the variable in static blocks? For example,
public class Forward {
static int i = test();
static int test() {
System.out.println(j);
j = 20;
return j;
}
static {
System.out.println(j);
j = 20;
}
static int j;
}
If we assign the value directly like:
int i = j;
int j = 10;
Why does this code not compile? How is it possible only with methods? How does the compiler compile the forward references internally? Is the declaration happening first for all the variables and initialization happening next for all at a time or one by one? Explain it in detail.
JLS Section 8.3.3 states that 4 criteria must all be met if the forward-usage of a static variable will be considered a compile-time error:
The declaration of a class variable in a class or interface C appears textually after a use of the class variable;
In other words, obviously, it must be a "forward declaration": you use it before you declare it:
// Maybe not OK to use j here.
static int j;
// OK to use j here.
The use is a simple name in either a class variable initializer of C or a static initializer of C;
You can make a forward reference to the variable if you qualify its name:
static {
System.out.println(j); // Error on this line...
System.out.println(Forward.j); // ...but not this line...
System.out.println(org.whatever.Forward.j); // ...or this line...
}
static int j;
This criterion only applies to variable or static initializers. This answers the specific question of why you are not getting a compiler error when referring to the static variable in a method.
However, let's just finish things off...
The use is not on the left hand side of an assignment;
Note in this code:
static {
System.out.println(j); // Error on this line...
j = 20; // ...but not this line.
}
static int j;
You can't do anything except assign the variable, even if you reverse the order of the lines (you can't assign and then print it).
C is the innermost class or interface enclosing the use.
The following code would be fine:
class Forward {
static class Inner {
static {
System.out.println(j);
}
}
static int j;
}

Instantiation and declaration separate

My question is regarding the declaration and value assignment rules in Java.
When writing the fields we can declare and assign values together but we cannot do the same separately.
E.G.:
class TestClass1 {
private int a = 1;
private int b ;
b= 1;
private int sum;
public int getA() {
return a;
}
public int getB() {
return b;
}
public int getSum() {
sum = a + b;
return sum;
}
}
public class TestClass {
public static void main(String[] args) {
TestClass1 testClass1 = new TestClass1();
System.out.println("total =" + testClass1.getSum());
}
}
Here in line:
private int a = 1;
We are able to declare a as a private int and assign a value 1 to it. But in case of:
private int b ;
b= 1;
Eclipse does not allow this to happen and throws an error. Kindly explain the logic behind this.
Code inside a class, but outside a function, is purely declarations. It does not get "executed". It simply declares what fields a class contains.
The reason you can do the shorthand private int a = 1; is just syntactic sugar that the Java language allows. In reality, what happens is that the a = 1 part is executed as part of the constructor. It's just easier to read and write when it is next to the variable declaration.
It's something nice that the Java langage creators allowed. Not every language allows that, look at C++ as an example that does not always allow it.
you have to put b=1; inside a method or put this inside a constructor.
you are getting this error since you can't do any thing other than declaration(private int a= 1;
) in class level.
It's just a question of syntax in Java. In the example you show, you try to affect a value to b in the member declaration part of your class. This is not allowed by the syntax of Java. You can only do it when you declare your attribute, in the body of a method or in a static block if your attribute is static e.g. :
private static int b;
static {
b = 1;
}
It is only a syntax problem. You can do it like this :
private int b ;
{ // <- Initialization block
b= 1;
}
See What is an initialization block?
You are unable to write logic directly in the class. You should move it to the constructor.
Java only allow declaration within the class and outside any method. Declarations like int b = 1; will be executed when you initialize a new Object.

Java: Can't get incremented value to print.

I'm learning to do some Java 101 syntax stuff. In an exercise I'm trying to do, I can't get the incremented value to print. Any ideas?
Here is my code:
class StaticTest {
static int i = 47;
}
class incrementable {
static void increment() { StaticTest.i++; }
}
class DataOnly {
int i;
double d;
boolean b;
public static void main (String[] args) {
incrementable t = new incrementable();
DataOnly df = new DataOnly();
df.i = t.increment();
System.out.println(df.i);
}
}
The error I get is:
aTyp0eName.java:18: incompatible types
found: void
required: int
df.i = t.increment();
df.i is an int and so is t.increment. I'm guessing it's because increment() is void?
your method signature is:
static void
Which means nothing is returned from this method.
Hence, attempting to assign increment() to df.i won't work.
increment() doesn't have a return value. You'd need to have it return an int for your code to work:
class incrementable {
static int increment() {
StaticTest.i++;
return StaticTest.i;
}
}
"void" is a keyword reserved for methods which don't return any value. Otherwise, you specify what class or primitive you return (int, double, String, whatever). You can read more about return values here.
Also, for future reference, class names should be capitalized, so you should be using "Incrementable" rather than "incrementable". (In my sample code I kept it the same as you had it so you could just drop the code in for now.)
The error I get is:
aTyp0eName.java:18: incompatible types
found: void
required: int
df.i = t.increment();
df.i is an int and so is t.increment [fault?]. I'm guessing it's because increment() is void?
Eeeexactly, your guess is correct.
This is the error message explained line by line:
aTyp0eName.java:18: incompatible types
You are trying to assign "void" to an int in line 18.
df.i = t.increment();
Here is where the error is.
found: void
You declare what's the return type in the method "signature".
The method signature is :
<access modifiers> <return type> <method name> (<parameters> )
static void increment ()
So the return type is void.
Next line:
required: int
df.i is int as you have previously stated.
So, pretty much you have already your own question answered.
The good point of having a compiler is that it tells you when something is wrong.
The bad thing ( for humans ) you have to learn to read those messages. They vary from programming language to another and even from compiler to compiler.
This would be a corrected version:
class StaticTest {
static int i = 47;
}
class Incrementable {
static int increment() {
return ++StaticTest.i;
}
}
class DataOnly {
int i;
double d;
boolean b;
public static void main (String[] args) {
Incrementable t = new Incrementable();
DataOnly df = new DataOnly();
df.i = t.increment();
System.out.println(df.i);
}
}
There are some other enhancements could be done, such as adding access modifiers to the methods and attributes, but for now I think this would help.
The answer is that the increment() method returns a void. That being said, there are a lot of violations of the Java standard syntax that programmers generally use, Namely:
Class names should start with a capital letter.
fields should not be mutated from different classes, rather a helper method should be within the same class
If you want to call a static method, don't reference an instance variable, rather use ClassName.reference
If a variable is only needed locally, it should not be a field (df.i could just be an int i declared within the main method).
EDIT:
An example of a helper method within the same class:
class StaticTest {
private static int i = 47; //keep i private and mutate and access via methods
public static void increment() { i++; }
public static int getI() { return i; }
}
also, if you instantiate incrementable, you shouldn't define the method increment() as static. or you can, but don't need to.
you could simply incrementable.increment() if it's static.
just a tip. as for the answer to your question, toolkit already said that right.
Also, your incrementable class should really be Incrementable.

Categories