Given the code fragment -
int var1 = -5;
int var2 = var1--;
int var3 = 0;
if (var2 < 0) {
var3 = var2++;
} else {
var3 = --var2;
System.out.println(var3);
What is the result?
Answer : C
Given:
public class MyClass {
public static void main(String[] args) {
String s = " Java Duke ";
int len = s.trim().length();
System.out.print(len);
What is the result?
Answer : B
Explanation: Java -String trim() Method
This method returns a copy of the string, with leading and trailing whitespace omitted.
Given:
Answer : A,D
Explanation:
The first println statement, System.out.println("Before if clause");, will always run.
If Math.Random() > 0.5 then there is an exception. The exception message is displayed and the program terminates.
If Math.Random() > 0.5 is false, then the second println statement runs as well.
Given the classes:
* AssertionError
* ArithmeticException
* ArrayIndexOutofBoundsException
* FileNotFoundException
* IllegalArgumentException
* IOError
* IOException
* NumberFormatException
* SQLException
Which option lists only those classes that belong to the unchecked exception category?
Answer : A
Explanation: Not B: IOError and IOException are both checked errors.
Not C, not D, not E: FileNotFoundException is a checked error.
Note:
Checked exceptions:
* represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
* are subclasses of Exception
* a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
Note:
Unchecked exceptions:
* represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes:
"Unchecked runtime exceptions represent conditions that, generally speaking,reflect errors in your program's logic and cannot be reasonably recovered from at run time."
* are subclasses of RuntimeException, and are usually implemented using
IllegalArgumentException, NullPointerException, or IllegalStateException
* method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
Given:
Answer : B
Explanation:
table.length is 3. So the do-while loop will run 3 times with ii=0, ii=1 and ii=2.
The second while statement will break the do-loop when ii = 3.
Note:The Java programming language provides ado-whilestatement, which can be expressed as follows: do { statement(s)
} while (expression);
Given the code fragment:
System.out.println(2 + 4 * 9 - 3); //Line 21
System.out.println((2 + 4) * 9 - 3); // Line 22
System.out.println(2 + (4 * 9) - 3); // Line 23
System.out.println(2 + 4 * (9 - 3)); // Line 24
System.out.println((2 + 4 * 9) - 3); // Line 25
Which line of codes prints the highest number?
Answer : B
Explanation: The following is printed:
An unchecked exception occurs in a method dosomething()
Should other code be added in the dosomething() method for it to compile and execute?
Answer : D
Explanation:
Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException,Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exceptionsubclasses inherit fromRuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch anyexceptions. Although this may seem convenient to the programmer, it sidesteps theintent of thecatchorspecifyrequirement and can cause problems for others using your classes.
Given:
Answer : A
Explanation:
We need to catch the exception in the doSomethingElse() method.
Such as:
private static void doSomeThingElse() {
try {
throw new Exception();}
catch (Exception e)
{}
}
Note: One alternative, but not an option here, is the declare the exception in doSomeThingElse and catch it in the doSomeThing method.
Given:
public class Test {
public static void main(String[] args) {
int arr[] = new int[4];
arr[0] = 1;
arr[1] = 2;
arr[2] = 4;
arr[3] = 5;
int sum = 0;
try {
for (int pos = 0; pos <= 4; pos++) {
sum = sum +arr[pos];
} catch (Exception e) {
System.out.println("Invalid index");
System.out.println(sum);
What is the result?
Answer : B
Explanation: The loop ( for (int pos = 0; pos <= 4; pos++) { ), it should be pos <= 3, causes an exception, which is caught. Then the correct sum is printed.
Which three statements are benefits of encapsulation?
Answer : A,B,D
Which three statements are true about the structure of a Java class?
Answer : A,B,C
Explanation: A: Private constructors prevent a class from being explicitly instantiatedby its callers.
If the programmer does not provide a constructor for a class, then the system will always provide a default, public no-argument constructor. To disable this default constructor, simply add a private no-argument constructor to the class. This private constructor may be empty.
B: The following works fine:
int cake() {
int cake=0;
return (1);
}
C: We can overload static method in Java. In terms of method overloading static method are just like normal methods and in order to overload static method you need to provide another static method with same name but different method signature.
Incorrect:
Not D: Only a public class in an application need to have a main method.
Not E:
Example:
class A
{
public string something;
public int a;
}
Q: What do you call classes without methods?
Most of the time: An anti pattern.
Why? Because it faciliates procedural programming with "Operator" classes and data structures. You separate data and behaviour which isn't exactly good OOP.
Often times: A DTO (Data Transfer Object)
Read only datastructures meant to exchange data, derived from a business/domain object.
Sometimes: Just data structure.
Well sometimes, you just gotta have those structures to hold data that is just plain andsimple and has no operations on it.
Not F: Fields need to be initialtized. If not the code will not compile.
Example:
Uncompilable source code - variable x might not have been initialized
Given the code fragment:
Answer : D
Given the code fragment:
System.out.printIn("Result: " + 2 + 3 + 5);
System.out.printIn("Result: " + 2 + 3 * 5);
What is theresult?
Answer : C
Explanation:
First line:
System.out.println("Result: " + 2 + 3 + 5);
String concatenation is produced.
Second line:
System.out.println("Result: " + 2 + 3 * 5);
3*5 is calculated to 15 and is appended to string 2. Result 215.
The output is:
Result: 235 -
Result: 215 -
Note #1:
To produce an arithmetic result, the following code would have to be used:
System.out.println("Result: " + (2 + 3 + 5));
System.out.println("Result: " + (2 + 1 * 5));
run:
Result: 10 -
Result: 7 -
Note #2:
If the code was as follows:
System.out.println("Result: " + 2 + 3 + 5");
System.out.println("Result: " + 2 + 1 * 5");
The compilation would fail. There is an unclosed string literal, 5", on each line.
Which statement initializes a stringBuilder to a capacity of 128?
Answer : D
Explanation:
StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by thecapacityargument.
Note: An instance of a StringBuilder is a mutable sequence of characters.
The principal operations on aStringBuilderare theappendandinsertmethods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.
Theappendmethod always adds these characters at the end of the builder; theinsertmethod adds the characters at a specified point.
Given the following four Java file definitions:
// Foo.java
package facades;
public interface Foo { }
// Boo.java
package facades;
public interface Boo extends Foo { }
// Woofy.java
package org.domain
// line n1
public class Woofy implements Boo, Foo {}
// Test.java
package.org;
public class Test {
public static void main(String[] args) {
Foo obj=new Woofy();
Which set modifications enable the code to compile and run?
Answer : E