Java is the future !: Questions/Answers
Showing posts with label Questions/Answers. Show all posts
Showing posts with label Questions/Answers. Show all posts

Tuesday, August 16, 2011

Quiz of the day | OCPJP - Aug 16, 2011


What will be the result of compiling and running the following code:

Options :
a) true
true
b) false
true
c) false
false
d) None of the above



Solution: Correct choice is option B.
Creating a new instance of the class File, you're not yet making an actual file, you're just creating a filename. So file.exists() return false.
createNewFile() method created an actual file. So file.exists() return true.

Quiz of the day | OCPJP - 16 Aug 2011


What is the output for the above code ?

Options :
a) Compile with error - Not allowed to override the return type of a method with a subtype of the original type.
b) class A - return C
c) class B - return D
d) Runtime Exception

Saturday, May 14, 2011

char a = '\u000A'. Why is this invalid?


Unicode escape characters of the form '\Uxxxx', where xxxx is a hexadecimal value, are processed very early in the translation process (see JLS 3.10.4 ). As a result, the special characters '0A' (line feed) and '0D' (carriage return) are interpreted literally as "end of line."
For example, the expression...

char A = '\u000A';
...therefore becomes...

char A =;
...which results in a compile-time error.
To avoid this error, always use the special escape characters '\n' (line feed) and '\r' (carriage return).

Is it allowed to declare the main method private?


Former JVM versions (pre-1.4) allowed the main method to have any accessibility (private, etc). This incompatibility with Section 12.1.4 of the Java Language Specification has been fixed as of version 1.4. In order to invoke a main method from the command-line, it is now mandatory to declare the main method as follows:

public static void main (String[] args)
If the main method has any access level other than public, it will no longer run from the command-line.

Sunday, April 24, 2011

What are some potential trips/traps in the SCJP exam?


  • Two top-level public classes cannot be in the same source file.
  • main() cannot call an instance (non-static) method.
  • Methods can have the same name as the constructor(s).
  • Watch for thread initiation with classes that don't have a run() method.
  • Local classes cannot access non-final variables.
  • Case statements must have values within permissible range.
  • Watch for Math class being an option for immutable classes.
  • instanceOf is not the same as instanceof.
  • Constructors can be private.
  • Assignment statements can be mistaken for a comparison; e.g., if(a=true)...
  • Watch for System.exit() in try-catch-finally blocks.
  • Watch for uninitialized variable references with no path of proper initialization.
  • Order of try-catch-finally blocks matters.
  • main() can be declared final.
  • -0.0 == 0.0 is true.
  • A class without abstract methods can still be declared abstract.
  • Map does not implement Collection.
  • Dictionary is a class, not an interface.
  • Collection (singular) is an Interface, but Collections (plural) is a helper class.
  • Class declarations can come in any order (e.g., derived first, base next, etc.).
  • Forward references to variables gives a compiler error.
  • Multi-dimensional arrays can be "sparse" -- i.e., if you imagine the array as a matrix, every row need not have the same number of columns.
  • Arrays, whether local or class-level, are always initialized
  • Strings are initialized to null, not empty string.
  • An empty string is not the same as a null reference.
  • A declaration cannot be labelled.
  • continue must be in a loop (e.g., for, do, while). It cannot appear in case constructs.
  • Primitive array types can never be assigned to each other, even though the primitives themselves can be assigned. For example, ArrayofLongPrimitives = ArrayofIntegerPrimitives gives compiler error even though longvar = intvar is perfectly valid.
  • A constructor can throw any exception.
  • Initializer blocks are executed in the order of declaration.
  • Instance initializers are executed only if an object is constructed.
  • All comparisons involving NaN and a non-NaN always result in false.
  • Default type of a numeric literal with a decimal point is double.
  • int and long operations / and % can throw an ArithmeticException, while float and double / and % never will (even in case of division by zero).
  • == gives compiler error if the operands are cast-incompatible.
  • You can never cast objects of sibling classes (sharing the same parent).
  • equals() returns false if the object types are different. It does not raise a compiler error.
  • No inner class (non-static inner class) can have a static member.
  • File class has no methods to deal with the contents of the file.
  • InputStream and OutputStream are abstract classes.

