Java Final

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

A program must explicitly use the this reference when accessing an instance variable that is shadowed by a local variable. Select one: True False

The correct answer is 'True'.

Static class variables are shared by all objects of a class. Select one: True False

The correct answer is 'True'.

The Java statement: Integer x = 7; performs an auto-boxing conversion. Select one: True False

The correct answer is 'True'.

The regular expressions "A*" and "A+" will both match "AAA", but only "A*" will match an empty string. Select one: True False

The correct answer is 'True'.

Consider array items, which contains the values 0, 2, 4, 6 and 8. If method changeArray is called with the method call changeArray(items, items[2]), what values are stored in items after the method has finished executing? public static void changeArray(int[] passedArray, int value) { passedArray[value] = 12; value = 5; } Select one: a. 0, 2, 5, 6, 12 b. 0, 2, 12, 6, 8 c. 0, 2, 4, 6, 5. d. 0, 2, 4, 6, 12.

The correct answer is: 0, 2, 4, 6, 12

Which of the following is not possible? Select one: a. All of the above are possible. b. A class that implements two interfaces c. A class that inherits from two classes. d. A class that inherits from one class, and implements an interface.

The correct answer is: A class that inherits from two classes.

Consider the Java segment: String line1 = new String("c = 1 + 2 + 3") ; StringTokenizer tok = new StringTokenizer(line1, "+="); String foo = tok.nextToken(); String bar = tok.nextToken(); The value of foo is ______ and the value of bar is ______ .

"c" "1"

For String c = "Now is the time for all"; The Java statements String i = c.substring(7); String j = c.substring(4, 15); will result in: i = _______ and j = _______

"the time for all" "is the time"

Draw a UML for the following problem. Drivers are concerned with the mileage their automobiles get. Design a Java class that will input the miles driven and gallons used (both as integers) for each trip. The class should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all trips up to this point. All averaging calculations should produce floating-point results.

...

For String c = "Hello. She sells sea shells"; The Java statements int i = c.indexOf("ll"); int j = c.lastIndexOf("ll"); will result in: i=_____ and j=____

2 24

For String c = "hello world"; The Java statements int i = c.indexOf('o'); int j = c.lastIndexOf('l'); will result in: i=______ and j=_____

4 9

Create a toString method that will store each value of the array and the sum of the values into a string.

@override public String toString() { return " The elements of the array are: " + String.ValueOf(arr) + " The sum of the values is: " + calcSum(); } Comments: String.ValueOf(arr) is not defined for an array type argument so each value of your array will not be displayed!!

Class ________ represents a dynamically resizeable array-like data structure.

ArrayList

public class Seuss{ } Write a Java statement that creates an instance field for the ArrayList that will hold the list below. Create constructor that initializes the ArrayList with the following {"green", "eggs", "and", "ham"} for the above class.

ArrayList<String> seuss = new ArrayList<String>; public Seuss() { this.seuss = {"green", "eggs", "and", "ham"}; } Comments: Elements can't be added to list this way!!! Dynamically allocate ArrayList in constructor!

Write a Java method called reverseString that uses a Collection (of your choice) to reverse the characters in a String. Hint: reverseString method takes a String as a parameter and returns the reversed String.

CharArray[] alpha = ('a','b','c','d','e'); public String reverseString(String letters) { StringBuilder buffer = new StringBuilder(alpha); buffer.reverse(); return buffer.toString(); }

Write a Java statement that enables a display windows containing messages using prebuilt dialog boxes to display Hello World!.

JOptionPane.showMessageDialog(null, "Hello World");

Assuming x refers to an Integer object, the Java statement: Integer y = x; performs an unboxing conversion. Select one: True False

The correct answer is 'False'.

Write a Java statement to display Java is fun! in the command window.

System.out.println("Java is fun!");

A constructor can specify return types and return values. Select one: True False

The correct answer is 'False'.

An anonymous String has no value. Select one: True False

The correct answer is 'False'.

Attempting to access an array element outside of the bounds of an array, causes a(n) . Select one: a. ArrayElementOutOfBoundsException. b. ArrayException. ArrayException. c. ArrayOutOfBoundsException. d. ArrayIndexOutOfBoundsException.

The correct answer is: ArrayIndexOutOfBoundsException.

Which of the following statements is true? Select one: a. If it is necessary to read a sequential file again, the program can simply keep reading—when the end of the file is reached, the Scanner is automatically set to point back to the beginning of the file. b. Class Scanner does not provide the ability to reposition to the beginning of the file. c. Class Scanner provides the ability to reposition to the beginning of a file with method seek. d. Class Scanner provides the ability to reposition to the beginning of a file with method reposition.

The correct answer is: Class Scanner does not provide the ability to reposition to the beginning of the file.

Which statement is false? Select one: a. A collection is an object that can hold references to other objects. b. Collections are carefully constructed for rapid execution and efficient use of memory. c. The collection interfaces declare the operations that can be performed on each type of collection. d. Collections discourage software reuse because they are non-portable.

The correct answer is: Collections discourage software reuse because they are non-portable.

The Java statement: g.fillOval(290, 100, 90, 55); Select one: a. Draws a filled oval bounded by a rectangle with its upper-left corner at coordinates x=290, y=100, with width=90 and height=55. b. Draws a filled oval with its center at coordinates x=290, y=100, with height=90 and width=55. c. Draws a filled oval with its leftmost point at coordinates x=290, y=100, with height=90 and width=55. d. Draws a filled oval bounded by a rectangle with its upper-left corner at coordinates x=290, y=100, with height=90 and width=55.

The correct answer is: Draws a filled oval bounded by a rectangle with its upper-left corner at coordinates x=290, y=100, with width=90 and height=55.

Which of the following statements is false? Select one: a. All of the above are true. b. Exception handling enables programmers to write robust and fault-tolerant programs. c. Exception handling can catch but not resolve exceptions. d. Exception handling can resolve exceptions.

The correct answer is: Exception handling can catch but not resolve exceptions.

Which of the following exceptions is a checked exception? Select one: a. InputMismatchException. b. RuntimeException. c. IOException. d. ArithmeticException.

The correct answer is: IOException.

Which of the following tasks cannot be performed using an enhanced for loop? Select one: a. Incrementing the value stored in each element of the array. b. Displaying all even element values in an array. c. Calculating the product of all the values in an array. d. Comparing the elements in an array to a specific value.

The correct answer is: Incrementing the value stored in each element of the array.

Which of the following statements is true? Select one: a. Information hiding is achieved by restricting access to class members via keyword public. b. None of the above is true. c. The private members of a class are directly accessible to the clients of a class. d. Methods and instance variables can both be either public or private.

The correct answer is: Methods and instance variables can both be either public or private.

Which of the following is false? Select one: a. Memory leaks using Java are rare because of automatic garbage collection. b. Method finalize does not take parameters and has return type void. c. Objects are marked for garbage collection by method finalize. d. The garbage collector reclaims unused memory.

The correct answer is: Objects are marked for garbage collection by method finalize.

Overriding a method differs from overloading a method because: Select one: a. Overloaded methods have the same signature. b. Both of the above. c. Neither of the above. d. Overridden methods have the same signature.

The correct answer is: Overridden methods have the same signature.

Consider the program below: public class Test { public static void main(String[] args) { int[] a; a = new int[10]; for (int i = 0; i < a.length; i++) a[i] = i + 2; int result = 0; for (int i = 0; i < a.length; i++) result += a[i]; System.out.printf("Result is: %d%n", result); } } The output of this program will be: Select one: a. Result is: 64. b. Result is: 65. c. Result is: 67. d. Result is: 62.

The correct answer is: Result is: 65.

Q1: Consider the statements below: String a = "JAVA: "; String b = "How to "; String c = "Program"; Which of the statements below will create the String r1 = "JAVA: How to Program"? Select one: a. String r1 = a.concat(b.concat(c)); b. String r1 = c.concat(c.concat(b)); c. String r1 = b.concat(c.concat(a)); d. String r1 = c.concat(b.concat(a));

The correct answer is: String r1 = a.concat(b.concat(c));

Which of the following creates the string of the numbers from 1 to 1000 most efficiently? Select one: a. StringBuilder sb = new StringBuilder(10); for (int i = 1; i <= 1000; i++) sb.append(i); String s = new String(sb); b. String s; for (int i = 1; i <= 1000; i++) s += i; c. StringBuilder sb = new StringBuilder(3000); for (int i = 1; i <= 1000; i++) sb.append(i); String s = new String(sb); d. All are equivalently efficient.

The correct answer is: StringBuilder sb = new StringBuilder(3000); for (int i = 1; i <= 1000; i++) sb.append(i); String s = new String(sb);

Which of the following statements is false? Select one: a. A finally block is placed after the last catch block. b. A finally block is optional. c. The finally block and try block can appear in any order. d. A finally block typically releases resources acquired in the corresponding try block.

The correct answer is: The finally block and try block can appear in any order.

Which of the following statements is true? Select one: a. The capacity of a StringBuilder is equal to its length. b. The capacity of a StringBuilder cannot exceed its length. c. The length of a StringBuilder cannot exceed its capacity. d. Both a and b are true.

The correct answer is: The length of a StringBuilder cannot exceed its capacity.

In the catch block below, what is e? catch (ArithmeticException e) { System.err.printf(e); } Select one: a. The name of catch block's exception parameter. b. A finally block. c. The type of the exception being caught. d. An exception handler.

The correct answer is: The name of catch block's exception parameter.

Which of the following statements about try blocks is true? Select one: a. The try block must be followed by a finally block. b. The try block should contain statements that may process an exception. c. The try block must be followed by at least one catch block. d. The try block should contain statements that may throw an exception.

The correct answer is: The try block should contain statements that may throw an exception.

Consider the code segment below. Which of the following statements is false? int[] g; g = new int[23]; Select one: a. The second statement creates the array. b. The value of g[3] is -1. c. The first statement declares an array reference. d. g is a reference to an array of integers.

The correct answer is: The value of g[3] is -1.

StringBuilder objects can be used in place of String objects if ________. Select one: a. all of these b. the string data is not constant c. the string data size may grow d. the programs frequently perform string concatenation

The correct answer is: all of these

The fact that class Graphics is abstract contributes to Java's portability because ________. Select one: a. drawing is performed differently on every platform that supports Java. A subclass of Graphics must be created that uses the drawing capabilities of the current platform. b. objects of non-abstract classes can only be instantiated on the Windows platform. c. drawing should not be performed on non-Linux platforms. d. Class Graphics is not abstract.

The correct answer is: drawing is performed differently on every platform that supports Java. A subclass of Graphics must be created that uses the drawing capabilities of the current platform.

Which set of statements totals the items in each row of two-dimensional array items, and displays each row's total? Select one: a. int total = 0; for (int row = 0; row < items.length; row++) { for (int column = 0; column < items[column].length; column++) total += items[row][column]; System.out.printf("Row %d's total is %d%n", row, total); } b. for (int row = 0; row < items.length; row++) { int total = 0; for (int column = 0; column < items[row].length; column++) total += items[row][column]; System.out.printf("Row %d's total is %d%n", row, total); } c. int total = 0; for (int row = 0; row < items.length; row++) { for (int column = 0; column < items[row].length; column++) total += items[row][column]; System.out.printf("Row %d's total is %d%n", row, total); } d. for (int row = 0; row < items.length; row++) { int total = 0; for (int column = 0; column < items[column].length; column++) total += items[row][column]; System.out.printf("Row %d's total is %d%n", row, total); }

