CNIT 255 Exam 1

¡Supera tus tareas y exámenes ahora con Quizwiz!

Fill in the blank below so that we can call b's printName() method: public class A { public String getName() { return "A"; } } public class B extends A { public String getName() { return "B"; } public void printName() { System.out.println(getName()); } public static void main(String args[]) { A b = new B(); ___________________ } }

( ((B)b).printName(); )

What is printed? System.out.println("12" + "13");

(1213)

How many integers are created? int multi[][] = new int[4][4];

(16) Note that any uninitialized values in a Java int array are automatically initialized to 0.

What happens when the computer goes to run this line of code? System.out.println("String".substring(2, 6));

(it prints "ring")

Write a short snippet of code to remove the spaces from the beginning and end of the following AND convert what's left to all lower case: String s = " NeAtJaVa ";

(s = s.trim().tolowerCase(); // or similar)

Compare and contrast the this and super keywords

(this is a magic variable referring to the current object within an instance method, and can be used to disambiguate variables with the same name. super is a reference to the super class.)

What Java expression can you write to tell if x is not smaller than 2?

(x >= 2)

What is printed? int x = 0; x += x++; System.out.println(x);

0

Given the following function: void doubleValue(int value) { value = value * 2; } What will be the value of number after the following code is executed? int number = 10; doubleValue(number);

10 (doubleValue receives a copy of value, any changes it makes are only made to the local copy).

What would be the output of the following program? public static void main(String[] args) { int[] primes = {11, 13, 17, 19, 23, 29}; System.out.println(primes[1]); System.out.println(primes[5]); }

13 29

Which fields can a subclass access from a superclass? ❏ public ❏ private ❏ protected

1st and 3rd

Given the following class: class ValueHolder { private int value = 10; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } And the following method: void doubleValue(ValueHolder holder) { int currentValue = holder.getValue(); holder.setValue(currentValue * 2); } What will be written to console after the following code is executed? ValueHolder holder = new ValueHolder(); doubleValue(holder); System.out.println(holder.getValue());

20 (Here, we're using an object of type ValueHolder, which is mutable because of the setValue function. doubleValue receives a copy of a reference to the ValueHolder object. Using that reference it can call the function setValue to mutate the actual object).

What is the output of the following code? class A { public int compute(int a,int b) { return a + b; } } class B extends A { @Override public int compute(int a, int b) { return a * b; } } public class Main { public static void main(String[] args) { A a = new B(); System.out.println(a.compute(10,20)); } }

200

Mark all that are true: ❏ In Java, "Global Data" is allowed to exist outside of a class. ❏ Any variable that isn't a "primitive value" is an object. ❏ An "instance" of a class C is an object of type C. ❏ OOP stands for "Object-Oriented Procedures."

2nd and 3rd

Mark all that are true of constructors: ❏ Calling a constructor creates a new class. ❏ Are called when you use the new keyword. ❏ Do not have a return type. ❏ Must have the same name as the class they're defined in. ❏ Can only have a single parameter.

2nd, 3rd, 4rth

What is printed? int x = 1; while(x < 5) { x = 2*x + 1; } System.out.println(x);

7

What is printed? public class Mystery { static int x = 2; public static int someFunc(int y, int x) { x = x+y; return x; } public static void main(String args[]) { int x = 3; Mystery.x = someFunc(x, Mystery.x); System.out.println(x+Mystery.x); } }

8

How can you make sure you're overriding a method rather than just accidentally introducing a new method?

@Override

How can you print the String "hello" in Java? A) System.out.println("hello"); B) printf("hello"); C) "hello".print(); D) println("hello"):

A

How do you find the length of an array "arr"? A) arr.length B) arr.length() C) arr.size D) arr[-1] E) System.array.length(arr);

A

What best describes the "String [] args" in a main() method? A) It allows someone to pass arguments into your program when they run your code. B) It explains to the compiler that your program is to be run from the command line instead of double clicked from the desktop. C) It defines a variable called String of type args. D) It's not typed right and will cause a compile-time error.

A

Which describes Java? A) Object Oriented B) Architecture-Neutral C) Multithreaded D) All of the above.

A

if "class X extends Y", which is most true?

A

Which conversions are "automatic"? List all that apply: A) int => double B) double => int C) char => int D) long => int E) double => short

A and C

Which is true of the char data type? (list all that apply) A) It is considered one of the four "integer" variable types B) It represents a unicode character by mapping a numerical value to a glyph. C) The maximum numerical value it can hold is 255. D) char literal values are typed in java programs using double quotes (e.g. "A") E) Some char literal values need a slash (\) in front of them.

B and E

True or false - when using add(), you can only add an element at the end of an ArrayList. ❏ true ❏ false

F

True or false: two methods with the same name and parameters can co-exist in the same class if they have a different return type. ❏ true ❏ false

F

What keyword do you put in front of ints and doubles to make them constants?

Final

Name as many floating number types in Java as you know:

Float and Double

Fill in the missing code: Print all days of the week using a regular for loop: String[] weekDays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; . . . { String day = . . . System.out.println(day); } Print all Mondays in December 2019 using a while loop: int firstMondayOfDecember = 2; int daysInAWeek = 7; int daysInDecember = 31; int value = firstMondayOfDecember; System.out.println("Monday dates in December:"); . . . { System.out.println(value); . . . }

For (int index = 0; index < weekDays.length; index++){ String day = weekDays[index]; System.out.println(day); } while (value <= daysInDecember){ System.out.println(value); value+=daysInAWeek; }

What is method overloading?

Method overloading allows us to have different methods with the same name, but different parameters (number of parameters, order of parameters, and/or data types of parameters).

You have a class: public class Student { private String name = "MyName"; public Student(String value) { String name = value; } public String getName() { return name; } } What will be printed after the following code executes?

MyName. The constructor is defining a new String name that is locally defined. This name is different than the name which is the instance variable.

Suppose you have a correctly written java file, "MyClass.java". When it is compiled, what new file will be produced?

Myclass.class

What is a method signature?

Name + parameter types = Method signature.

As opposed to declaring an array, what keyword actually creates an array?

New

Can an abstract class be instantiated?

No

Why does it make sense that the main() method must be static?

No object exists yet upon which we can call a regular method, when a program first starts

What happens when the following is run? Point x = null; Point x2 = new Point(3, 3); System.out.println("The two x coordinates added: " + x.getX() + x2.getX())

NullPointerException

What are related classes grouped into, in Java?

Packages

In your own words, how can and how can't a method alter variables passed by the calling function?

Primitive variables can never be altered by calling a function on them. Objects can not be reassigned by calling a method on them, but just as final objects can have their state changed, so can objects passed as parameters to methods be altered.

What's the difference between public and private instance variables? What Object-Oriented Programming (OOP) principle does the keyword private facilitate?

Public instance variables can be accessed from anywhere. Private instance variables can only be accessed from within the class. Encapsulation.

Write a little Java to read the next integer from System.in:

Scanner in = new Scanner(System.in); int x = in.nextInt();

What is the difference between static and non-static fields/functions?

Static fields/functions can be used anywhere by referring to the class, while non-static fields/functions are only accessible through actual objects.

Assume we have two Integer objects, num1 and num2. a) How can we test if num1 is equal to num2? b) How can we test if num1 is smaller than num2? (Hint: Look at the Integer class in the Java API)

a) num1.equals(num2) b) There are multiple ways. First off, you can call intValue() on each Integer object, then compare the two resulting ints as normal: num1.intValue() < num2.intValue(); OR you can use compareTo: num1.compareTo(num2) < 0; OR you can simply compare them as if they were regular ints: num1 < num2. The last one works because the comparison operator "<" is not defined for objects, and both Integer objects will automatically be compared as int.

Would an if/else chain or a switch statement be better for each of these programs? Why? a) Performing a specific action based on character input from the keyboard. 'q' - quit. 'c' - continue. 'y' - yes. 'n' - no. 'h' - help. b) Changing power level based on temperature data from a thermometer every 5 minutes. a. Below -10°C --> 100%. b. Between -10°C and 10°C --> 80%. c. Between 10°C and 25°C --> 60%. d. Greater than 25°C --> 40%