What's up with integers not being equal to one another? The following code prints "true, true, false, true". Shouldn't it be "true, true, true, true"?



The key to understanding this is that the JVM uses a process called "boxing" (or "auto-boxing") when converting an int (like 127) to an Integer object. This involves calling the Integer.valueOf(127) method. The JavaDoc:java.lang.Integer#valueOf(int) says: "Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values." What that means is that the valueOf() method has a cache of Integer objects, and if the primitive being boxed is in that range, the cached object is returned. It just so happens that 127 is in that range, but 128 is not. So i and j are the same object, while i1 and j1 are not.

Source: CodeRanch

How to convert a String array to ArrayList?

1.


2.


3.




Note: In the solution no 1 Arrays.asList() is efficient because it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array - a wrapper that makes the array look like a list. When you change an element in the list, the element in the original array is also changed. Note that the list is fixed size - if you try to add elements to the list, you'll get an exception.


If you only need read access to the array as if it is a List and you don't want to add or remove elements from the list, then only use solution no 1.

Source: JavaRanch

Sunday, November 7, 2010

Quiz of the Day | November 7, 2010



What will happen when you attempt to compile and run the above code? (Assume that the code is compiled and run with assertions enabled.)

a. It will print odd and even numbers from 0 to 9 correctly (0 even and 1 odd). 
b. It will print odd and even numbers from 0 to 9 incorrectly (0 odd and 1 even). 
c. Compilation error at line 9. 
d. Compilation error at line 10. 
e. It will result in an infinite loop.


Solution : Choice A is the correct answer.

The code will compile successfully and it will print odd and even numbers from 0 to 9 correctly, without reversing even and odd.

Let's look at the execution of the code. The assert statement at line 9 asserts that "i%2==0" must be true, which will be true for all the even numbers in the range 0 to 9 (0, 2, 4, 6, and 8), and false for all the odd numbers in the range 0 to 9 (1, 3, 5, 7, and 9). When the assert statement is evaluated to true, the second expression on the right hand side of the colon is not evaluated. On the other hand, when the assert statement is evaluated to false, the expression on the right hand side of the colon is evaluated and an AssertionError is thrown.

When the for loop starts with i=0, the assert condition at line 9 is evaluated to true, hence the other expression i-- is not evaluated, the value of i (0 here) is printed at line 10. Next, i is incremented to 1 in the next iteration of the for loop. The assert condition at line 9 is false in this case, hence the expression i--is evaluated (i becomes 0) and an AssertionError is thrown. The print statement at line 10 is not executed in this case. The catch statement at line 12 catches this error and the print statement at line 14 increments i with ++i and prints its value (which is 1 in this case). The same process is repeated for all the numbers, thus effectively printing all the even and odd number correctly.

The key here lies in understanding when the right-hand side expression of an assert statement gets evaluated. It gets evaluated *only* when the boolean left-hand side expression is evaluated to false. Hence, the loop will not result in an infinite loop. 


Source : "Facebook community"

Saturday, November 6, 2010

Converting a 2d array of ints to char and string in Java

Question : How can i convert the ints in a 2d array into chars, and strings?

If i copy ints to a char array i just get the ascii code.
For example
public int a[5][5]
//some code
public String b[5][5] = public int a[5][5]
Answer : Quite frankly, the easiest approach would simply leave your array as-is... and convert int values toString's when you use them:

Integer.toString(a[5][5]);
Alternatively, you could start with a String[][] array in the first place, and simply convert your intvalues to String when adding them:
a[5][5] = new String(myInt);
If you really do need to convert an array of type int[][] to one of type String[][], you would have to do so manually with a two-layer for() loop:
String[][] converted = new String[a.length][];
for(int index = 0; index < a.length; index++) {
    converted[index] = new String[a[index].length];
    for(int subIndex = 0; subIndex < a[index].length; subIndex++){
        converted[index][subIndex] = Integer.toString(a[index][subIndex]);
    }
}
All three of these approaches would work equally well for conversion to type char rather thanString.

Source : Stack-Overflow