Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

automatic variable has not been initialized. problem.

 
Pankaja Shinde
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. class Car
2.{
3.static int milesPerGallon;
4.int index;
5.
6.Car(int mpg) {
7.milesPerGallon = mpg;
8.index = 0;
9.}
10.Car() {
11.}
12.
13.public static void main(String[] args) {
14.int index;
15.Car c = new Car(25);
16.
17.if (args.length > 0)
18.if (args[index].equals("Hiway"))
19.milesPerGallon*= 2;
20.System.out.println("mpg: " + milesPerGallon);
21.}
22.}

Options

1. The code compiles and displays "mpg: 50" if the command-line argument is "Hiway". If the command-line argument is not "Hiway", the code displays "mpg: 25".
2. The code compiles and displays "mpg: 50" if the command-line argument is "Hiway". If the command-line argument is not "Hiway", the code throws an ArrayIndexOutOfBoundsException.
3. The code does not compile because the automatic variable named index has not been initialized.
4. The code does not compile because milesPerGallon has not been initialized.
5. The code does not compile because the no-args constructor is not written correctly


Correct Answer : 3

why ?
As i think index is initialized in the constructor call at line 8. Then why option c is correct.
Explain.

pankaj shinde

 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable index declared in Class car is not static. So main method cannot access non static variables directly without having an instance of the class.
Secondly, index variable declared in main method is not initialized but trying to use it and hence the compilation error.
 
Antonio Trapero
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look variable index inside main. It iss shadowing instance variable inside main block. Cause it has not been initialized, you get a compilation error.
 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess its not even shadowing because index variable in class cannot be accessed by main() method at all.
 
Antonio Trapero
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep, you are right.No shadows here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic