0

I have this code below and it does not worked. However if I declare Integer variable before while loop it can worked. The output will be printed.

        query = "SELECT COUNT(*) AS tot_by_code FROM `hr` WHERE `hr`.`code` = ?";              
        st = conn.prepareStatement(query);
        st.setString(1, code);
        rs = st.executeQuery();

        //Integer tot_by_code = null;
        while (rs.next()) {
            Integer tot_by_code = rs.getInt("tot_by_code");
        }


        System.out.println("Total patient by code : " + tot_by_code);

I check other thread and supposedly you can declare variable before loop or inside loop so why I can't ran my code with variable declaration inside while loop? Thanks in advance.

0

2 Answers 2

4

You can declare it inside the loop. The problem is that it will then only be visible in that loop, so you won't be able to access it outside. If you want to print it outside, you have to declare it outside as well.

For details about scope, see JLS §6.3.

In particular:

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears

Sign up to request clarification or add additional context in comments.

Comments

2

did you see that, tot_by_code wrapped in a brackets, that is called variable scope. so out side of the scope nobody know about that tot_by_code..

 System.out.println("Total patient by code : " + tot_by_code);

but here you are trying to access outside of the scope. so declare before the loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.