The correct answer is: for (int row = 0; row < items.length; row++) { int total = 0; for (int column = 0; column < items[row].length; column++) total += items[row][column]; System.out.printf("Row %d's total is %d%n", row, total); }

Which JFileChooser method returns the file the user selected? Select one: a. getSelectedFile b. getOpenDialog c. showOpenDialog d. getFile

The correct answer is: getSelectedFile

Which syntax imports all static members of class Math? Select one: a. import static java.lang.Math.*; b. None of the above c. import java.lang.Math.*; d. import static java.lang.Math;

The correct answer is: import static java.lang.Math.*;

Which of the following statements creates a multidimensional array with 3 rows, where the first row contains 1 element, the second row contains 4 elements and the final row contains 2 elements? Select one: a. int[][] items = {{1}, {4}, {2}}; b. int[][] items = {{1}, {2, 3, 4, 5}, {6, 7}, {}); c. int[][] items = {{1, null, null, null}, {2, 3, 4, 5}, {6, 7, null, null}}; d. int[][] items = {{1}, {2, 3, 4, 5}, {6, 7}};

The correct answer is: int[][] items = {{1}, {2, 3, 4, 5}, {6, 7}};

If the superclass contains only abstract method declarations, the superclass is used for ________. Select one: a. Neither b. implementation inheritance c. interface inheritance d. Both

The correct answer is: interface inheritance

Declaring a method final means: Select one: a. it will prepare the object for garbage collection. b. it cannot be overloaded. c. it cannot be overridden. d. it cannot be accessed from outside its class.

The correct answer is: it cannot be overridden.

Which of the following is the superclass constructor call syntax? Select one: a. keyword super, followed by a dot (.) b. None of the above c. keyword super, followed by a dot and the superclass constructor name d. keyword super, followed by a set of parentheses containing the superclass constructor arguments

The correct answer is: keyword super, followed by a set of parentheses containing the superclass constructor arguments

Set methods are also commonly called ________ methods and get methods are also commonly called ________ methods. Select one: a. query, accessor b. query, mutator c. accessor, mutator d. mutator, accessor

The correct answer is: mutator, accessor

Which superclass members are inherited by all subclasses of that superclass? Select one: a. protected instance variables and methods. b. protected constructors. c. private instance variables and methods. d. private constructors.

The correct answer is: protected instance variables and methods.

Which of the following could be used to declare abstract method method1 in abstract class Class1 (method1 returns an int and takes no arguments)? Select one: a. public int abstract method1(); b. public int nonfinal method1(); c. public abstract int method1(); d. public int method1();

The correct answer is: public abstract int method1();

Which JFileChooser method specifies what users can select in the dialog? Select one: a. setFileSelectionMode b. setSelectionMode c. showOpenDialog d. None of these

The correct answer is: setFileSelectionMode

What is the value of result after the following Java statements execute (assume all variables are of type int)? a = 4; b = 12; c = 37; d = 51; result = d % a * c + a % b + a; Select one: a. 119 b. 51 c. 127 d. 59

The correct answer is: 119

How many String objects are instantiated by the following code segment (not including the literals)? String s1, output; s1 = "hello"; output = "\nThe string reversed is: " ; for (int i = s1.length() - 1; i >= 0; i--) output += s1.charAt(i) + " " ;

The correct answer is: 7

Consider the array: s[0] = 7 s[1] = 0 s[2] = -12 s[3] = 9 s[4] = 10 s[5] = 3 s[6] = 6 The value of s[s[6] - s[5]] is: Select one: a. 10 b. 3 c. 9 d. 0

The correct answer is: 9

Which statement is false? Select one: a. A List cannot contain duplicate elements b. Lists use zero-based indices. c. A List is a Collection d. A List is sometimes called a sequence

The correct answer is: A List cannot contain duplicate elements

Which statement is false? Select one: a. Classes are reusable software components. b. A class is to an object as a blueprint is to a house. c. Performing a task in a program requires a method. d. A class is an instance of its object

The correct answer is: A class is an instance of its object

A Java class can have which of the following methods? A. void foo(int a) B. void foo(int a, int b) C. void foo(double a) D. void foo(double a, double b) E. void foo(int b) Select one: a. All of the above b. A, B, D, E c. A, B, C, D d. A, C, D, E

The correct answer is: A, B, C, D

For the code segment below: switch(q) { case 1: System.out.println("apple"); break; case 2: System.out.println("orange"); break; case 3: System.out.println("banana"); break; case 4: System.out.println("pear"); case 5: System.out.println("grapes"); default: System.out.println("kiwi"); } Which of the following values for q will result in kiwi being included in the output? Select one: a. 2 b. Any integer less than 1 and greater than or equal to 4 c. 1 d. 3

The correct answer is: Any integer less than 1 and greater than or equal to 4

Which of the following classes enable input and output of entire objects to or from a file? A. SerializedInputStream B. SerializedOutputStream C. ObjectInputStream D. ObjectOutputStream E. Scanner F. Formatter Select one: a. C and D b. C,D,E,F c. E and F d. A and B

The correct answer is: C and D

Which region is used by default when a Component is added to a BorderLayout? Select one: a. NORTH b. LEFT c. CENTER d. WEST

The correct answer is: CENTER

Which of the following statements is true? Select one: a. Constructors can specify parameters and return types. b. Constructors can specify parameters but not return types. c. Constructors cannot specify parameters but can specify return types. d. Constructors can specify neither parameters nor return types.

The correct answer is: Constructors can specify parameters but not return types.

Which of the following statements for a JTextField is false? Select one: a. Enables users to enter data from the keyboard. b. Displays a list of fields. c. Can be used to display uneditable text. d. Can be used to display editable text.

The correct answer is: Displays a list of fields.

Which of the following statements is false? Select one: a. Each class can be used only once to build many objects. b. Reuse helps you build more reliable and effective systems, because existing classes and components often have undergone extensive testing, debugging and performance tuning. c. Just as the notion of interchangeable parts was crucial to the Industrial Revolution, reusable classes are crucial to the software revolution that has been spurred by object technology. d. Avoid reinventing the wheel—use existing high-quality pieces wherever possible. This software reuse is a key benefit of object-oriented programming.

The correct answer is: Each class can be used only once to build many objects.

Which of the following classes is not used for file input? Select one: a. Formatter b. FileInputStream c. ObjectInputStream d. FileReader

The correct answer is: Formatter

The JColorChooser dialog allows colors to be chosen by all but which of the following? Select one: a. Hue, saturation, brightness b. Swatches c. Red, Green, Blue d. Gradient, cycle, brightness

The correct answer is: Gradient, cycle, brightness

When the user clicks a JCheckBox, a(n) occurs. Select one: a. ItemEvent b. ButtonEvent c. ActionEvent d. CheckedEvent

The correct answer is: ItemEvent

A(n) _____________ allows a program to walk through the collection and remove elements from the collection. Select one: a. Queue b. Set c. Iterator d. List

The correct answer is: Iterator

Every class in Java, except ________, extends an existing class. Select one: a. Class b. Integer c. Object d. String

The correct answer is: Object

________ is a graphical language that allows people who design software systems to use an industry standard notation to represent them. Select one: a. The Unified Graphical Language b. The Unified Design Language c. The Unified Modeling Language d. None of the above

The correct answer is: The Unified Modeling Language

What is output by the following Java code segment? int temp = 180; while (temp != 80) { if (temp > 90) { System.out.print("This porridge is too hot! "); // cool down temp = temp - (temp > 150 ? 100 : 20); } else { if (temp < 70) { System.out.print( "This porridge is too cold! "); // warm up temp = temp + (temp < 50 ? 30 : 20); } } } if (temp == 80) System.out.println("This porridge is just right!"); Select one: a. This porridge is too cold! This porridge is just right! b. This porridge is too hot! This porridge is just right! c. This porridge is just right! d. None of the above.

The correct answer is: This porridge is too hot! This porridge is just right!

What will be output after the following Java statements have been executed (assume all variables are of type int)? a = 4; b = 12; c = 37; d = 51; if ( a < b ) System.out.println( "a < b" ); if ( a > b ) System.out.println( "a > b" ); if ( d <= c ) System.out.println( "d <= c" ); if ( c != d ) System.out.println( "c != d" ); Select one: a. a < b c != d b. a < b d <= c c != d c. a > b c != d d. a < b c < d a != b

The correct answer is: a < b c != d

A(n) ________ class cannot be instantiated. Select one: a. final b. polymorphic c. abstract d. concrete

The correct answer is: abstract

All import declarations must be placed Select one: a. inside the class declaration's body. b. before the class declaration. c. after the class declaration. d. all of the above will work.

The correct answer is: before the class declaration.

Which of the following code segments does not increment val by 3? Select one: a. val += 3; b. val = val + 1; val = val + 1; val = val + 1; c. c = 3; val = val + (c == 3 ? 2 : 3); d. All of the above increment val by 3.

The correct answer is: c = 3; val = val + (c == 3 ? 2 : 3);

Which statement best describes the relationship between superclass and subclass types? Select one: a. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable. b. A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. c. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable. d. A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable.

The correct answer is: c) A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable.

String objects are immutable. This means they ____________. Select one: a. must be initialized b. cannot be changed c. none of the above d. cannot be deleted

The correct answer is: cannot be changed

Filled rectangles and filled circles are drawn using Graphics method ________ and ________. Select one: a. fillRect, fillCircle b. filledRect, filledCircle c. fillRect, fillOval d. filledRect, filledOval

The correct answer is: fillRect, fillOval

Consider the code segment below. if (gender == 1) { if (age >= 65) ++seniorFemales; } This segment is equivalent to which of the following? Select one: a. if (gender == 1 || age >= 65) ++seniorFemales; b. if (gender == 1 && age >= 65) ++seniorFemales; c. if (gender == 1 AND age >= 65) ++seniorFemales; d. if (gender == 1 OR age >= 65) ++seniorFemales;

The correct answer is: if (gender == 1 && age >= 65) ++seniorFemales;

A String constructor canot be passed ____________. Select one: a. int arrays b. byte arrays c. char arrays d. Strings

The correct answer is: int arrays

Which of the following is not a package in the Java API? Select one: a. java.component b. java.awt c. javax.swing.event d. java.lang

The correct answer is: java.component

Which of the following is not a valid Java identifier? Select one: a. my Value b. $_AAA1 c. width d. m_x

The correct answer is: my Value

A JRadioButton is different from a JCheckBox in that . Select one: a. a JRadioButton is a state button, JCheckBox is not b. a JRadioButton is a type of button, JCheckBox is not c. normally several JRadioButtons are grouped together and are mutually exclusive d. a JRadioButton is a subclass of JToggleButton, JCheckBox is not

The correct answer is: normally several JRadioButtons are grouped together and are mutually exclusive

A well-designed method ________. Select one: a. performs multiple unrelated tasks b. repeats code found in other methods c. contains thousands of lines of code d. performs a single, well-defined task

The correct answer is: performs a single, well-defined task

The collections framework algorithms are __________, i.e., each of these algorithms can operate on objects that implement specified interfaces without concern for the underlying implementations. Select one: a. implementation dependent b. lexicographical c. stable d. polymorphic

The correct answer is: polymorphic

Which of the following is not a Java primitive type? Select one: a. char b. byte c. real d. double

The correct answer is: real

Types in Java are divided into two categories. The primitive types are boolean, byte, char, short, int, long, float and double. All other types are ________ types. Select one: a. static b. reference c. declared d. source

The correct answer is: reference

The default implementation of method clone of Object performs a ________. Select one: a. deep copy b. shallow copy c. full copy d. empty copy

The correct answer is: shallow copy

Which of the following is the method used to display a dialog box to gather input? Select one: a. showMessageDialog b. showInputDialog c. inputDialog d. getInput

The correct answer is: showInputDialog

A key part of enabling the JVM to locate and call method main to begin the app's execution is the ________ keyword, which indicates that main can be called without first creating an object of the class in which the method is declared. Select one: a. stable b. private c. static d. public

The correct answer is: static

To catch an exception, the code that might throw the exception must be enclosed in a ________. Select one: a. finally block b. catch block c. try block d. throws block

The correct answer is: try block

The body of each class declaration begins with _______ and ends with ________.

The correct answer is: { }

A class that implements an interface but does not declare all of the interface's methods must be declared ________.

abstract

An argument type followed by a(n) __________ in a method's parameter list indicates that the method receives a variable number of arguments of that particular type.

correct answer is ellipsis

Which of the following statements is true? Select one: a. Performing a task in a program requires a method. b. A method houses the program statements that actually perform its tasks. c. The method hides its statements from its user, just as the accelerator pedal of a car hides from the driver the mechanisms of making the car go faster. d. All of the above

d. All of the above.

A(n) ________ indicates a problem that occurs while a program executes.

exception

Composition is sometimes refered to as a(n) __________ relationship.

has-a

Iterator method ___________ determines whether the Collection contains more elements.

hasNext

The __________keyword is used to specify that a class will define the methods of an interface.

implements

Write the SalaryCalculator class which allows an employee to input name, number of hours worked and rate of pay and displays the employee's name and gross pay. The company pays straight time for the first 40 hours worked by each employee and time and a half for all hours worked in excess of 40. SalaryCalculator -hours:int -hourlyRate:double -name:String <<constructor>> + SalaryCalculator(rate:double,time:int,nick:String): + getHours():int +getRate():double +getName():String +setHours(time:int):void +setRate(rate:double):void +setName(nick:String):void +pay():double +inputInfo():void +displayInfo():void

import java.util.Scanner; import javax.swing.JOptionPane; public class SalaryCalculator { private int hours; private double hourlyRate; private String name; public SalaryCalculator() { } public SalaryCalculator(double rate, int time, String nick) { hourlyRate = rate; hours = time; name = nick; } public int getHours() { return hours; } public double getRate() { return hourlyRate; } public String getName() { return name; } public void setHours(int time) { hours = time; } public void setRate(double rate) { hourlyRate = rate; } public void setName(String nick) { name = nick; } public double pay() { if (getHours() <=40) { hours *= getRate(); } else if (getHours() >40) { hours = (int) ((getHours() *0.5) * getRate()); } return hours; } public void displayInfo() { JOptionPane.showMessageDialog(null, "Hi " + getName() + ", your gross pay is: " + pay()); } public void inputInfo() { String message = JOptionPane.showInputDialog ("Please enter your name, number of hours worked and rate of pay separated by a space: "); Scanner input = new Scanner(message); setName(input.next()); setHours(input.nextInt()); setRate(input.nextDouble()); } }

Inheritance is also known as the _____ relationship.

is-a

The length of a String can be determined by the String method _________.

length

public class Array1 { int [ ] arr; } Given the above array write a constructor that creates the one-dimensional array of length 10 and sets the value of each element to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.

public Array1() { int[] arr = new int[10]; arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; }

Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide methods that calculates the rectangle's perimeter and area. It has set and get methods for both length and width.

public class Rectangle() { private double length = 1; private double width = 1; public Rectangle(double width, double length) { this.width = width; this.length = length; } public void setWidth(double w) { width = w; } public void setLength(double l) { length = l; } public int getWidth() { return width; } public int getLength() { return length; } public void calcPerimeter() { double total = 0; total = (2 *( getWidth())) + (2*(getLength())); } public void calcArea() { double total = 0; total = getWidth() * getLength(); } @override public String toString() { return "Perimeter is : " + calcPerimeter() + " Area is : " + calcArea(); } } Comments: All types should be double!! Area and perimeter should return an answer!

Create a square class that inherits from the rectangle class from the previous problem. Each set methods, perimeter, and area methods should perform appropriately with rectangle class.

public class Square extends Rectangle { private double width = 0; private double length = 0; public Square(double width, double length) { super(double width, double length) } } Comments: Square only has one side value!!! Where are you coming up with two?? According to Rectangle class you can never return the answer for perimeter and area!

Write a class that will assign the words "Default Text" of size 50 to a JTextField, assign the word "Copy" to a JButton. Write the correct listener class that when the button is selected the information in the JTextField will be copied to a JLabel. Assign these to correct positions using the BorderLayout.

public class copyText { public copyText() { JTextField text = new JTextField("Default Text", 50); JButton button = new JButton("Copy"); ActionListener listener = new ActionListener(); button.addActionListener(listener); add(text, BorderLayout.NORTH); add(button, BorderLayout.CENTER); public class ActionListener { private void copyButton(ActionEvent event) { if (event.getSource() == button) { Scanner input = new Scanner(text); String textLabel = input.Next(); JLabel label = new JLabel(textLabel); add(label, BorderLayout.SOUTH); } } }

Create a helper constructor return the sum of the values stored in the one-dimensional array using an enhanced loop. public double calcSum() { int sum = 0; for(int number: arr) { sum += arr[number]; } return sum; }

public double calcSum() { int sum = 0; for(int number: arr) { sum += arr[number]; } return sum; } Comment: (1) return type should be int not double! (2) Summation statement should not include [number]! Otherwise, nice job!

Consider the following Java statements: int x = 9; double y = 5.3; result = calculateValue(x, y); Write Java code for the method calculateValue to return the product of the two arguments. (Assume result is a double!)

public double calculateValue(int x, double y) { return (double) x * y; }

Write a main program to test class Rectangle. The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0. (Hint: use exception handling!)

public static void main(String[] args) { Rectangle rect = new Rectangle(); try { rect.setWidth(); rect.setLength(); }catch(Exception e) { if ( width < 0.0 || width > 20.0) System.err.out("width must be between 0 and 20"); if ( length < 0.0 || length > 20.0) System.err.out("length must be between 0 and 20"); } rect.toString(); } Comments: Don't have any thrown errors in setWidth and setLength of Rectangle class to catch these errors!

Write a Java main method to run the salary calculator five times allowing the user to input name, hours worked and rate of pay. Each user's name and gross pay should be displayed. public static void main(String[] args) { SalaryCalculator driver = new SalaryCalculator(); int counter = 1; for(i <= 5, i++) { driver.inputInfo(); driver.displayInfo(); } }

public static void main(String[] args) { SalaryCalculator driver = new SalaryCalculator(); for(int i = 1; i <= 5; i++) { driver.inputInfo(); driver.displayInfo(); } }

Write a Java method that reads in a line of text from an InputStream. The line of text is to be tokenized into words separated by spaces and written in reverse order to a string. You may assume there is an instance variable named 'in' that contains a reference to the InputStream, and an instance variable named "reverse" that is a String where the reversed string is to be stored.

public void reverseString() { StringTokenizer token = new StringTokenizer(in, " "); for(int i = in.length()-1, i >= 0, i --) { reverse += token.Next(); } }

A ________ path starts from the directory in which the application began executing.

relative

When an exception occurs it is said to have been ________.

thrown


Conjuntos de estudio relacionados

GOVT 2305 - Chapter 13. The Federal Courts

View Set

Linux - Chapter 14 - Network Configuration

View Set

Principles of Microeconomics: Chapter 18-Health Insurance and Health Care & Chapter 19-International Trade

View Set

FCCLA FCSA - Education & Training 2019

View Set

What is the Output of the function?

View Set