java

Ace your homework & exams now with Quizwiz!

Match the following Boolean operators with their symbol. and or not equals not equals

&& || ! == !=

Given the following (partial) GameCharacter class definition, which represents a character in a video game, create 3 constructors. 1) Parameterized constructor 2) Default constructor - name should be initialized to empty string, all other characteristics should be initialized to zero. 3) Copy constructor public class GameCharater { private String mName; private int mStrength; private int mDexterity; private int mIntelligence; private double mHealth; //3 constructors; //1) parameterized constructor //2) default constructor //3) copy constructor }

// parameterized constructor public GameCharacter(String mName, int mStrength, int mDexterity, int mIntelligence, double mHealth) { mName = name; mStrength = strength; mDexterity = dexterity; mIntelligence = intelligence mHealth = health; } // default constructor public GameCharacter () { mStrength = 0; mDexterity = 0; mIntelligence = 0; mHealth = 0; mName =(); } Copy consturctor public GameCharacter (GameCharacter other) { mName = other.mName; mStrength = other.mStrength; mDexterity = other.mDexterity; mIntelligence = other.mIntelligence; mHealth = other.mHealth; }

What String literal will be assigned to the variable yearPart when the following code is executed? String oCCFoundedDate = "01/01/1947"; String yearPart = oCCFoundedDate.substring(5);

/1947

What String literal will be assigned to the variable monthPart when the following code is executed? String oCCFoundedDate = "01/01/1947"; String monthPart = oCCFoundedDate.substring(0,1);

0

What output is produced by the following code? int count = 0; while (count <5) { Sys.out.println(count); count++; } Sys.out.println("count after loop = " + count)

0 1 2 3 4 count after loop = 5

What output is produced by the following code? int count = 0; do { Sys.out.println(count); count++; }while (count <5); Sys.out.println("count after loop = " + count)

0 count after loop = 1

When the following array is declared, what will be the initial value of each of its elements? double [ ] [ ] grades = new double[30][10];

0.0

Assume the variables: int u = 2, v = 3, w = 5, x = 7, y = 11; have been declared and given values. What is the value of the following expression? u + (y % v) * w + x

19

How many elements are in the following array? double[ ][ ] sales = new double[6][4];

24

Given the following two-dimensional array declaration: double [ ] [ ] grades = new double[30][10]; What will the code: System.out.println(grades.length); output?

30

What is the value of the variable sum after the following loop executes? int sum = 0; for (int i = 0; i < 20; i+=3) sum += i;

63

How many iterations (repetitions) does the following loop encounter? int sum = 0; for (int i = 0; i < 20; i+=3) sum += i;

7

Consider the following fragment of code (assume the integer variable x has already been declared): if ( x > 5) Sys.out.println("A") else if (x < 10) Sys.out.println("B") else Sys.out.println("C") What is displayed if x has the value 11?

A

What are the differences between Java applications and Java applets?

A Java applet runs under the control of a browser, whereas an application runs stand-alone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources.

What is the purpose of an try statement in Java?

A block of code containing instructions that may cause an interruption in the normal flow of execution.

What is the purpose of a catch statement in Java?

A block of code in which errors are caught and handled accordingly.

What is the purpose of a finally statement in Java?

A block of code that executes whether an error occurs or not; this block is generally used for cleanup operations.

What is the purpose of a "class" in Java?

A class serves as a category (blueprint or design) of an entity and can be used to create many objects.

What is a constant in Java?

A constant is a named location in memory for values that will not change.

What is a constructor?

A constructor is a special method that instantiates new objects.

What are the differences between a while loop and a do-while loop?

A do-while loop always executes its loop body at least once. A while loop may or may not execute its loop body. Do-while loops are post-test, but while loops are pre-test.

What are the differences between a for loop and a do-while loop?

A for loop is a counter-controlled loop. A do-while loop is not. For loops are pre-test, but do-while loops are post-test.

What is the purpose of a static method inside a class definition?

A static method belongs to the class (not an instance of it). Static methods use no instance variables, but will usually take input from parameters, perform some actions on it and sometimes return a result.

What is the purpose of a static variable inside a class definition?

A static variable means there will only be one copy for the entire class. All instances of the class share and potentially impact this one variable.

When referring to arrays, what is an element?

An element refers to the value at a certain position in the array.

What is a logical error?

An error that occurs when output of the program does not match with what the programmer expected.

What is a syntax error?

An error that occurs when there is an issue in the writing of the code itself (e.g. programmer forgot a semi-colon at the end of a statement)

What is the purpose of an Exception in Java?

An event that occurs during the execution of a program that disrupts the normal flow of instructions.

When referring to arrays, what is an index?

An index refers to a certain position in the array.

What is an object (in Java)? How is an object different from a class?

An object is an entity that encapsulates data (instance variables) and behavior (methods), while a class is a blueprint for a type (category) of objects.

onsider the following fragment of code (assume the integer variable x has already been declared): if (x >5) Sys.out.println("A"); else if (x < 10) Sys.out.println("B"); else Sys.out.println("C"); What is displayed if x has the value 4?

B

In ascending (smallest to largest) lexicographic order, how would the following Strings be ordered? "Hi" "hi" "human" "HUmor" "bye" "Bye"

Bye HUmor Hi bye hi human

Which of the following situations would generate an exception in Java? (Select all that apply)

Dividing a quantity by zero Accessing an array at the same index as its length Attempting to write to a file in Java, but the file does not exist.

What is the purpose of "enums" (enumerations) in Java?

Enums represent a set of related constants.

Consider the following fragment of code: double courseAverage = 99.95; char courseGrade; if ( courseAverage >= 90 && courseAverage <= 99.9 ) courseGrade = 'A'; else if ( courseAverage >= 80 && courseAverage <= 89.9 ) courseGrade = 'B'; else if ( courseAverage >= 70 && courseAverage <= 79.9 ) courseGrade = 'C'; else if ( courseAverage >= 60 && courseAverage <= 69.9 ) courseGrade = 'F'; What letter will courseGrade be assigned?

F

What output is produced by the following code? for (int n = 1; n <= 5; n++) { if (n == 3) System.exit(0); Sys.out.println("Hello"); } Sys.out.println("After the loop.");

Hello Hello

Java is what type of programming language?

High-level, object-oriented programming language

When a programmer creates a Java Applet, what is the name of the class s/he needs to extend? For example: public class MyJavaApplet extends ______

JApplet

Match the following descriptions to their correct JOptionPane dialogs. Displays output to a user graphically. Replaces System.out.println(). Receives input from the user via a text box. The input is read in as a String. Receives input from the user via a button. The input is read in as an integer value. Receives input from the user. Can be used with custom button text (such as "Yep" "Nope" instead of "Yes" "No") and even custom icons.

JOptionPane.showMessageDialog() JOptionPane.showInputDialog() JOptionPane.showConfirmDialog() JOptionPane.showOptionDialog()

What are Java packages?

Java packages are unique namespaces, similar to directory structures, in which Java source code and classes are stored.

When a computer executes a Java program, what type of memory will be used to store it?

Main Memory (RAM)

When used in a Java program, what would the following statements display on the screen? int age; age = 20; System.out.println("My age is"); System.out.println(age);

My age is 20

What output will be produced by the following code? double hoursWorked[] = {8.0, 7.5, 8.0, 7.5, 9.0}; Sys.out.println(hoursWorked[hoursWorked.length])

Nothing, the code will crash due to an exception.

Assume you have the following code already declared: double amount = 5.5; Which of the following will correctly print the amount formatted with a $ symbol and two decimal places? (see below) five fity (select all that apply - there may be more than one correct answer)

NumberFormat currency = NumberFormat.getCurrencyInstance(); System.out.println(currency.format(amount)); ----------------------------------------- DecimalFormat currency = new DecimalFormat("#.00"); System.out.println("$" + currency.format(amount));

What is a method?

One behavior that can be performed on the object.

What is a field (a.k.a. member variable)?

One item of data stored about the object.

What output is produced by the following statements? int number = 7; boolean isPositive = (number > 0); if (number > 0) number = -100; if (isPositive) Sys.out.println("Positive"); else Sys.out.println("Not positive"); Sys.out.println(number);

Positive -100

At Orange Coast College, there are several honors notations that may be added to your semester transcript depending upon your GPA. Dean's List Notation: The student completes 12 or more units of OCC coursework with letter grades and earns a semester GPA of 3.50-3.99 Honors List Notation: The student completes 6 - 11.9 units of OCC coursework with letter grades and earns a semester GPA of 3.75-4.0 President's List Notation: The student completes 12 or more units of OCC coursework with letter grades and earns a semester GPA of 4.0 Assuming a new Java programmer has interpreted the above guidelines and programmed them into code as follows: double creditsCompleted = 12.0; double gPA = 4.0; if (creditsCompleted >= 12 && gPA >= 3.5) Sys.out.println("Dean's List"); if (creditsCompleted >= 12 && gPA >= 3.75) Sys.out.println("Honors List"); else Sys.out.println("President's List"); What output will be produced by this code? Dean's List, Honors List, Presidents List, Dean's List Honors List, Dean's List Presidents List

President's List

Which of the following is an important difference between object-oriented and procedural programming?

Procedural programming treats a program as a sequence of actions or commands, while object-oriented programming looks at a program as a group of interacting entities named objects with related data and behavior.

Assume you have already defined an int variable named age (you do not need to re-define it). Which of the following choices will: 1) declare a new Scanner named consoleScanner 2) use the consoleScanner to read in the user's age. *You do not need to output a message to the user, just read in their age.

Scanner consoleScanner = new Scanner(System.in); age = consoleScanner.nextInt();

Assume you have a String variable named phoneNumber, which is initialized to a ten-digit zip code with parentheses around the area code, then a space, then the number with a hyphen between the two parts. For example: String phoneNumber = "(714) 432-6842"; Which of the following declares a new String variable named areaCode and initializes it to only the numbers in the area code (e.g. 714)?

String areaCode = phoneNumber.substring(1, 4);

Assume you have a String variable named oCCZipCode, which is set to a nine-digit zip code with a hyphen between the two parts. For example: String oCCZipCode = "92626-1023"; In every 9 digit zip code, the last two digits, in this case "23", are known as the delivery segment, and can identify specific locations to postal workers, such as the side of the street, or the floor in a building, or the department within a large office. Which of the following declares a new String variable named deliverySegment and initializes it to only the last two digits of the oCCZipCode above? (Select all that apply - there may be more than one correct answer)

String deliverySegment = oCCZipCode.substring(8); String deliverySegment = oCCZipCode.substring(8,10);

Assume you have a String variable defined that stores a person's last name. For example: String lastName = "Paulding"; Which of the following defines a new String variable named lastNameAllCaps, which is initialized to the lastName in all capital letters (in this example, it would be "PAULDING")?

