Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Questions Object References: You use a null reference to indicate that an o

ID: 3730009 • Letter: J

Question

Java Questions

Object References: You use a null reference to indicate that an object variable (reference) does not refer to any object. Of course, you cannot invoke methods on a null reference since there is no object to which the method would apply. Consider this program segment: String str null; System.out.println (str) str.length) System.out.println (str) 1. What problem arises when executing these statements? Do the statements produce any printout beyond an error message? If so, what printout? (2 points) 2. Explain why it would be a poor decision to make instance data public instead of private. Give an example of why this could result in a problem. (2 points)

Explanation / Answer

1. It will print "null", then it will throw NullPointerException because we are calling "length" function on NULL object

2. Because "public" data are directly accessible outside the class.

Example:

Consider a class Human.*/

public class Human

{

public int numberOfLegs;

}

public class UseHuman

{

public static void main(String args[])

{

Human h = new Human();

h.numberOfLegs = 1000000;//Ouch

}

}

/*So for better control over data, we keep class variables private and methods which operate on them are marked public. So These variables can be accessed only using your methods. And in those method you will have control over type of values being set. Modifying above code*/

public class Human

{

private int numberOfLegs;

public void setNumberOfLegs(int legs)

{

if(legs<0 || legs>2)

throw new MyCustomException("WOW!!!! You found an alien..");

numberOfLegs = legs;

}

}

public class UseHuman

{

public static void main(String args[])

{

Human h = new Human();

h.setNumberOfLegs(1000000);//Now you will get a big fat Exception

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote