About Question enthuware.ocajp.i.v7.2.1260 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
R2-D2-
Posts: 2
Joined: Mon Nov 20, 2017 7:04 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1260 :

Post by R2-D2- »

Hi Paul,

I tried to play around with the code and there's one thing I don't understand. If I have

Code: Select all

public class TestClass {
    public static void main(String[] args) {
        int j = 1;
        int i;
        try {
            i = doIt() / (j = 2);
            System.out.println(i);
        } catch (Exception e) {
            System.out.println(" j = " + j);

        }
    }

    public static int doIt() throws Exception {
        throw new Exception("FORGET IT");
    }
}
then the code will compile. (Notice that I have moved the declaration of variable i before the try block and added a println in the try).

However, if I add a

Code: Select all

System.out.println(i);
in the catch clause, or right after the catch clause, it will say the variable might not have been initialized. My question is: why does the compiler not complain in the first case?

My guess: in the first case, the compiler knows that i might not be intialized and throw an Exception, but will not complain because the println will not be executed in that case.

Could you please point out if there's a flaw in my reasoning or give a little more info on how this works?

Thanks a lot!

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1260 :

Post by admin »

Your reasoning is correct. Complier will complain only if it notices a possible execution path in which a variable will be accessed without prior initialization.


hth,
Paul.
If you like our products and services, please help us by posting your review here.

wangchit
Posts: 1
Joined: Thu Nov 30, 2017 5:24 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1260 :

Post by wangchit »

I run the code and get the result j=1.
But the answer is "it will not compile". Why?

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1260 :

Post by admin »

I see that option 1 i.e. It will print j =1 is indeed set as the correct option.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 42 guests