Java MTA

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

Given the following code: import java.util.*; public class Main{ public static void main(String[] args) { ArrayList<String> myList = new ArrayList<String>(); myList.add("apple"); myList.add("carrot"); myList.add("banana"); myList.add(1, "plum"); System.out.print(myList); } } What will be outputted to the console?

[apple, plum, carrot, banana] Explanation ArrayList elements are automatically inserted in the order of entry; they are not automatically sorted. ArrayLists use zero-based indexes and the last add() inserts a new element and shifts the remaining elements back. This means that plum is inserted into the ArrayList at index 1.

ArrayList.remove(i)

a method of ArrayList class used to remove i item from an ArrayList and moves all following values up one space.

ArrayList.get(i)

a method of ArrayList class used to return the i item within an ArrayList.

ternary conditional

a shortened version of an if/else statement that returns a value based on the value of a Boolean expression (condition ? true : false)

private method

can only be accessed by methods of the same class, is usually a helper method, and can never be a constructor

try-catch-finally block

code from a try block that throws an exception will look for a corresponding catch block with code that handles the exception. Optionally a finally statement can be added to run clean-up code independent of the try-catch outcome. (One try can have either; There can be multiple catch blocks)

You need to evaluate the following statement: Using a break in a while loop causes the loop to break the current iteration and start the next iteration of the loop. If the statement is correct, select "No change is needed". if the statement is not correct, select the appropriate solution that makes the statement correct.

continue Explanation Java supports three jump statements 'break' 'continue' and 'return'. The main difference between break and continue is that break is used for immediate termination of loop whereas, continue terminate current iteration and resumes the control to the next iteration of the loop.

You write the following code: java.util.Scanner sc = new java.util.Scanner("1 Excellent 2 Good 3 Fair 4 Poor"); Object data1 = sc.next(); Object data2 = sc.next(); Object data3 = sc.nextInt(); Object data4 = sc.nextLine(); You need to determine the values of the data1, data2, data3, data4 variables

data1 = 1 data2 = Excellent data3 = 2 data4 = Good 3 Fair 4 Poor (Correct) Explanation The following answer is correct: data1 = 1 data2 = Excellent data3 = 2 data4 = Good 3 Fair 4 Poor java.util.Scanner sc = new java.util.Scanner("1 Excellent 2 Good 3 Fair 4 Poor"); Object data1 = sc.next(); Object data2 = sc.next(); Object data3 = sc.nextInt(); Object data4 = sc.nextLine(); data1 => sc.next() reads the first word delimited by a space. (1) The cursor is set before Excellent. data2 => sc.next() reads the second word delimited by a space starting from the cursor (Excellent) The cursor is now set before 2. data3 => sc.nextInt() reads the first integer it encounters starting from the cursor. (2) The cursor is now set before Good. data4 => sc.nextInt() reads the whole line starting from the cursor (Good 3 Fair 4 Poor).

You are evaluating loops. You need to identify infinite loops. Which three statements represent infinite loop? (Each correct answer represents a complete solution?

do {} while (true); (Correct) for (; ;) {} (Correct) while (true) {} (Correct) Explanation The following code represents an infinite loop: for (; ;) {} This for loop does not use an initialization statement, a termination statement, or an increment/decrement statement. Therefore, it runs forever. The following code also represents an infinite loop: while (true) {} The while statement loops until the condition in parentheses return false. Because the value true is specified in parentheses, this loop will run forever. The following code also represents an infinite loop: do {} while (true); The do-while statement runs until the while condition returns false. Because the value true is specified in the parentheses, it loops forever.

conversion errors

errors that arise form converting statements from one (non-equivalent) form to another (ie: setting a double to equal an integer).

You need to create a Java application. The Java application will accept n-numbers (unspecified numbers) of numeric command line arguments and will output the sum of all of the arguments. You already have the following code: public static void main(String args[]) { int sum = 0; //Insert logic here System.out.println(sum); } How should you complete the code?

for(String arg : args){ sum += Integer.parseInt(arg); } (Correct) Explanation The answer is: for(String arg : args){ sum += Integer.parseInt(arg); } This code loops through each element within the args array and parses that element as an integers. Once the element is parsed as an integer, the value is added to the sum variable. If we do not parse the numeric string value to an integer using the Integer wrapper class, we'll receive an error stating: "incompatible types: String cannot be converted to int"

Exhibit: public static void countDown(int start){ for(; ;){ System.out.println(i); } } You are writing a Java method named countdown. The method must meet the following requirements: Accept an int parameter named start. Display all numbers from start to zero in decrements of one. How should you complete the for loop in the exhibit? To answer, select the appropriate code segments in the answer area.

for(int i = start; i >= 0; --i) Explanation The answer is: for(int i = start; i >= 0; --i) The for loop consists of three parts: the initiation: The numbers have to be displayed starting from the value of start, so this part is setting i equal to start. the condition: The loop should display numbers starting from start to zero, so basically the loop has to run until it reaches zero. So as long as the value of i is equal to or greater than zero, the loop should run. the decrement/increment part: The loop should be decremented by one. You can use either --i or i--, both have their own complete solution.

You are developing a Java program to play Tic-Tac-Toe. You define the following array to store the state of the board: char[][] grid = { {'-','-','X'}, {'-','-','-'}, {'-','O','-'}, }; You need to answer the following questions? Which array element contains an 'X'? Which array element contains an 'O'?

grid[0][2] contains an 'X' grid[2][1] contains an 'O' (Correct) Explanation char[][] grid = { {'-','-','X'}, {'-','-','-'}, {'-','O','-'}, }; This is a 2-Dimensional array. 'X' is located on the intersection of the first row (index 0) and the third column (index 2) grid[0][2] 'O' is located on the intersection of the third row (index 2) and the second column (index 1) grid[2][1]

You need to evaluate the following code segment: public static void main(String[] args) { double dNum = 2.667; int iNum = 0; iNum = (int)dNum; } What happens when the code segment is run?

iNum has a value of 2 Explanation Simplest way to convert a double to an int in Java is by down-casting it. This will return you the non-fractional part of the number as an int, but it doesn't do rounding, so even 9.999 will be converted to 9. If you are looking to convert double to the nearest integer e.g. 9.999 to 10, then you should use Math.random() method.

You need to create an application that asks the users for their date of birth in the format "MMDDYYYY". After the user has inputted their date of birth, you need to output their response to the console. Which of the following, satisfies these requirements?

import java.util.Scanner; public class DataReader { public static String getBirthdate() { System.out.println("Enter your birthday in the format MMDDYYYY"); Scanner sc = new Scanner(System.in); String birthdate = sc.next(); sc.close(); return birthdate; } public static void main(String args[]) { System.out.println(getBirthdate()); } } Explanation A Data input Stream lets an application read primitive Java datatype (int, bool, long, etc.) from an underlying input stream in a machine independent way. Scanner Class: A simple text scanner which can parse primitive types and Strings using regular expressions.A scanner breaks input into the delimiters you provide. By default the scanner class uses the white-space as the default delimiters

Which of the following statement is correct? ​

"X extends Y" is correct if X and Y are either both classes or both interfaces (Correct) Explanation The following rules apply for extending and implementing: Classes can only be extended by other classes, not by interfaces. Classes implement interfaces, not by classes. Interfaces can only be extended by other interfaces, not by classes.

Your instructor asks you to evaluate four arithmetic code segments. What is the value of each code segment? (2 + 3) * 4 - 1 4 * 4 + 2 * 5 8 * 2 % 3 5 / 2 - 4 % 2

(2 + 3) * 4 - 1 = 19 4 * 4 + 2 * 5 = 26 8 * 2 % 3 = 1 5 / 2 - 4 % 2 = 2 (Correct) Explanation These are the correct answers: (2 + 3) * 4 - 1 = 19 (2 + 3)* 4 - 1 = 5 * 4 - 1 = 20 - 1 = 19 4 * 4 + 2 * 5 = 264 * 4 + 2 * 5 = 16 + 10 = 26 8 * 2 % 3 = 1 8 * 2 % 3 = 16 mod 3 = 1 5 / 2 - 4 % 2 = 2 5 / 2 - 4 % 2 = 2.5 - 4 % 2 = -1.5 mod 2 = 2 See java operator precedence: http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html

You have the following code segment. (Line numbers are included for reference only.) public static void main(String[] args) { double number = 27; number %= -3d; number += 10f; number *= -4; System.out.println(number); } What is the output of line 07?

-40 Explanation The following process takes place when we run the code: A variable named number, of the type double is declared and initialized to 27. (%=) this is a shorthand notation for modulo, this results in number = number % -3 = 27 mod -3 = 0 10 is added to number. ( number = number + 10 = 0 + 10 = 10) And finally, the value of number is multiplied by -4, resulting in -40

What is the proper filename extension for a Java bytecode compiled file?

.class Explanation In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the javaccompiler. The bytecode gets saved on the disk with the file extension .class

You need to analyze the following code segment. Line numbers are included for reference only. public void printInt(){ if(true){ int num = 1; if(num > 0){ num++; } } int num = 1; addOne(num); num = num -1; System.out.println(num); } private void addOne(int num) { num = num + 1; }

0 Explanation There are two different variables named num. The first variable is within the scope of the if body, and the second variable is within the scope of the printInt method. Once the body of the if clause is executed, the first num no longer exists. We now only have the following code: int num = 1; addOne(num); num = num -1; System.out.println(num); the second variable is declared and assigned a value of 1. For the second statement you need to be familiar with Value type objects and reference type objects. Primitive data types (int, long, double, char, etc.) are value types, when we pass a value type to a method, we're basically passing by value. So whatever changes made on the parameter within the method, will not be reflected on the variable we passed as a parameter to the method. Basically the addOne(num); can be removed, since it does not affect the value of variable num. We're left with the following: int num = 1; num = num -1; System.out.println(num); // 1-1=0

What will be the output if you run the following program? public class Main{ public static void main(String args[]){ int i; int j; for (i = 0, j = 0 ; j < 1 ; ++j , i++){ System.out.println( i + " " + j ); } System.out.println( i + " " + j ); } }

0 0 will be printed followed by 1 1. Explanation Both variable "i" and "j" are initialized to 0 at the beginning of the loop. for (i = 0, j = 0 ; j < 1 ; ++j , i++){ System.out.println( i + " " + j ); } The loop will run as long as the value of "j" is less than 1. This will output 0 0 to the console. Once the loop has executed once, the value of "j" and "i" will be incremented by 1. The loop checks the condition where j < 1 the condition isn't satisfied, so the loop breaks. The following line is executed: System.out.println( i + " " + j ); Since "i" and "j" are both 1, this will output 1 1 to the console.

Examine the following program: public class JavaProgram1 { int x = 25; public static void main(String args[]) { JavaProgram1 app = new JavaProgram1(); { int x = 5; } { int x = 10; } int x = 100; System.out.println(x); System.out.println(app.x); } public JavaProgram1() { int x = 1; System.out.println(x); } } Three values will be outputted to the console. Which of the following output is correct?

1 100 25 Explanation 1 will be outputted first (line 18), during the instantiation of the object on line 4. This piece of code is out of scope and thus not affect other code within the method. { int x = 5; } { int x = 10; } We are then left with this: int x = 100; System.out.println(x); //Outputs 100 System.out.println(app.x); //Outputs 25 The public class JavaProgram1 has an initialized instance variable named x. The value of x is 25. The reference of the new JavaProgram1 object that was created is stored in the variable "app". This means that if we write System.out.println(app.x); we're basically outputting the value of the instance variable x.

You are interviewing for a job as a Java developer. You need to evaluate the following code. Line numbers are included for reference only. String s1 = "Hello World"; String s2 = "Hello World"; String s3 = s2; For each of the following statements, select Yes if the statement is true. Otherwise, select No. 1. s1 and s2 refer to the same object in memory. 2. s2 and s3 refer to the same object in memory. 3. A different string can be assinged to s1 on line 04. 4. A different string can be assinged to s2 on line 05.

1 No 2. Yes 3. Yes 4. Yes Explanation s1 and s2 refer to the same object in memory: Even thou s1 and s2 have the same value, they refer to two different objects in memory. s2 and s3 refer to the same object in memory: s2 and s3 refer to the same object in memory. A string is an optimized complex reference type, which means that whenever we assign the value of one reference type object to another reference type object, we're basically copying the reference from one object to another. A very important note about Strings is that Strings are immutable and cannot change after they have been defined. If I were to reassign a string to either s1 or s2, a new object would be created in memory.

You have the following code segment. Line numbers are included for reference only. public class Customer { private int id = 3; public static void main(String[] args) { Customer customer = new Customer(); id = 5; showId(); } protected void showId(){ System.out.println(id); } } The code does not compile. For each of the following statements, select Yes if the action is required to resolve the compilation error. Otherwise, select No. NOTE: Each correct selection is worth one point. (Exam Environment) 1. Change the access modifier of the variable id to public. 2. Change the access modifier of showId method to public. 3. On lines 06 and 07, add the prefix customer to id and showId().

1. No 2. No 3. Yes (Correct) Explanation Both the showId() method as the private id field are declared as non-static, which means that they cannot be used in a static context. Since, the entry point of the application is declared within the Customer class, we can access both the private field and the protected method

You work for Woodgrove Bank as a Java programmer. You need to evaluate the following class. Line numbers are included for reference only. public class Account { protected int balance; public Account() { balance = 0; } public Account(int amount){ balance = amount; } } For each of the following statements, select Yes if the statement is true. Otherwise, select No. NOTE: Each correct selection is worth one point. (Exam Environment) 1. The Account class has a single constructor. 2. Other classes can inherit the Account class. 3. Line 08 is equivalent to this.balance = amount.

1. No 2. Yes 3. Yes (Correct) Explanation The Account class has two constructors defined: public Account() { balance = 0; } public Account(int amount){ balance = amount; } Only classes that are marked as final cannot be extended. protected int balance; The protected field balance is an instance variable. Instance variables can explicitly be called by using the 'this' keyword, which refers to the instance of a class.

You are interviewing for a job as a Java developer. You are presented with the following code. Line numbers are included for reference only. public static void main(String[] args) { char data1 = 65; System.out.println(data1); long data2 = 65; System.out.println(data2); float data3 = new Float("-65.0"); System.out.println(data3); short data4 = new Short("65.0"); System.out.println(data4); } You need to evaluate what happens when the code runs. 1. What happens when line 02 and 03 are run? 2. What happens when line 05 and 06 are run? 3. What happens when line 08 and 09 are run? 4. What happens when line 11 and 12 are run?

1. The letter 'A' is displayed. 2. The number 65 is displayed. 3. The number -65.0 is displayed. 4. An exception is thrown. (Correct) Explanation char data1 = 65; 65 is a decimal number, that translates to 'A' when assigned to a unicode data type variable. long data2 = 65; The numerical value is parsed exactly as it is written and is displayed exactly as it is parsed: 65 float data3 = new Float("-65.0"); The numerical value is parsed exactly as it is written and is displayed exactly as it is parsed: -65.0 short data4 = new Short("65.0"); The short data type stores whole numbers within a range of -32,768 and 32,767. A short data type variable cannot store decimal numbers or floating point numbers. This will result in a NumberFormatException being thrown

You need to evaluate the following code: public static void main(String[] args) { int count = 10; do{ System.out.print(count); count--; }while(false); } What will be the result?

10 (Correct) Explanation The do-while loop executes at least once even if the condition isn't satisfied. The application will output the following: 10. Since the condition is set to false, the loop will execute one time only.

You have been given the following class definition. class Student { int marks = 10; } What is the output of the following code? class Result { public static void main(String[] args){ Student s = new Student(); switch(s.marks){ default: System.out.println("100"); case 10: System.out.println("10"); case 98: System.out.println("98"); } } }

10 98 Explanation The default case executes only if no matching values are found. In this case, a matching value of 10 is found and the case label prints 10. Because a break statement is not specified within the case block, the code execution continues and executes the remaining statements within the switch block, until a break statement terminates it or it ends. In other words, control will fall through to the remaining cases until a break statement is executed or until the code ends. When using the switch construct always be aware of the break statements, because if not specified, they can lead to unwanted results.

Examine the following code: public static void main(String[ ] args) { int [ ][ ] values = {{9,8,7}, {6,5,4}, {3,2,1,0}, {9,7,1,6}}; System.out.println(values[2][1]); } What is the result?

2 ​ Explanation This is a Two-dimensional array, int [][] values = {{9,8,7}, {6,5,4}, {3,2,1,0}, {9,7,1,6}}; There are 4 rows, and a total of 4 columns.

You're a Java developer. You need to examine the following application. What is the output of the following application? public class Airplane { static int start = 2; final int end; public Airplane(int x) { x = 4; end = x; } public void fly(int distance) { System.out.print(end-start+" "); System.out.print(distance); } public static void main(String... start) { new Airplane(10).fly(5); } }

2 5 Explanation Once the entry point is reached, a new instance of the Airplane class is created using the following constructor: public Airplane(int x) { x = 4; end = x; } This constructor takes a parameter x, the value of x is 10. Within the body of the constructor the value of x is changed to 4. The variable end is assigned the same value of x, which is 4. Now, another method is invoked, namely the fly method. A value of 5 is passed to the following method: public void fly(int distance) { System.out.print(end-start+" "); // 4 - 2 = 2 System.out.print(distance); // 5 } The result is: 2 5

Which of the following is not a valid variable name?

2blue (Correct) Explanation A variable name cannot start with a number. All Java components require names. Names used for classes, variables, and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character, identifiers can have any combination of characters. A keyword cannot be used as an identifier. Most importantly, identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, __1_value. Examples of illegal identifiers: 123abc, -salary.

Double

64 bit numbers with decimal points

Long

64-bit whole number, pretty large

printf

A method of the System class that is capable of outputting formatted text.

There are three types of exceptions in Java. Checked Exceptions Unchecked Exceptions Errors Which of the following is true about Errors?

An error can be thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. (Correct) The Error class denotes an exception that an application is not likely to be able to deal with. (Correct) Explanation Error classes are used to define irrecoverable and fatal exceptions, which applications are not supposed to catch. Programmers cannot do anything with these exceptions. Even if you catch OutOfMemoryError, you will get it again because there is a high probability that the Garbage Collector may not be able to free memory. Unchecked Exception Unchecked exceptions are checked at runtime. Unchecked exceptions extend RuntimeException class. You cannot be reasonably expected to recover from these exceptions. Unchecked exceptions can be avoided using good programming techniques. Throwing unchecked exception helps to uncover lots of defects Checked Exception Checked exceptions are checked at compile time. Checked exceptions extend Throwable or its sub-classes, except RunTimeException and Error classes. Checked exceptions are programmatically recoverable. You can handle checked exception either by using try/catch block or by using throws clause in the method declaration. Static initializers cannot throw checked exceptions.

You are writing a Java console program. The program accepts command line arguments. You need to ensure that the main method parses and handles each command line argument. How should you complete the code? public static void main(|||||||||||||||||||||||| args) { for (int i = 0; i< ||||||||||||||; i++) { handleArgument(||||||||||||); } } Choose the appropriate answers?

Answer 1 => String[] Answer 2 => args.length Answer 3 => args[i] Explanation You use the String[] to create an array of Strings for the Entry point of the application. You loop through each of the elements, starting from index 0 to length of the array - 1 or differently said you loop through each of the elements, starting from index 0 to the highest index less than then length of the array. Elements within an array can be accessed by using indexers or indexes, specified between the square brackets.

static

Argument that cannot be changed when declaring the main method; It takes one space in memory; (for a class to be called from a _______ method, it too must be ______, or runtime error )

You need to evaluate the following lines of code: int x = 10, y = 1; int z = x/(--y); System.out.println ("Result = " + z); When the application is run, an exception is thrown. Which exception is most likely to be thrown?

ArithmeticException Explanation int a = 30, b = 1; int c = a/(--b); If b equals 1, then a/(--b) will result in 30/0. Division by zero is not possible, this throws an ArithmeticException.

protected method

Can be called by any subclass within its class, but not by unrelated classes (same package only)

You work as a Java programmer. A member of the team creates the following program. Line numbers are included for reference only. public static void main(String[] args) { int timer = 60; while(timer => 0){ if(timer = 0) break; else{ System.out.println("The timer is counting down..."); timer++; } } } The program is supposed to display a message to the console while it counts down from 60. The method does not work as intended. How should you complete the code?

Change line 03 to while(timer >= 0){ Change line 04 to if(timer == 0) Change line 08 to timer--; Explanation The correct answer is: public static void main(String[] args) { int timer = 60; while(timer >= 0){ if(timer == 0) break; else{ System.out.println("The timer is counting down..."); timer--; } } } A variable timer of the type int is created, and the variable is initialized to 60. The while loop is constructed to be executed while 60 reaches zero (zero included). In other words, the loop should execute as long as the value of the timer variable is not less than zero. Execute as long as timer >= 0 . '=>' is not a valid Java operator. '=' is an assign operator and cannot be used as a boolean operator. Within the body of the loop we have to make sure that the loop does not execute infinitily. Since, this loop is constructed for countdown purposes, we have to decrement the loop on each iteration.

Exhibit: class Circle { public double radius; public Circle(double radius){ this.radius = radius; } public void expand(double amount){ this.radius += amount; } } You need to use a Circle class (in Exhibit) to do the following: Create a Circle instance. Call the expand method. Print the new radius. How should you complete the code? ​

Circle circle = new Circle(100); circle.expand(50); double newRadius = circle.radius; Explanation You create a new Circle instance by writing this code: Circle circle = new Circle(100); You invoke the expand method on the newly created Circle instance, by writing the following code: circle.expand(50); The new value of the radius can be retrieved by writing the following: double newRadius = circle.radius; Be aware of the naming conventions in Java. 'Circle' with a capital C, denotes the type or class. 'circle' with a lowercase c, denotes the instance of a type or class.

Given: 1. ClassA has a ClassD 2. Methods in ClassA use public methods in ClassB 3. Methods in ClassC use public methods in ClassA 4. Methods in ClassA use public variables in ClassB Which is most likely true?

ClassB has weak encapsulation Explanation ClassB has weak encapsulation. In programming, encapsulation focuses primarily on information hiding. In the context is given that classB contains public methods and public variables (data members), that are both used by ClassA. This exposes ClassB's behavior, and violates encapsulation. A good practice is to always declare class variables (data members) private (encapsulation - data members), and use getters and setters as an interface for other objects to access those data members, instead of directly exposing the variables to other objects.

scanner.close()

Closes the scanner to prevent resource leaks

You are interviewing for a job as a Java developer. You need to demonstrate your understanding of switch statements. For each of the following code segments, select Yes if the code segment can be changed to a switch statement with up to three case statements. Otherwise, select No. (Exam Environment) Code segment 1: if (age >= 25) { discount = 0.50; } else if (age => 21){ discount = 0.25; } else { discount = 0.0; } Code segment 2: if (grade == "A") { message = "Exceeds Standards"; } else if (grade == "B"){ message = "Meets Standards"; }else { message = "Needs Improvement"; } Code segment 3: if (gpa == 4.0) { priority = 1; } else if (gpa >= 3.0){ priority = 2; } else if (gpa >= 2.5){ priority = 3; }

Code segment 1: No Code segment 2: Yes Code segment 3: No Explanation This is the only code segment that can be converted to a switch statement: if (grade == "A") { message = "Exceeds Standards"; } else if (grade == "B"){ message = "Meets Standards"; }else { message = "Needs Improvement"; } The other code segments can also be converted to switch statements but require a more complex work around, which won't be efficient. Switch statements, in contrast to if-else statements primarily evaluate the value of variables based on a single value. An if-else statement can test expressions based on ranges of values or conditions.

You need to analyze the following code? public class Frodo extends Hobbit { public static void main(String[] args) { Short myGold = 7; System.out.println(countGold(myGold, 6)); } } class Hobbit { int countGold(int x, int y) { return x + y; } } When you compile and run the application, what will be the result?

Compilation fails due to an error on line 6 Explanation The class Frodo inherits the method countGold from the class Hobbit. The main method is a static method, executing the non-static method countGold from a static context will result in a compilation error.

Examine the following code: public class Main { int x = 3; public static void main(String[] args) { new Main().go1(); } void go1() { int x; go2(++x); } void go2(int y) { int x = ++y; System.out.println(x); } } What will be the result?

Compilation fails due to compilation error Explanation A compilation error is thrown on line 10 (method go1()), because variable x might not have been initialized. In Java, using a variable that hasn't been initialized will result in a compilation error. To fix this, simply write: int x = 0;

You have the following program: class Dog { public void bark() { System.out.print("woof "); } } class Hound extends Dog { public void sniff() { System.out.print("sniff "); } public void bark() { System.out.print("howl "); } } public class DogShow { public static void main(String[] args) { new DogShow().go(); } void go() { new Hound().bark(); ((Dog) new Hound()).bark(); ((Dog) new Hound()).sniff(); - line 28 } } What is the result?

Compilation fails with an error at line 28 Explanation An object of the type Hound is up-casted to the type Dog. Class Dog doesn't have a sniff method defined.

Byte

Contains numbers from -128 to 127

Boolean.toString();

Converts a boolean to a String

Integer.parseInt(args[0]);

Converts a string of data to a whole number.

Scanner scan = new Scanner(System.in);

Creates a Scanner object "scan"

You work on a team that develops e-commerce applications. A member of the team creates a class named DB that connects to a database. The class contains a method named query. You need to instantiate the db class and invoke the query method. How should you complete the code?

DB db = new DB(); db.query(); Explanation The syntax for creating an object is as follow: <Type> <variable_name> = new <Type> DB db = new DB(); To invoke the query() method on the newly created object we simply write the following: db.query();

getMessage

Displays details of an exception

Which of the following code segments successfully converts a string value to a primitive double value?

Double.parseDouble(numberString); (Correct) ​ Double.valueOf(numberString); (Correct) Explanation In this case we make us of the Double wrapper class, which adds a number of functionalities to our primitive double type, including conversions. We can use the Double.parseDouble() or Double.valueOf() method to get corresponding primitive double value or value of Double wrapper class respectively. If the string cannot be converted to a double, a NumberFormatException will be thrown.

ScannerTest.main(ScannerTest.java:9)

Example of an error caused by a mismatch of data types while testing the Scanner utility, not in a "scanner" method (Checked exception)

What is the use of a constructor?

Initialize the class and it's members Explanation A constructor or initializer is used to initialize an object and it's class members

Exhibit; 1 - class Random { 2 - public static void test(){ 3 - double y = Math.random(); 4 - int y = Math.random(); 5 - 6 - System.out.println(y); 7 - } 8 - } The Random class is shown in the exhibit. Line numbers are included for reference only. You need to evaluate the class and determine which line prevents the class from compiling successfully. Which line prevents the class from compiling successfully?

Line 04 Explanation Line 04 causes a compilation error. This is because the variable y has already been declared as double on line 03. You cannot declare the same variable twice within the same scope.

You need to evaluate the following code segment. Line numbers are included for reference only. public static void main(String... args) { int a = 5; int b = 10; int c = ++a * b--; System.out.println(c); int d = a-- + ++b; System.out.println(d); } Use the drop-down menus to select the answer choice that answers each question based on the information presented in the code. NOTE: Each correct selection is worth one point. (Exam Environment) What is the result at line 05? What is the result at line 07?

Line 05: 60 Line 07: 16 (Correct) Explanation int c = ++a * b--; This line of code, first increments a by one (++a) and then multiplies the new value of a (6) by the value of b (10), and then decrements b by 1. We're than left with a = 6 and b = 9. int d = a-- + ++b; This line of code, first increments b by one (++b), and then adds the new value of b (10) to the current value of a (6), and then decrements a by 1.

java.util.Scanner

Loads the library to allow the user to take information into the code

This question requires that you evaluate the following text to determine if it's true: Class variables have a scope limited to a method. Select "No change is needed" if the statement is correct. If the statement is incorrect, select the appropriate answer that makes the statement correct.

Local variables Explanation A local variable in Java is a variable that's declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren't even aware that the variable exists.

You need to analyze the following stack trace: Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) In which method is the exception initially thrown and what is the type of the instance that method resides in?

Method => getTitle(); Instance type => Book (Correct) Explanation The exception is thrown in an Instance of the Book class, within the getTitle method on line 16.

String.isEmpty()

Method checking if a String is empty (no null method)

Evaluate the following code: public class Main{ class MyException extends Exception {} public void myMethod() throws ______{ throw new MyException(); } } Which of the following can be replaced with ______? (Choose all that apply)

MyException (Correct) ​ Exception (Correct) ​ Throwable (Correct) Explanation Exception, because Exception is a superclass of MyException. The throws clause is needed because MyException is a checked exception. Any exception that extends java.lang.Exception but is not a subclass of java.lang.RuntimeException is a checked exception. Throwable, because Throwable is a super class of Exception.

The question requires that you evaluate the italic text to determine if it is correct. You have the following class definition: class Logger{ public void logError(String message){ } } The logError method can be invoked by code in all classes in the same package as the Logger class. Review the italic text. If it makes the statement correct, select "No change is needed." If the statement is incorrect, select the answer choice that makes the statement correct.

No change is needed Explanation Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

You have been given the following code: public static void traverse(String[][] board){ for(int x = 0; x < board.length; x++){ for(int y = 0; y < board[x].length;y++){ System.out.println(board[x][y]); } } You need to make sure that the method satisfies the following conditions: The method accepts a two-dimensional string array. The method prints the content of each array element. The size of each dimension of the array might be different. If the method satisfies the conditions, select "No change is needed". If the method is incorrect, select the appropriate answer to correct the method.

No change is needed Explanation In a 2-D array we have a table-like structure. The first loop, loops through all the columns, from left to right, based on the number of columns(board.length). For each iteration the first loop performs, the second loop iterates from top to bottom, based on the total number of rows per column (board[x].length). So we have a scenario where we have: loop one performs first iteration 0. (1st column) loop two performs iterations 0 - 5 - 10 - 15. loop one performs second iteration 1. (2nd column) loop two performs iterations 1 - 6 -11 -16. loop one performs third iteration 1. (3rd column) loop two performs iterations 2 - 7 - 12 - 17. And so on.

Given: try { int x = Integer.parseInt("two"); } Which could be used to create an appropriate catch block? (Choose all that apply)

NumberFormatException (Correct) IllegalArgumentException (Correct) Explanation Integer.parseInt can throw a NumberFormatException, and IllegalArgumentException is its superclass (i.e., a broader exception).

Float

Numbers whose decimals have the letter 'f' after it (also loses precision in a calculation)

IOException

Occurs when a file being read from does not exist

InputMismatchException

Occurs when an incorrect data type is entered or read

You need to evaluate the following Java program. Line numbers are included for reference only. public static void main(String... args) { double pi = Math.PI;//3.141593 System.out.format("Pi is %.3f%n", pi); System.out.format("Pi is %.0f%n", pi); System.out.format("Pi is %09f%n", pi); }

Pi is 3.142 Pi is 3 Pi is 03.141593 Explanation the value of pi is approximately 3.141593. System.out.format("Pi is %.3f%n", pi); This line formats the value of pi, so that only the first 3 decimal places are shown and also takes care of rounding to the nearest decimal point. System.out.format("Pi is %.0f%n", pi);This line formats the value of pi, so that no decimal places are shown. System.out.format("Pi is %09f%n", pi);This line formats the value of pi, by adding 0 at the beginning to make the total length of the formatted string, including the decimal point, 9 characters. This for example: System.out.format("Pi is %011f%n", pi);formats the value of pi, by adding 0 at the beginning to make the total length of the formatted string, including the decimal point, 11 characters, and would have the following result: Pi is 0003.141593

You are writing a Java class named Pcikle. In the entry point of the application you need to do the following: Create a new instance of the Pickle class. Set the isCreated field to true. Invoke the preserve method. public class Pickle { boolean isPreserved = false; private boolean isCreated = false; void preserve(){ isPreserved = true; } public static void main(String[] args) { //insert code here } } How should you complete the code?

Pickle pickle = new Pickle(); pickle.isCreated = true; pickle.preserve(); Explanation The correct answer is: Pickle pickle = new Pickle(); pickle.isCreated = true; pickle.preserve(); To create a new instance of a class, we need to create an object of that type using the new keyword. isCreated is declared private, which means it's only accessible to members and methods within this class. Since isCreated is not declared with a static modifier, it signifies an instance variable. Instance variables can be accessed by the instance with the 'this' keyword or depending on the modifier, by using the variable that is holding the reference to the newly created instance, which is pickle. Another reason why this would be obvious instead of just writing isCreated = true;is because, isCreated is a non-static field. Therefore it cannot be used in a static context. Same goes for the method.

getStackTrace

Returns an array of stack trace elements

Fill in the blanks: A __________ occurs when a program recurses too deeply into an infinite loop, while a(n) _____________occurs when a reference to a nonexistent object is acted upon.

StackOverflowError, NullPointerException Explanation A StackOverflowError is a runtime error in java. It is thrown when the amount of call stack memory allocated by JVM is exceeded. A common case of a StackOverflowError being thrown, is when call stack exceeds due to excessive deep or infinite recursion. NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.

You need to evaluate the following code: public static void main(String[] args){ String tree = "pine"; int count = 0; if (tree.equals("pine")) { int height = 55; count = count + 1; } System.out.print(height + count); } What is the result?

The code does not compile (Correct) Explanation The code will not compile because height is declared within the body of an if statement, and is only accessible within that body. Trying to access height outside of that body will result in a cannot find symbol error, because height is out of scope on line 08.

Given that FileNotFoundException is a subclass of IOException, what is the output of the following Java application? package office; import java.io.*; public class Printer { public void print() { try { throw new FileNotFoundException(); } catch (IOException exception) { System.out.print("Z"); } catch (FileNotFoundException enfe) { System.out.print("X"); } finally { System.out.print("Y"); } } public static void main(String... ink) { new Printer().print(); } }

The code does not compile. Explanation The code does not compile because the catch blocks are used in the wrong order. Since IOException is a superclass of FileNotFoundException, the FileNotFoundException is considered unreachable code, because the FileNotFoundException that has been thrown is already caught by it's supertype IOException. For this reason, the code does not compile.

The following Java code exists (line numbers are included for reference only): char data = 65; System.out.println(data); You need to determine what happens when this code is compiled and run. What happens when this code is run?

The letter 'A' is printed (Correct) Explanation The letter 'A' is printed. The char data type represents Unicode characters. The letter 'A' is the character equivalent of the value 65. An exception is not thrown. The compiler assigns values in the range of 0 to 65,536 to char data types. When you print the values of these types, their Unicode-equivalent characters are printed. Therefore, the Java run-time does not throw an exception when a value of the char data type is printed.

IllegalArgumentException

Thrown by a method to indicate an illegal or inappropriate argument.

You need to evaluate the following program. public class TestClass { public static void main(String[] args) { System.out.println("Values : "+args[0]+args[1]); } } What will be the output of the following program when it is compiled and run with the command line: java TestClass 1 2 3

Values : 12 (Correct) Explanation In Java, command line arguments are passed into the program using the String[]parameter to the main method. The String array contains actual parameters and does not include java and the name of the class. Therefore, in this case, args will point to an array of Strings with 3 elements - "1", "2", and "3". The program prints out only args[0] and args[1], which is 1 and 2.

Examine the following code: public static int fee(char model){ int price = 0; switch(model){ case 'A': price = 50; break; case 'T': price = 20; break; case 'C': price = 5; break; default: price = 100; break; } return price; } Which of the following statement(s) are correct?

When model equals 't', than the returned value equals 100 (Correct) ​ When model equals 'Q', than the returned value equals 100 (Correct) ​ When model equals 'A', than the returned value equals 50 (Correct) Explanation When model has a value of 'Q' or 't' (case sensitive), none of cases will be matched. The control then flows to the default case, if exists.

You work as an intern Java programmer at Adventure Works. Your team lead asks you to create a method. The method must meet the following requirements: Accept an int array Check for duplicate values in the array Stop the outer loop as soon as a duplicate value has been detected and return true Return false if all values in the array are unique You already have a part of this method declared: Larger image How should you complete the code? To answer, select the appropriate code segments that should be replaced with the black boxes.

int x = 0; x <= array.length - 1; y++ break; (Correct) Explanation The method should look like this: public static boolean duplicate(int[] array){ boolean isDuplicate = false; for(int x = 0; x <= array.length - 1; x++){ System.out.println(array[x]); for(int y = x + 1; y < array.length; y++){ if(array[x] == array[y]) isDuplicate = true; if(isDuplicate) break; } } return isDuplicate; }

You need to create an array of integers to store the following values: 1, 9, 10, 12 and 15. Which of the following provide the requested solution.

int[] values = {1, 9, 10, 12, 15}; int[] values = new int[]{1, 9, 10, 12, 15}; Explanation int[] values = {1, 9, 10, 12, 15}; This creates a traditional array of integers, and is considered the short-hand notation. The full-out written declaration of an integer array is the following: int[] values = new int[]{1, 9, 10, 12, 15};

Which of the following creates an empty two-dimensional array with dimensions 2×2?

int[][] blue = new int[2][2]; Explanation This is the valid syntax for declaring a 2x2 dimensional array: int[][] blue = new int[2][2];

You need to compile a .java file. Which of the following commands do you use?

javac Explanation javac (pronounced "java-see") is the primary Java compiler included in the Java Development Kit (JDK) from Oracle Corporation.

javac command

loads a Java class from the command line

You are writing a Java method. The method must meet the following requirements: Accept a String parameter firstName Display a welcome message that constains firstName Ensure that the first letter of the name is capitalized and the remaining letters are in lowercase How should you complete the code using only the following functions: charAt, substring, toLowerCase, toUpperCase Larger image

public String showGreeting(String firstName){ String welcomeMsg = "Welcome, "; welcomeMsg += firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase(); return welcomeMsg; } (Correct) Explanation The correct answer is: public String showGreeting(String firstName){ String welcomeMsg = "Welcome, "; welcomeMsg += firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase(); return welcomeMsg; } Method substring() returns a new string that is a substring of given string. Java String substring() method is used to get the substring of a given string based on the passed indexes. There are two variants of this method. When we pass only the starting index: String substring(int beginIndex); Returns the substring starting from the specified index, as seen in firstName.substring(1).toLowerCase(); . This part of the code takes a substring from the firstName starting from index 1 to the end of the string, the firstName without the first letter, and changes it's case, if not already, to lowercase using the toLowerCase method When we pass both indexes: String substring(int startIndex, int endIndex);This method returns a new String object containing the substring of the given string from specified startIndex to endIndex, as seen in firstName.substring(0,1).toUpperCase() . This part of the code takes a substring starting from the index 0 up to the character at index 1, the first letter of the firstName, and capitalizes it using the toUpperCase method

You're a Java developer. You have been given the following interface: public interface Frobnicate { public void twiddle(String s); } Which of the following code segment is a correct implementation of this interface?

public abstract class Frob implements Frobnicate { } Explanation The correct answer is: public abstract class Frob implements Frobnicate { } public abstract class Frob implements Frobnicate { public abstract void twiddle(String s) { } } This is incorrect, because an abstract methods do not provide implementation. They only define a signature. When an abstract class implements an interface, it doesn't have to re-declare the interface methods. public class Frob extends Frobnicate { public void twiddle(Integer i) { } } This is incorrect, because a class cannot be extended by an interface, it needs to implement the interface. public class Frob implements Frobnicate { public void twiddle(Integer i) { } } This is incorrect, because it does not implement the twiddle method. (See the method signature) public class Frob implements Frobnicate { public void twiddle(String i) { } public void twiddle(Integer s) { } } This is also incorrect, because it does not implement the twiddle method. (See the method signature)

You are writing a Java method. The method must meet the following requirements: Accept a String array named entries Iterate through entries Stop the iteration and return false if any element has more than 10 characters Otherwise, return true Which of the following is correct?

public boolean validateEntries(String[] entries){ boolean allValidEntries = true; for(String entry : entries){ if(entry.length() > 10){ allValidEntries = false; break; } } return allValidEntries; } Explanation The for loop, discussed in the answer is similar to a for-each loop, that iterates through each individual element. The loop simply translates to, "iterate through all the elements of the entries, and store the current entry within the variable "entry". Break is used to exit the loop immediately when an entry's length is greater than 10.

You are writing a Java class named Savings Account. The class must meet the following requirements: Inherit from an existing class named Account. Include a constructor that uses the base class constructor to initialize the starting balance. Include a substitute toString() method. How should you complete the code? Larger image

public class SavingsAccount extends Account { double rate = 0.02; SavingsAccount(double startingBalance){ super(startingBalance); } @Override public String toString(){ return String.format("Savings current Balance: $%.2f", this.getBalance()); } } (Correct) Explanation To inherit from another class, we have to use the keyword extends. To call or invoke the constructor of a base class, we have to use the keyword super. Every class in java is child of Object class either directly or indirectly. Object class contains toString() method. We can use the toString() method to get the string representation of an object. Whenever we try to print the Object reference then internally toString() method is invoked. If we want to define our own toString() method we need to override the base class toString() method using the @Override annotation.

You have a Java class named InsurancePolicy. You need to define a constant data member named rate. The data member must be accessible by any class without instantiating the InsurancePolicy class. How should you complete the code?

public final static double RATE = .0642; (Correct) Explanation We use the public modifier so that the data member can be accessible by all classes, regardless of their package. We use the static keyword / modifier so that the data member becomes a class variable. We use the final keyword to indicate that the data member contains a constant value that throughout the life-cycle of the application cannot change.

You are writing a Java method named safeRoot. The method must meet the following requirements: Accept two double parameters radicand and index. If radicand is negative and index is even, return null. If radicand is negative and index is odd, return -Math.pow(-radicand, 1 / index) Otherwise, return Math.pow(radicand, 1 /index) How should you complete the code?

public static Double safeRoot(double radicand, double index){ if(radicand >= 0){ return Math.pow(radicand, 1 /index); } else { if(index % 2 == 0){ return null; } else{ return -Math.pow(-radicand, 1 / index); } } } (Correct) Explanation The correct answer is: public static Double safeRoot(double radicand, double index){ if(radicand >= 0){ return Math.pow(radicand, 1 /index); } else { if(index % 2 == 0){ return null; } else{ return -Math.pow(-radicand, 1 / index); } } } This method correctly returns Math.pow(radicand, 1 /index) if radicand is not negative. (in other words zero, or positive). This method correctly returns null, if radicand is negative and index is even. This method correctly returns -Math.pow(-radicand, 1 / index), if radicand is negative and index is not even. (in oher words odd)

Which of the following code snippets are valid variations of the main method in Java?

public static void main(String... args) {} public static void main(String args[]) {} public static void main(String[] args) {} Explanation The main method can be declared as either: public static void main(String[] args) or public static void main(String args[]) or public static void main(String... args); The main method (Entry point) in Java has the following requirements: The method "main" must be declared public, static, and void. It must accept a single argument that is an array of strings. String[] args , String args[] and String... args symbolize an array of strings.

You are writing a Java console program. The program must meet the following requirements: Read line of text entered by the user. Print each word in the text to the console on a separate line. Larger image

public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); while(input.hasNext()){ System.out.println(input.next()); } } Explanation To read input from the command line, we can make use of the Scanner class. The Java Scanner class breaks the input into tokens using a delimiter which is white-space by default. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file. The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. The java.util.Scanner.next() method finds and returns the next complete token from this scanner.

Consider the following code: class Base{ private float f = 1.0f; void setF(float f1){ this.f = f1; } } class Base2 extends Base{ private float f = 2.0f; //Code to be inserted here } Which of the following options are a valid example of overriding? (Choose all that apply)

public void setF(float f1){ this.f = 2*f1; } (Correct) ​ protected void setF(float f1){ this.f = 2*f1; } (Correct) Explanation Overriding in Java. In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. This means that the method that is overridden should have the same method signature and return type as that of the method of the parent class. An overriding method can be made less restrictive than the overridden method. The restrictiveness of access modifiers is as follows: private > default > protected > public (where private is most restrictive and public is least restrictive). Note that there is no modifier named default. The absence of any access modifiers implies the default access. protected is less restrictive than default, so it is valid for overriding the method. public is less restrictive than default, so it is also valid for overriding the method. private is more restrictive than default, so it is NOT valid for overriding the method.

do-while loop

repeatedly executes a block of statements until a specified Boolean expression evaluates to false.

%d

returns an integer as a decimal value

java command

runs a Java class from the command line (can contain raw numbers, no commas or percent symbols)

%,d

separates an integer with a comma as a thousands' separator

This question requires that you evaluate the text below, to determine if it is correct. You should use a byte data type to store a numeric value of 216, so that the least amount of memory is used. Review the statement. If it makes the statement correct, select "No change is needed". If the statement is incorrect, select the answer choice that makes the statement correct.

short Explanation A byte stores numerical values ranging from -128 to 127, and takes 8 bits (1 byte) of memory. Given the range, this data type is not applicable. A short stores numerical values ranging from -32,768 to 32,767, and takes 2 bytes of memory. An int stores values ranging from 2,147,483,648 to 2,147,483,647, and takes 4 bytes of memory. A long stores numerical values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, and takes 8 bytes of memory. The most memory efficient data type to store a numerical value of 216 is the short data type.

Evaluate the following code: public static void main(String[] args){ int a = 55; int b = 70; System.out.println(((b >= a && a >= 50)) && (a < 50 || a < b)); }

true Explanation System.out.println(a < 50 || a < b);The code evaluates to true. So "true" will be printed to the console.

You need to evaluate the following code: public static void main(String args[]) { int x= 10; int y= 25; int z= x + y; if(((x > y) || (z > y)) && (x < z)){ System.out.println(true); }else{ System.out.println(false); } } What will be outputted to the console?

true Explanation || => or && => and ((x > y) || (z > y)) this means either x > y or z > y has to be true. If one of the condition is true, this part returns true. true && (x < z), means that both conditions have to be true.


Conjuntos de estudio relacionados

accounting test true false chapt 3

View Set

Chapter 2: Western Asia and Egypt

View Set

Environmental Science Chapter 5 Section 2

View Set

ATI TEAS 7 - English & Language Usage

View Set

General Insurance Missed Quiz Questions

View Set

Chapter 13 Physical and Cognitive Development in Middle Adulthood

View Set

Sociology Mod 4 Chapter 3 Culture

View Set