a) switch is often preferable when you need to choose between multiple predefined values, based on 1 variable. b) if/else because you can't use conditions with switch. But they are easy to use with if/else.

In your own words, what's the difference between break and continue?

continue skips the rest of the current iteration of a loop; break skips the rest of the loop altogether

True or false: if you try to cast to an invalid type the result is null. ❏ true ❏ false

false - either the compiler won't even let you run the program, or you'll get a ClassCastException

True or false: all instance fields of an object are initialized to null if you don't assign to them explicitly. ❏ true ❏ false

false - this is correct for object variables, but primitives become 0/false

Write some code that executes only in the event that x is less than -2?

if (x < -2) { ... }

Simplify this code so that far fewer nested blocks are needed (you do not need to worry about code represented by "..."): if (x == 0) { ... } else { if (x == 1) { ... } else { if (x == 2) { ... } else { if (x == 3) { ... } else { ... } } } }

if (x == 0) { ... } else if (x == 1) { ... } else if (x == 2) { ... } else if (x == 3) { ... } else { ... }

How would you import every class in the java.util package without tediously importing each one, one at a time?

import java.time.*;

Find the sum of the numbers using a "for each" loop: int numbers[] = new int[]{1,2,3,4,5,6,7,8,9,10};

int sum = 0; for(int n : numbers) sum += n;

What is a benefit of marking variables "private"?

it forces access to variables to be encapsulated in getters and setters

What is the difference between the variables declared on these two lines: int x; int y[];

one is a single integer; another is an array