String lastNameAllCaps = lastName.toUpperCase( );

Which of the following lines of Java code produces the following output (e.g. the numbers 3 2 1, each on a separate line. You do not need a blank line to begin with. The cursor should end up underneath the 1): 3 2 1 (Choose all that apply)

System.out.println("3\n2\n1"); System.out.print("3\n2\n1\n"); System.out.print("3\n" + "2\n" + "1\n"); System.out.println("3\n" + "2\n" + "1");

What is the state and behavior of a String object?

The state is its sequence of characters, and the behavior is its methods, such as length() and toUpperCase().

What output will be produced by the following code? double tides[] = {12.2, -7.3, 14.2, 11.3}; Sys.out.println("Tide 1 is " + tides[1]);

Tide 1 is -7.3

What output is produced by the following code? int time = 2, tide = 3; if ( time + tide > 6) Sys.out.println("Time and tide wait for no one.") else if (time + tide > 5) Sys.out.println("Time and tide wait for someone.") else if (time + tide > 4) Sys.out.println("Time and tide wait for everyone.") else Sys.out.println("Time and tide wait for me!")

Time and tide wait for everyone.

What is the purpose of a default constructor?

To instantiate a new object by initializing its instance variables to null or default values.

What is the purpose of a copy constructor?

To instantiate a new object by initializing its instance variables to the values of another object (of the same type)

What is the purpose of a parameterized constructor?

To instantiate a new object by initializing its instance variables with the arguments coming into the constructor.

Which of the following directly causes an IOException in Java code?

Trying to open a local file that does not exist.

Which of the following directly causes a ClassNotFoundException in Java code?

Trying to open a local file that does not exist. When trying to read an object from a binary file as one data type, but it was saved as another data type.

Which of the following directly causes an InputMismatchException in Java code?

When a Scanner tries to read input as one data type, but receives an incompatible data type.

What output will be produced by the following code? char vowels[] = {'a', 'e', 'i', 'o', 'u'}; for (int i = 0; i<vowels.length; i++) Sys.out.println(vowels[i]);

a e i o u

Which of the following would draw the outline of a circle with a width of 50 and a height of 50, with the top left corner at position x = 10, y = 100? Assume that the canvas has already been defined.

canvas.drawOval(10, 100, 50, 50);

What is the file extension used for storing Java byte code (machine code)?

class

