Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Sun Mar 18, 2018 5:58 pm
by nagarjuna19
Hi,

Can you please tell me how below code is valid?

public class A
{  
 public static void main(String[] args)
{     
System.out.println(new A().main); // What does the method new A().main mean? 
 }      
int main; } // what does this mean?

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Sun Mar 18, 2018 8:26 pm
by admin
It is creating an instance of A and then accessing the instance variable named main of that instance.

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Mon Mar 19, 2018 9:32 am
by nagarjuna19
hi Admin,

Thank you for reply. Can you please explain bit more.

What does A().main mean, as A a()=new A() is object creation
What does int main; mean?

Regards,
Nagarjuna

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Mon Mar 19, 2018 10:36 am
by admin
1. new A() means you are creating an object of class A. You are not assigning it to any variable. The compiler creates a temporary variable to refer to this object.
2. int main; is the definition of a variable named main of type int. Just like int x; or int i; etc.

I suggest you to go through a good book before attempting mock questions.

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Fri Jul 27, 2018 2:40 pm
by ash4413
Hi there,
I tried below code
A.java
import java.io.IOException;
class B {

public static void main() throws IOException{}
}

this shows an error message that
Error: Main method not found in class B, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

In simulator, there is nothing wrong with this code

Please clear my doubt
Thank you

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Fri Jul 27, 2018 9:50 pm
by admin
The question doesn't ask you to run the code. It only asks you whether the code will compile or not. Not every java class requires that it must be run from the command line. So from that perspective, there is nothing wrong with the code.

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Wed Sep 15, 2021 10:23 am
by qazwsx922
Hello,

//In file A.java
public class A{
int a;
public void m1(){
private int b = 0;
a = b;
}
}


Access modifiers (public/private/protected) are valid only inside the scope of a class, not of a method.


Does it mean all local variables can't have access modifiers?

Re: About Question enthuware.ocajp.i.v8.2.1452 :

Posted: Wed Sep 15, 2021 11:51 am
by admin
>Does it mean all local variables can't have access modifiers?
Correct. You cannot apply access modifiers (public, private, protected) to local variables (i.e. variables defined within a method).