This textbook is available atAmazon.com Logo
Java Programming 9th Edition

Java Programming (9th Edition)

Book Edition9th Edition
Author(s)Farrell
ISBN9781337397070
PublisherCengage
SubjectComputer Science
Understanding Blocks and Scope
TWO TRUTHS & A LIE
Overloading a Method
TWO TRUTHS & A LIE
Learning About Ambiguity
TWO TRUTHS & A LIE
Creating and Calling Constructors with Parameters
TWO TRUTHS & A LIE
Learning about the this Reference
TWO TRUTHS & A LIE
Using static Fields
TWO TRUTHS & A LIE
Using Automatically Imported, Prewritten Constants and Methods
TWO TRUTHS & A LIE
Understanding Composition and Nested Classes
TWO TRUTHS & A LIE
Chapter 4, Understanding Blocks and Scope, TWO TRUTHS & A LIE, Exercise 01
Page 177

TWO TRUTHS & A LIE

 

1. A variable ceases to exist, or goes out of scope, at the end of the block in which it is declared.

 

2. You cannot declare the same variable name more than once within a block, even if a block contains other blocks.

 

3. A class's instance variables override locally declared variables with the same names that are declared within the class's methods.

Explanation

//This is an example of number 1
//You can see that x is declared inside an if block. After the if block you can declare x again as x does not not exist anymore //after the if block
if(true){
    int x = 1;
}
int x = 1;


//This is an example of number 2. This code will give a definition error because x is already defined in the block, whether another x is defined in another block inside the previous block
if (true) {
    int x = 1;
    if (true) {
        int x = 1;
    }
}


//This is an example of number 3. We created another class Test with variables x and y. And then also declared variables x and y in the main method. x and y of Test does not override local variables x and y.

public class TestMain {

    public static void main(String[] args) {
        Test test = new Test();
        int x;
        int y;
        test.x = 1;
        test.y = 1;
        x = 1;
        y = 1;
    }


}

class Test{
    int x;
    int y;
}

Answer

Answer:

1 and 2 is True

3 is a Lie

Did you like this example?
Subscribe for full access
Page 177