CNIT 255 Exam 1 (Syntax)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

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

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

Arrays.copyOf()

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

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's a good layout manager to produce the following?

GridLayout

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

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

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

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

True

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 { ... }

What value will be returned when calling mystery5()? public static String swapAndChop(String a, String b) { String tmp = b; b = a; a = tmp; return a.substring(1) + b.substring(1); } public static String mystery5() { String first = "Abraham"; String last = "Lincoln"; String intermediate = swapAndChop(first, last); return first + " " + intermediate.substring(0, 1); } "Abraham L" "Abraham i" "Lincoln i" "Lincoln L"

"Abraham i"

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 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 is printed? System.out.println("12" + "13");

1213

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

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.)

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 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 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 (arr.length)

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.

How can you add plain-English comments to code in Java? By putting it between /* and */ anywhere in the file By putting it after // at the end of a line. Both A and B None of the above

Both A and 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

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

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.)

Can an abstract class be instantiated?

No

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

In the Model-View-Controller pattern: a. The . . . displays the data. b. The . . . handles events. c. The . . . is pure data with no visual appearance.

View, Controller, Model

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"

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

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

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

Give two examples of layouts in Swing.

a) GridLayout 2) FlowLayout

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.

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

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

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 method should you override in a subclass of JComponent to do custom painting?

paintComponent(Graphics g)

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 happens when the computer goes to run this line of code? System.out.println("String".substring(2, 6));

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

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


Ensembles d'études connexes

Absolutism/Constitutionalism Test Q?'s

View Set

Module 4: Random Variables and Introduction to Distributions

View Set

Memmlers The human body chapter 15 circulation

View Set

Chapter 26 Coagulation Modifier Drugs

View Set

Chapter 14- Retailing and direct marketing

View Set

Simulation Lab 2.2: Module 02 Install and Use Wireshark

View Set

Gr 8 Tegnologie Ratte en meganiese voordeel

View Set

Ch. 15 PrepU questions, NUR444 PrepU Ch.15, Chapter 15: Obsessive-Compulsive and Related Disorders, NSG 211 - CH 15 OCD, Ch 15 Anxiety and Obsessive-Compulsive Related Disorders, Chapter 15: Obsessive-Compulsive and Related Disorders

View Set