Java Unit 5 writing class
public class Main { private static int n = 0; public static void bar() { Main m1 = new Main(); Main m2 = new Main(); Main m3 = new Main(); m1.foo(); } public Main() { n = n + 1; } public void foo() { System.out.println(n); } }
3
Refer to this code snippet. public class Main { private static int n = 0; public static void bar() { Main m1 = new Main(); Main m2 = new Main(); Main m3 = new Main(); m1.foo(); } public Main() { n = n + 1; } public void foo() { System.out.println(n); } } Suppose the following method is added: public void setN(int newValue) { n = newValue; } What would be the output of the program if bar() were changed to the following: public static void bar() { Main m1 = new Main(); Main m2 = new Main(); Main m3 = new Main(); m1.setN(5); m3.foo(); }
5
Accessors and Mutators are used to
Allow private data to be accessed outside of a class
Which of the following types can be permanently modified in a method when it is passed as a parameter to a method?
Any user defined class
public class Athlete { String first_name; String last_name; int jersey; public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }
Athlete athlete = new Athlete("Dirk", "Nowitzki", 41);
In 2016 Volkswagen used software to give false results on their vehicle emissions tests. Basically, they falsified results to show a "pass" when it would otherwise "fail" under normal conditions. Which of the following ACM ethical principles was most compromised by this action?
Be honest and trustworthy.
Class members that should be public are
Constructors, Accessors / Mutators, Methods
Which of the following is not part of the ACM Code of Ethics and Professional Conduct's General Ethical Principles?
Credit original creator when using other's work.
What is the difference between instance variables and static variables?
Each object has its own copy of the instance variables, but all objects share a copy of the static variables
Which of the following would be the best example of how the Internet has impacted the economy?
Email has reduced the amount of mail that is produced and shipped.
True or False: All impacts of advances in computing systems are beneficial.
False
Mark the valid way to create an instance of Foo given the following code: public class Foo { int bar; String stoo; public Foo() { this.bar = 0; this.stoo = ""; } public Foo(int bar) { this.bar = bar; stoo = "You."; } }
Foo fee; fee = new Foo();
What would the value of the static variable phrase be after the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }
Hello World!
Given the following definition for the class Athlete: public class Athlete { String first_name; String last_name; int jersey; public Athlete(String first_name, String last_name) { this.first_name = first_name; this.last_name = last_name; this.jersey = 0; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } } Which of the following are valid instantiations of the class Athlete?
I - Athlete joe = new Athlete("Joe", "Montana"); III - Athlete joe = new Athlete("Joe", "Montana", 16);
Where must a static variable be initialized?
In the class file, but not in a method.
An object's state is defined by the object's
Instance variables and their values
If you do not implement a constructor for your class,
Java creates one and give each instance variable its own value
public class Person { public String name; public Person(String name) { this.name = name; } public void changeName(String name) { this.name = name; } public void printName() { System.out.println(this.name); } }
John
Given the code snippet, public class Pokemon { private String name; private int health; public Pokemon(String name, int health) { name = name; health = health; } } what is wrong with the class definition?
Must use this in constructor when the constructor parameters have the same name as instance variables. ie: this.name = name; this.health = health;
Which of the following is a benefit of using a mutator method?
Mutator methods can verify the new value is a valid value for the instance variable
Given this code snippet, public class Athlete { public Athlete(String name) { this.name = name; } } what is missing from the class definition?
Need to declare the name instance variable
Static methods can access
Only other static instance variables and class methods
Consider the following code segment: public static String mystery(String word, int i, int j) { String mystery = word.substring(i, i+ 1); mystery += word.substring(i, j); return mystery; } Which of the following is the most appropriate precondition for the variable i in mystery so that substring does not throw an exception?
Precondition: i >= 0, i < word.length, i <= j.
Consider the following code segment: public static String mystery(String word, int i, int j) { String mystery = word.substring(i, i+ 1); mystery += word.substring(i, j); return mystery; } Which of the following is the most appropriate precondition for the variable j in mystery so that substring does not throw an exception?
Precondition: j >= i and j <= word.length.
Which of the following is true?
Primitives are returned by value. Objects are returned by reference.
Why can't this be used in static methods?
Static methods are not called using an object. Thus, this would be null.
According to the ACM's Code of Ethics, computing professionals should do all of the following EXCEPT
Teach computing classes
What is the scope of private methods and private instance variables?
The Declaring class
Given the following code public class Storm { private int lighteningCount; private int precipTotal; private String precipType; public Storm(String precipType) { this.precipType = precipType; precipTotal = 0; lighteningCount = 0; } public Storm(String precipType, int precipTotal) { this.precipType = precipType; this.precipTotal = precipTotal; lighteningCount = 0; } public Storm(String precipType, int lighteningCount) { this.precipType = precipType; this.lighteningCount = lighteningCount; precipTotal = 0; } } Which statement best describes this code?
The code will not compile because there are two constructors with the same signature.
Which of the following is NOT a characteristic of a mutator?
The method returns the value of an instance variable
Given the following code: public class TvShow { private String name; private int channel; public TvShow (String name, int channel) { this.name = name; this.channel = channel; } public void getName() { return name; } public void setName(String name) { this.name = name; } }
The return type for the getName method should be set to String.
What is the this keyword used to reference?
The this keyword references the object that called the method.
What is the difference between a getter method and an accessor method?
There is no difference, they refer to the same idea
Why do good coders use commenting?
To make their code readable for others, and to explain a specific chunk of code
What is the purpose of a mutator method?
To safely modify an instance variable
Given an instance of the Athlete class called athlete, what is the proper way to set the value of the jersey number after it has been instantiated? public class Athlete { private String first_name; private String last_name; private int jersey; public int getJersey() { return this.jersey; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }
You cannot set the jersey, since jersey is private and there is no setter method.
public class Athlete { private String first_name; private String last_name; private int jersey; public int getJersey() { return this.jersey; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }
athlete.getJersey()
public class Main { private String str = "bar"; public static void main(String[] args) { Main m = new Main("foo"); System.out.println(m.getString()); } public Main(String str) { str = str; } public String getString() { return str; } }
bar
The purpose of specifying a postcondition is to
explain the method's end result, whether it is a return value or change in an object's state
Which methods of class Foo can be called without an actual instance of the class Foo? public class Foo { public static void foo() { ... } public void bar() { ... } public void baz() { ... } }
foo()
What would be printed the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }
hi
The following function computes the hypotenuse of a right triangle. public double findHypotenuse(int side1, int side2){ double hyp = Math.sqrt(side1 * side1 + side2 * side2); return hyp; } The following code found in main throws an error. What is the bug? int side1 = 3; int side2 = 4; findHypotenuse(side1, side2); System.out.println(hyp);
hyp is a local variable. It can only be accessed in findHypotenuse.
The return type of an accessor method
must match the type of of the instance variable being accessed
It is considered good practice to
only modify objects when the method postcondition has specified the modification
The Glasses class represents a pair of eyeglasses. One of its instance variables is a Prescription object called script. The Prescription object has instance variables that stores the prescription for the left and right eye. Which of the following constructors for the Glasses class correctly sets the script instance variable correctly? Assume any method calls are valid.
public Glasses(Prescription thePrescription){script = new Prescription(thePrescription.getLeft(),thePrescription.getRight());}
Which of the following correctly uses the this keyword?
public boolean isSame(Bird other) { return this.name.equals(other.name); }
The Insect class will contain a String for the insect's name, an int for the number of legs it has, and a boolean for whether or not the insect has wings. Which of the following is the most appropriate implementations for the Insect Class?
public class Insect { private String name; private int numLegs; private boolean hasWings; //constructor and methods not shown }
Each of the methods below can be found in the Rectangle class. Which of the following methods would have access to the parameter object's private data and methods?
public void copy(Rectangle other)
public class Athlete { private String first_name; private String last_name; private int jersey; public int getJersey() { return this.jersey; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }
public void setJersey(int jersey) { this.jersey = jersey; }
Classes' access specifier is generally set to
public, so any user can set and create use objects in the class
Suppose you have the following methods defined public double increaseWidth(double num){ num += 10; return num; } public double increaseWidth(Rectangle rect){ double newWidth = rect.getWidth() * 2; rect.setWidth(newWidth); return newWidth; } Consider this code snippet double width = 10.5; Rectangle room = new Rectangle(10, 15); System.out.println(width); System.out.println(room); increaseWidth(width); increaseWidth(room); System.out.println(width); System.out.println(room); Which variable will have a different value the second time it is printed? Assume the toString method of Rectangle prints the rectangle's dimensions.
room
public double increaseWidth(double num){ num += 10; return num; } public double increaseWidth(Rectangle rect){ double newWidth = rect.getWidth() * 2; rect.setWidth(newWidth); return newWidth; } Consider this code snippet double width = 10.5; Rectangle room = new Rectangle(10, 15); System.out.println(width); System.out.println(room); increaseWidth(width); increaseWidth(room); System.out.println(width); System.out.println(room); Which variable will have a different value the second time it is printed? Assume the toString method of Rectangle prints the rectangle's dimensions.
room
Which variables are in scope at the point labeled // POINT A? In other words, which variables exist at that point in the code? public class ScopeQuiz { private int count = 0; public void printPointSums() { int sum = 0; // POINT A for(int i = 0; i < 10; i++) { sum += i; } int result = sum + count; } }
sum and count
Suppose there is a local variable declared in the method of a particular class. The local variable's scope is
the method in which is it declared
Which of the following is NOT a proper use of the keyword this?
to access the private variables of other objects of the same class
What is the purpose of an accessor method?
to return the value of an instance variable
What is the purpose of specifying preconditions?
to set the expectation for what a method should be compared to what it's going to be
A computing system that is biased is likely to
unfairly prefer a certain kind of user over other kinds of users
What is the return type of a mutator method?
usually void
What is the output of the following code snippet? int x = 8; int y = 10; // x = y + 10; y *= 2; /* y = x; x *= 3; */ System.out.println("x: " + x); System.out.println("y: " + y);
x: 8 y: 20
The Glasses class represents a pair of eyeglasses. One of its instance variables is a Prescription object called script. The Prescription object has instance variables that stores the prescription for the left and right eye.Suppose the Glasses constructor was implemented as follows public Glasses(Prescription thePrescription) { script = thePrescription; } What is the output of the following code snippet? // Create a new Prescription object Prescription reading = new Prescription(-1.25, -1.5); // Create two new Glasses objects Glasses myGlasses = new Glasses(reading); Glasses yourGlasses = new Glasses(reading); // Mutator for the prescription to change the prescription reading.updatePrescription(-1.5, -1.5); // Prints the glasses' prescription as // (Left Eye, Right Eye) e.g. (-2.0, -2.5) myGlasses.printPrescription(); yourGlasses.printPrescription();
(-1.5, -1.5) (-1.5, -1.5)
