use of System.out.println(""); error....
Hi all,
Cant we use System.out.println within class scope ? Like the one shown below:
Code :
class A{
int a=1;
System.out.println(" a is " +a); //giving error ... understandable
System.out.println(); // but why error for this..?
void cal(){
int b=2;
System.out.println(" b is " +b); //working fine
}
}
public class Test {
public static void main(String[] args) {
A a =new A();
a.cal();
}
}
Why doesn't java allow this? I mean Should i explicitly write a method to display the value of variables of a particular class? OR Do it this way which is as told in java in main()
A a = new A();
System.out.println("a is " +a.a);
a.cal();
Re: use of System.out.println(""); error....
The println calls need to be inside of a method or constructor.
Statements outside of methods are executed when the class is instantiated. They are for defining and initializing variables.
Re: use of System.out.println(""); error....
You can do this if you put your printing code inside an initialization block. This will get executed once for every instance, before the constructor runs. For example:
Code java:
class A {
int a = 1;
{ // open initialization block
System.out.println(" a is "+a);
System.out.println();
} // close initialization block
void cal() {
int b = 2;
System.out.println(" b is " + b); //working fine
}
}
This is not recommended practice unless you have a good reason for doing it, and in my experience, is rarely, if ever necessary.