Given an array of type double named examScores that has already been declared and initialized with 40 scores, which of the following would correctly sum all the scores in the array? Select all that may apply (there may be more than one correct answer).

double sum = 0.0; for (int i = 0; i < examScores.length; i++) sum += examScores[i]; double sum = 0.0; for (double score : examScores) sum += score;

Given two already defined constants (NUM_STUDENTS and NUM_GRADES) and a two-dimensional array named grades that has already been declared with NUM_STUDENTS as the size of its rows and NUM_GRADES as the size of its columns. Assume the grades array has already been initialized with values from the user. Write the code that will declare two variables (both type double): named sumOfGrades and averageGrade Then loop through all the elements of the grades array to calculate both sumOfGrades and the averageGrade. You only need to calculate the sumOfGrades and averageGrade (not display them). Note: you do not need to know the size of NUM_STUDENTS and NUM_GRADES to accomplish this task.

double sumOfGrades = 0, averageGrade; for (int i = 0; i < NUM_STUDENTS; i ++) { for (int j = 0; j < NUM_GRADES; j ++) { sum += grades[i][j]; } } averageGrade = sumOfGrades/ (NUM_STUDENTS * NUM_GRADES)

What is the value of the boolean variable answer after the following code is executed? double creditsCompleted = 6.0; double gPA = 4.0; boolean answer = (creditsCompleted >= 12 && gPA >= 4.0); 0 1 true false

false

What is the value of the boolean variable answer after the following code is executed? double creditsCompleted = 6.0; doublegPA = 4.0; boolean = answer = (creditsComplted >= 12 && gPA >= 4.0); 0, 1, true, or false

false

Which of the following will correctly loop through the positions in an array of length 5? Assume the array's name is numbers [select all that apply]

for (int i = 0; i < 5; i++) for (int i = 0; i < numbers.length; i++)

Which of the following fragments of code tests whether an integer variable named score is in the range 0 to 100 (including 0 and 100). (select all that apply - there could be more than one correct answer)

if (score >= 0 && score <= 100) if (score <= 100 && score >= 0)

Suppose the integer variable number has been declared and initialized with a value. Write an if/else if/else statement that displays the word "High" if number is greater than 10, "Low" if number is less than 5 and "So-so" if number is anything else.

if( number > 10) { System.out.println("High"); } else if (number < 5) { System.out.println("Low"); } else { System.out.println("So-so"); }

Which of the following lines of code needs to appear in your Java program in order to utilize the Scanner library?

import java.util.Scanner;

Write the code that will declare an integer array named multiplesOfFive with a size of 100. Then, write a loop that will initialize the array with the first 100 multiples of five (specifically, 5, 10, 15, 20, ... , up to 500) Finally, write a loop that will print each multiple of 5 from the array, one multiple per line, starting at 500 and ending at 5. For example, the loop will print: 500 495 490 [continuing the pattern, but skipping lines for brevity] 15 10 5

int [] multiplesOfFive = new int [100]; for(int i = 0; i <= multiplesOfFive.length; i++) multiplesOfFive[i-1] = 5*i; for(int i = multipesOfFive.length; i >= 0; i--) System.out.println(multiplesOfFive[i]);

Which of the following excerpts of Java code accomplishes the following: Define an integer variable named evenSum and initialize its value to 0. Write a loop that adds up the even numbers between 0 and 100 and stores the answer in evenSum Your loop should only iterate over even numbers (skip the odd ones)

int evenSum = 0; for (int number = 0; number <= 100; number+=2) { evenSum += number; }

Which of the following declares a two-dimensional array of integers named grades with 40 rows and 10 columns?

int[ ] [ ] grades = new int [40] [10];

Which of the following will correctly declare an integer array named numbers with exactly 100 elements?

int[ ] numbers = new int[100];

Which of the following declares (and initializes) a two-dimensional array named settings with the same layout as the table of data below? 12 24 32 21 14 67 87 65 19 1 24 12

int[ ][ ] settings = { {12, 24, 32, 21}, {14, 67, 87, 65}, {19, 1, 24, 12} };

What is the file extension used for storing Java source code?

java

Which of the following loops is used to iterate through all the contents of a two-dimensional array?

nested for loops

Imagine the Person class has already been defined with the following information: public class Person { private String firstName; private String lastName; private String dateOfBrith; public Person(String newFirstName, String newLastName, String newDateOfBirth) { /////code } } Which of the following correctly initializes all of the member variables? Assume the following code is placed within the block of code for the constructor.

newFirstName = firstName; newLastName = lastName; newDateOfBirth = dateOfBirth;

Assume we have a Scanner defined as: Scanner consoleScanner = new Scanner(System.in); What is the method we need to invoke to read a string with the consoleScanner? (e.g. String lastName = consoleScanner._______)

nextLine();

Which of the following are legal Java identifiers? first-name printLn 42isTheSolution _average annualSalary ABC sum of data "hello" else

printLn average annualSalary ABC HoursWorked

In this exercise, you are to create a new exception class named CrazyException. Similar to we did in last week's in-class assignments, please write the code for the entire CrazyException class below, which only needs a single constructor: A parameterized constructor that takes as input a String message and sends it to its super class. Please write the code for the entire CrazyException class.

public class CrazyException extends Exception { public CrazyException (String message) { super(message); } }

Which of the following correctly defines a public enumeration (enum) of the planets in our solar system: Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto

public enum Planet { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto }

Which of the following define a constant named CM_SALES_TAX, which has the value 0.08 (sales tax in Costa Mesa)? Choose all that apply.

public static final double CM_SALES_TAX = 0.08;

Which of the following would be correct in declaring a constant named SIZE to represent the value 30 for an array?

public static final int SIZE = 30;

When a programmer creates a new applet, which of the following methods will s/he need to implement in order to set the size of the applet and draw shapes on the canvas?

public void init( ) public void paint(Graphics canvas)

When dealing with Java Applets, this method is called exactly once in an applet's life, when it its first loaded. This method is normally used for activities such as setting up the user interface or downloading any images or media files needed.

public void init()

When creating Java Applets, this method is called to draw various graphical elements, such as rectangles, ovals, arcs, lines and text on the applet.

public void paint(Graphics canvas)

You are trying to write Java code that reads a word from the user (either Yes or No) to make a decision in code. Assume you have already written the following Java code: String response; Scanner consoleScanner = new Scanner(System.in); System.out.println("Would you like to try again (Yes/No)"); Which line of code below assigns the String variable named response to the word from the consoleScanner -AND- ensures the word is read as uppercase no matter how it was typed in.

response = consoleScanner.next().toUpperCase();

Which of the following would correctly declare and initialize an array named buttons with the following String values? "Yes" "No" "Retry" Select all that apply (there may be more than one correct answer)

ring buttons[] = new String[3]; buttons[0] = "Yes"; buttons[1] = "No"; buttons[2] = "Retry"; String[] buttons = {"Yes", "No", "Retry"};

Which of the following statements assigns the value 56893.12 to the very first column of the very first row of the sales array defined in the previous problem?

sales[0][0] = 56893.12;

Which of the following statements assigns the value 56893.12 to the very last column of the very last row of the sales array defined in the problem #2?

sales[5][3] = 56893.12;

Which Java keyword is added to the definition of a method to alert other programmers that the method "may" generate an exception?

throws

What is the value of the boolean variable answer after the following code is executed? double creditsCompleted = 6.0; double gPA = 4.0; boolean answer = (creditsCompleted >= 12 || gPA >= 4.0; 0 , 1, true or false?

true

What is the value of the boolean variable answer after the following code is executed? double creditsCompleted = 6.0; double gPA = 4.0; boolean answer = (creditsCompleted >=12 || gPA >= 4.0); 0 1 true false

true

What output would be produced by the following code (when number is changed to 36)? try { Sys.out.print("try block entered"); int number = 36; if (number > 36) throw new CrazyException("this is one crazy exception!"); Sys.out.println("Leaving try block"): } catch (CrazyException ex) { Sys.out.println(ex.getMessage()); } Sys.out.println("End of code"); }

try block entered Leaving try block End of code

What output would be produced by the following code? try { Sys.out.print("try block entered"); int number = 42; if (number > 36) throw new CrazyException("this is one crazy exception!"); Sys.out.println("Leaving try block"): } catch (CrazyException ex) { Sys.out.println(ex.getMessage()); } Sys.out.println("End of code"); }

try block entered This is one crazy exception! End of code


Related study sets

Microeconomics and Behavior Book (Test 1)

View Set

Psych Quiz 8 Questions (From Launchpad)

View Set

Money, Finance, Banking Final Cheat Sheet

View Set

Comprehensive Exam - Public Speaking - Chapter 1

View Set

AP US History Chapter 19 Questions

View Set

Business Management Organizational Design Test

View Set