Fill in the comments by explaining what each section of code does: public class ArrayExamples { public static void main(String[] args) { // © Sedgewick and Wayne int n = 10; // _____________________________ double[] a = new double[n]; for (int i = 0; i < n; i++) { a[i] = Math.random(); } // _____________________________ for (int i = 0; i < n; i++) { System.out.println(a[i]); } // _____________________________ double m = Double.NEGATIVE_INFINITY; for (int i = 0; i < n; i++) { if (a[i] > m) m = a[i]; } System.out.println(m); // ____________________________ double s = 0.0; for (int i = 0; i < n; i++) { s += a[i]; } System.out.println(s / n); // ____________________________ double[] b = new double[n]; for (int i = 0; i < n; i++) { b[i] = a[i]; } } }

public class ArrayExamples { public static void main(String[] args) { // © Sedgewick and Wayne int n = 10; // initialize array of size 10 to random values // between 0 and 1 double[] a = new double[n]; for (int i = 0; i < n; i++) { a[i] = Math.random(); } // print array values, one per line for (int i = 0; i < n; i++) { System.out.println(a[i]); } // find the maximum and print it double m = Double.NEGATIVE_INFINITY; for (int i = 0; i < n; i++) { if (a[i] > m) m = a[i]; } System.out.println(m); // find the average and print it double s = 0.0; for (int i = 0; i < n; i++) { s += a[i]; } System.out.println(s / n); // make an array copy double[] b = new double[n]; for (int i = 0; i < n; i++) { b[i] = a[i]; } } }

Read the following classes: import java.time.LocalDate; class Employee { // Fields private String name; private double salary; private LocalDate hireDay; // Constructors public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; hireDay = LocalDate.of(year, month, day); } // Methods public String getName() { return name; } } public class EmployeeMaker { ___________________________ }

public class EmployeeMaker { public static void main(String[] args) { Employee e = new Employee("My Name",100000,1998,7,7); System.out.println(e.getName()); } } DateTimeException

Change the following class so that all instance fields are initialized to the same values here, but inside of a constructor that takes no parameters: public class Lecture8Challenge { int x = 2; double d = 3.4; String s; boolean myBool = false; }

public class Lecture8Challenge { int x; double d; String s; boolean myBool; public Lecture8Challenge() { x = 2; d = 3.4; s = null; myBool = false; } }

Rewrite this to have better design (hint: create a Person class that contains a firstName and lastName, and a Couple class that has two Person objects): public class Couple { public String spouse1FirstName; public String spouse1LastName; public String spouse2FirstName; public String spouse2LastName; public void setNames(String fN1, String lN1, String fN2, String lN2) { spouse1FirstName = fN1; spouse1LastName = lN1; spouse2FirstName = fN2; spouse2LastName = lN2; } }

public class Person { private String firstName; private String lastName; public Person(String f, String l) { firstName = f; lastName = l; } } public class Couple { private Person spouse1; private Person spouse2; public Couple(Person s1, Person s2) { spouse1 = s1; spouse2 = s2; } }

Add three more object types of your choice to Person as instance variables, and write the code for those three classes. For example, you may use objects such as Contact and Address. You do not need to write any methods or constructors, just the types/names of instance fields contained in each class.

public class Person { private String name = "MyName"; private int age = 25; private Contact contact; private Address address; private Pet pet; public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class Address { private String streetAddress1; private String streetAddress2; private String city; private String state; private String ZIP; private String country; } public class Contact { private String email; private String cellphone; private String officePhone; private String faxNumber; } public class Pet { private String name; private String animalType; private int age; private double weight; }

Add get / set methods to this class. Name should be read-only. Age should be both readable and writeable. public class Person { private String name = "MyName"; private int age = 25; }

public class Person { private String name = "MyName"; private int age = 25; public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

Create a constructor for the following class: public class Person { private String name; private int age; }

public class Person { private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } }

Fill in the blank in the following function, so that the returned value will be 9: public int test() { int[] a = {1,2,3,4}; int sum = 0; for(int i = . . .; i < a.length; i++) { sum+=a[i]; } return sum; }

public int test() { int[] a = {1,2,3,4}; int sum = 0; for(int i = 1; i < a.length; i++) { sum+=a[i]; } return sum; }

Write a small program to add all of the letters of the alphabet to an ArrayList<String> ; then remove the five vowels; then print the remaining list elements.

public static void main(String args[]) { java.util.ArrayList<String> list = new java.util.ArrayList<String>(); for(char c = 'A'; c <= 'Z'; c += 1) { list.add("" + c); } list.remove("A"); list.remove("E"); list.remove("I"); list.remove("O"); list.remove("U"); for(String s : list) { System.out.println(s); } }

What does the Scanner class do?

reads input from the console (or from a String)

Name everything you can that's missing? Scanner scanner = new Scanner(System.in); System.out.print("How many things are there, and I'll print the Engish to use..."); int x = scanner.nextInt() switch(x) case 1: System.out.println("one"); break; case 2: System.out.println("a couple") case 3: System.out.println("many");

semicolon on x=; semicolon on println() for couple; braces on switch; break on most cases; default case

What's wrong with the code below? Point x = new Point(2, 3); Point y = new Point(3-1, 5-2); if (x = y) { System.out.println("Equal!"); }

should be ==. Except == is unreliable; so should use x.equals(y). Even then, if the programmer has not implemented equals(), it won't work right.

Correct the error in the following code: public class ArrayExample { public static void main (String[] args) { int[] arr = new int[2]; arr[0] = 10; arr[1] = 20; for (int i = 0; i <= arr.length; i++) System.out.println(arr[i]); } }

should be less than instead of less than or equal to

True or false: even if not in the .java file, a class always has at least one constructor. ❏ true ❏ false

true - the default "no-argument" constructor is always implied if others are not present

What's "strange" about Math.sqrt()?

We didn't need to create an instance of type Math to call sqrt()

When might you prefer an ArrayList over an Array?

When you don't know how many elements you're going to need ahead of time. Or you want to make use of add() and remove()

What is the output of the following code? public class SimpleOperations { public static void main(String[] args) { double a = 10.5 % 2; double b = 3.5 * 2; double c = 6.8 / 2; System.out.println("a => " + a + " b => " + b + " => c " + c); } }

a => 0.5 b => 7.0 => c 3.4

Name 3 differences between Array and ArrayList in Java.

a) Array has a fixed size. ArrayList has a dynamic size. b) Array can contain both primitives and objects. ArrayList can only contain objects. c) Array members are accessed using []. ArrayList has methods.

How is a constructor different from other methods?

a) Constructors initialize objects being created with the new keyword. b) Constructors are not called directly. They are called implicitly when using new. Methods can be called directly on an object that has already been created. c) Constructors must have the same name as the class name. Constructors cannot return anything (implicitly, the object itself is returned). Methods must declare the return value, even if it is just void. d) Constructors and methods both can have parameters, modifiers (public, private, etc.), and method bodies in braces.

