Question

Analyze the following code: public class Test { private int t; public static void main(String[] args) { int x; System.out.pri
The variable t is private and therefore cannot be accessed in the main method. The program compiles and runs fine. t is non-s
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer : t is non-static and it cannot be referenced in a static context in the main method.

Explaination :

Here look for the main(String args[]) method that is static.

Declaration of any method as static means that it will be created only once at time when the class loads.

Also note that non static method is created when object is instantiated.

In given problem, t is non-static and we are trying to fetch from static context i.e, main method

Since t is non-static, memory has not yet assigned to it.

To assign a memory for t you can create object and then use your t as example

public class Test{
 private int t;
 public static void main(String args[]){
  
  Test test = new Test(); // we are creating object of Test giving some memory allocation to t
   

    System.out.println(test.t);// from object we can use t
}
}

There is another way to use t directly. Make t as static , when Test class loads static t allocated with memory

It will be looking as

public class Test{
 private static int t;
 public static void main(String args[]){
 
    System.out.println(t);// t has assigned some memory, by default int has 0, so print will be 0.
}

Why all other options are wrong:

1 . Since variable t is private it can be accessed from there subclass. (Given option violates definition itself)

2. Program will give you compile time error as memory is not assigned to t which is being referred by main method.

3. This is the correct answer.

4 . variable t is not initialized but declared as int which is by default initialized to 0. (Error is not caused through this reason)

5. variable x is not initialized which we are not using it. Error is not caused through this reason.

Correct answer is t is non-static and it cannot be referenced in a static context in the main method.

Hope you got my point and must be helpful. Vote up. Thanks.

Add a comment
Know the answer?
Add Answer to:
Analyze the following code: public class Test { private int t; public static void main(String[] args)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT