Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please explain Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please explain" Watch "Please explain" New topic

Please explain

ketki kalkar
Ranch Hand

Joined: May 09, 2007
Posts: 36
What is the output of the following code?

public class TestLocal {
public static void main(String args[]) {
String s[] = new String[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();
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

Joined: Oct 02, 2003
Posts: 11955

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
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

Joined: Jun 04, 2007
Posts: 320
I see what you mean, Fred!

SCJP - 86% - June 11, 2009
Henry Wong

Joined: Sep 28, 2004
Posts: 20535

"ketki kalkar",

Please Quote Your Sources.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Gaurav Pavan Kumar Jain
Ranch Hand

Joined: Mar 19, 2007
Posts: 168
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
I agree. Here's the link:
subject: Please explain
It's not a secret anymore!