Read the following example. A) How does it use encapsulation? B) How does it use inheritance? C) How does it make polymorphism possible? abstract class Animal{ public abstract void makeSound(); } class Dog extends Animal{ private static final String sound = "bark"; @Override public void makeSound() { bark(); } public void bark(){ System.out.println(sound); } } class Cat extends Animal{ private static final String sound = "meow"; @Override public void makeSound() { meow(); } public void meow(){ System.out.println(sound); } }

A) Encapsulation: Dog and Cat both have their sound as private. B) Inheritance: Dog and Cat extend the Animal abstract class. C) Polymorphism: If you create a variable of type Animal, you can assign the variable to an object of type Dog or Cat. You can then call makeSound on this variable, regardless of whether it was assigned to a Cat or a Dog object. This is known as run-time polymorphism.

In the example above: A) class A is the ____class of class B. B) class B is a ____class of class A. C) a.compute is an example of ____ binding.

A) class A is the superclass of class B. B) class B is a subclass of class A. C) a.compute is an example of dynamic binding.

Mark all statements that are valid "best practices" to use when writing code: ❏ Attempt to minimize the number of variables in your classes. ❏ Mark variables private where possible. ❏ Always initialize data. ❏ Use descriptive names for methods, fields, and classes. ❏ Break up classes with too many responsibilities into two or more other classes.

All apply

What is an abstract function? When should we use it?

An abstract function is a function that has no implementation. We use it when we want our subclasses to provide the implementation for it.

How can you make a "true copy" of an array?

Arrays.copyOf()

static fields: A) Are methods that are called when a program is first created. B) Exist once per class, and represent a single "shared" variable no matter how many instances of a class exist. C) Are constant. D) Are dangerous sources of electro-static discharge

B

Assuming this compiles and runs, what is printed? SomeClass x = new SomeClass(); x.y = 3; SomeClass x2 = x; x2.y = 4; System.out.println(x.y + x2.y); A) 6 B) 7 C) 8 D) 34

C

How do you get the number of elements in an ArrayList called list? A) list.size B) list.length C) list.size() D) list.length()

C

What best describes a String? A) It is a primitive variable type in Java B) One can be created by putting it in single quotes, 'like this' C) Strings are sequences of unicode characters. D) You can only call a method on a String if you put it in a variable first.

C

What does it mean for a method to be "overloaded"? A) It's trying to do too much. B) It's being called with too many parameters. C) There are two or more versions of the method, differentiated in the number, order, or type of parameters they take. D) The method has been redefined in a different class.

C

What is true of a static method? A) It has no this variable while it is executing. B) Within its containing class, it can only access static fields. C) All of the above.

C

What will the value of x be after the following expression is evaluated? int x = 14 % 10 + 5 / 4; A) 5.25 B) 2.65 C) 5 D) 2

C

Which describes the origins of Java? A) Java was invented in in 2000. B) Java has always been used mostly at the server level, since it could not compete with better options for dynamic content in the browser. C) Java was considered reasonably safe and secure, running in a limited "sandbox." D) Oracle, who invented Java, made sure Netscape, Internet Explorer, and the other major browsers at the time had a unified version of Java built into them.

C

What are some techniques for naming initialization parameters in a constructor that you want to copy to an instance field? A) Name the initialization parameter as the first letter in the field name. B) Add a dummy prefix to the initialization parameter, i.e., name becomes aName. C) Make use of this inside the constructor, and name the parameter the same as the field. D) All of the above.

