Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain

 
ketki kalkar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
What is the output of the following code?

public class TestLocal {
public static void main(String args[]) {
String s[] = new String[6];
System.out.print(s[6]);
}
}

A) A null is printed
B) Compile time error
C) Exception is thrown
D) null followed by 0 is printed on the screen
answer is D.

What is the result of the following code?

public class MyTest {
int x = 30;
public static void main(String args[]) {
int x = 20;
MyTest ta = new MyTest();
ta.Method(x);
System.out.println("The x value is " + x);
}
void Method(int y){
int x = y * y;
}
}

A) The x value is 20.
B) The x value is 30.
C) The x value is 400.
D) The x value is 600.

answer is A.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the easiest way to find out what the output is would be to run it and see!!!

Once you've done that, if you don't understand the answer, or have questions, come back and ask. but just telling you the answer isn't the best way for you to learn.
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For your first question the correct answer is C. I'm getting

java.lang.ArrayIndexOutOfBoundsException: 6

The array only has indices 0-5 since you explicitly set its size to 6.


Your second question involves the scope of the variable x. When you get to the print statement at the end of the code, the local variable x = 20 is the one in scope, so it is the one used. The local variable in the main method hides the object instance variable during the execution of main. The variable x inside the Method method goes out of scope as soon as the method returns.
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see what you mean, Fred!
 
Henry Wong
author
Marshal
Pie
Posts: 21003
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"ketki kalkar",

Please Quote Your Sources.

Thanks,
Henry
 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folk

The correct answer of

Ques 1 is answer c because array size is of 0-5 total six. So it throws ArrayIndexOutofBond exception.

Ques2 answer is 20 because method Method() does not returns the value.So it prints 20
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic