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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started