Question: Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Try to fix the

Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Try to fix the errors by either using variables that are in scope or moving the variable declarations so that the variables have larger scope.

public class Person { private String name; private String email;

public Person(String initName, String initEmail) { name = initName; email = initEmail; }

public String toString() { for (int i=0; i < 5; i++) { int id = i; } // Can you access the blockScope variables i or id? System.out.println("i at the end of the loop is " + i); System.out.println("The last id is " + id);

// Can toString() access parameter variables in Person()? return initName + ": " + initEmail; }

// main method for testing public static void main(String[] args) { // call the constructor to create a new person Person p1 = new Person("Sana", "sana@mail.com"); System.out.println(p1); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!