D

Which is guaranteed, of String s = "abc".substring(0, 0); A) It will prevent the file it's in from compiling B) s == null is guaranteed to evaluate true C) s == "" is guaranteed to evaluate true D) "".equals(s) is guaranteed to evaluate true E) s has non-zero length F) it will crash the program when it goes to run

D

Which line (A, B, C, or D) contains an error? public class Test { static int varA = 1; int varB = 2; void functionA(){ System.out.println(varA); //A System.out.println(varB); //B } static void functionB(){ System.out.println(varA); //C System.out.println(varB); //D } }

D

Why might you ever use a do/while loop instead of a regular while loop? A) You wouldn't - do/while isn't a valid Java construct. B) It lets you define variables used in the loop conditional that go away when the loop is done. C) It saves the value of the loop expression and checks that only after running the loop. D) It guarantees that the loop will run at least once.

D

What is returned by Math.pow(3,2) A) "bang!bang!bang! bang!bang!bang!" B) 8 C) 9 D) 8.0 E) 9.0

E

What does it mean when we say that String is immutable?

We cannot change a String object. We can change where a String variable points to, but not the object itself. Example: String s1 = "Original"; String s2 = s1; // s1 and s2 now point at the same string - "Original" s1 = "Novel!"; System.out.println(s2); // still prints "Original"

Write down the output of each println in the following program: public class StringMethods { public static void main(String[] args) { String str = "Java Fundamentals"; System.out.println(str.charAt(5)); System.out.println(str.startsWith("java")); System.out.println(str.endsWith("tals")); System.out.println(str.indexOf("men")); System.out.println(str.lastIndexOf("a")); System.out.println(str.replace("Fund", "Coll")); System.out.println(str.substring(3)); System.out.println(str.substring(1, 5)); System.out.println(str.toLowerCase()); System.out.println(str.toUpperCase()); } }

System.out.println(str.charAt(5)); // F System.out.println(str.startsWith("java")); // false System.out.println(str.endsWith("tals")); // true System.out.println(str.indexOf("men")); // 10 System.out.println(str.lastIndexOf("a")); // 14 System.out.println(str.replace("Fund", "Coll")); // Java Collamentals System.out.println(str.substring(3)); // a Fundamentals System.out.println(str.substring(1, 5)); // ava System.out.println(str.toLowerCase()); // java fundamentals System.out.println(str.toUpperCase()); // JAVA FUNDAMENTALS

True or false - the first element in an ArrayList called list, assuming it contains elements, is list.get(0). ❏ true ❏ false

T

True or false: all classes belong to a package of some kind. ❏ true ❏ false

T

True or false: two classes are allowed to have the exact same name as long as they are in different packages. ❏ true ❏ false

T

True or false: you are allowed to change the state of a final variable (e.g., the "name" or "salary" instance field of an Employee variable). ❏ true ❏ false

T

The ____ keyword is used to invoke a superclass constructor.

The SUPER keyword is used to invoke a superclass constructor.

Look at the following class. A) Is it well encapsulated? B) Why is encapsulation important? public class BankAccount { public String accountHolder; public float money; public BankAccount(String accountHolder, float money) { this.accountHolder = accountHolder; this.money = money; } }

This class is not well encapsulated. Its instance variables are public and therefore accessible to anyone. Encapsulation is important to limit the access of data to certain classes. Otherwise, data that can be read/written from anywhere can lead to hard-to-find bugs.

Here's a crazy for loop. What does it print? for(boolean b = true; b; b = !b) { System.out.println(b); }

True


Conjuntos de estudio relacionados

MBA 689 New Prod Development Mid-Term-Ch. 5

View Set

Core Subject EC-6: Social Studies

View Set

Chapter 7 (Electron Transport Chain)

View Set

Fundamentals of Nursing Book End of Chapter Questions

View Set

Social Media and Youth Development

View Set

Chapter 11:Corporate Governance, Social responsibility, and Ethics

View Set