Sunday, May 2, 2010

JAVA QA?

1) Which of the following statements hold true in the following program?
package generics;
import java.util.ArrayList;
import java.util.List;
public class Ques04 {
public static void main(String[] args) {
List allInstruments = new ArrayList();
// -->X
allInstruments.add(new Guitar());
allInstruments.add(new Violin());
}
}
interface Instrument {
public void play();
}
class Guitar implements Instrument {
public void play(){
System.out.println("Playing Guitar.");
}
}
class Violin implements Instrument {
public void play(){
System.out.println("Playing Violin.");
}
}
1. The program will not compile.
2. The program will compile but will throw run-time exception.
3. The statement 'X' manifests that objects of type Instrument as well as sub-types can be
added to the list 'allInstruments'.
4. It is not possible to add any type of objects to the list 'allInstruments'.
5. The only possible element that can be added to the list 'allInstruments' is 'null'.

Answers
1) 1,5.
The declaration 'allInstruments' manifests a list, whose reference can point to a similar
declaration of list holding Instrument objects or sub-class of Instrument objects. It is not
possible to add elements into the list 'allInstruments'. The only permissible allowed type is
'null'.
2) What will be the output of the following program?
package enums;
public enum Color {
RED("Red Color"),
GREEN("Blue Color"),
BLUE("Blue Color");
private String displayName;
Color(String displayName){
this.displayName = displayName;
}
public String toString(){
return displayName;
}
}
class ColorTest{
public static void main(String[] args) {
Color redColor = Color.RED;
System.out.println(redColor);
Color blueColor = Color.BLUE;
System.out.println(blueColor);
}
}
1. The program will compile and the output will be 'Red Color' followed by 'Blue Color'.
2. The program will compile and throw a run-time exception.
3. The program won't compile as it is not possible to define methods within an Enum.
Answer
2)1
The above program defines a Enum called Color and the Enum constants within are
parameterized by defining a constructor for holding the display name of each constants. The
method toString() is defined at the declaration level which means that when an Enum object
is printed, this method will get called.

3) What will be the output of the following program?
package var_arg;
public class VarArgTest1 {
public static void main(String[] args) {
acceptMultipleArguments(1);
acceptMultipleArguments(1, 2);
}
static void acceptMultipleArguments(var_arg int nums){
System.out.println(nums.length);
}
}
1. The program will compile to produce the output 1 2.
2. The program will not compile
3. The program will compile but throw a run-time exception.
4. The program will output 1 1.
Answer
3) 2
The program won't compile as there is no keyword called 'var_arg' in Java
4) Imagine that you have directory called test1 in C drive containing some files,
within which there is a directory called test2 (sub-directory of test1) containing
some other set of files. Considering this, what statements are true about the
following program?

package io;
import java.io.File;
import java.io.FileFilter;
public class DirLister {
public static void main(String[] args) {
String path = "C:\\test1";
list(path);
}
static void list(String path){
File fileObject = new File(path);
if (fileObject.exists()){
if (fileObject.isDirectory()){
System.out.println("Dir-->" + fileObject.getAbsolutePath());
File allFiles[] = fileObject.listFiles(new MyFileLister());
for (File aFile : allFiles){
list(aFile.getAbsolutePath());
}
}else{
System.out.println("File-->" + fileObject.getAbsolutePath());
}
}
}
}
class MyFileLister implements FileFilter{
@Override
public boolean accept(File pathname) {
return pathname.getAbsolutePath().endsWith(".bmp");
}
}
1. The program will list down all the files within the directory test1 and test2
2. The program will list down only the files in directory test1
3. The program will list down only the files in directory test2
4. The program will run infinitely.
Answer
4)1
The program recursively traverses over the directories and the files. Hence answer 1 holds
good.
5) What will be the output of the following program?
package wrapper_boxing;
public class WrapperTest2 {
public static void main(String[] args) {
Boolean bool1 = new Boolean(true);
Boolean bool2 = new Boolean(false);
Boolean bool3 = new Boolean("false");
Boolean bool4 = new Boolean(bool1);
System.out.println(bool1.equals(bool4));
System.out.println(bool2 == bool3);
System.out.println(bool1 == bool4);
}
}
1. The program will not compile because the creation of bool4 object will cause
compilation error.
2. The program will produce the output 'true false false'.
3. The program will produce the output 'true true true'.
4. The program will output 'true false true'.
Answer
5)2
The first comparison statement compares the value of two objects and hence will return
true. Whereas the second and the third comparison verfires whether the references are
pointing to the same object, in which case both the comparisons will fail.
6) What will be the output of the following program?
package misc_apis;
import java.util.Scanner;
public class ScannerTest3 {
public static void main(String[] args) {
Scanner scanner = new Scanner("hello 1 2.00 false");
scanner.useDelimiter(" ");
String str = scanner.next();
int anInt = scanner.nextInt();
float aFloat = scanner.nextFloat();
boolean booleanValue = scanner.nextBoolean();
System.out.println(str + ":" + anInt + ":" + aFloat + ":" + booleanValue);
}
}
1. The program will output 'hello:1:2.0:false'
2. The program will throw Input Mismatch exception at the run-time
3. The program will output nothing.
4. The program will ouput ':1:2.0:false'
Answer
6) 1
The output will be 'hello:1:2.0:false'.
7) Which of the following statements are true about the new enhanced for loop?
1. The enhanced for loop eliminates the need for Iterator objects.
2. The enhanced for loop simplifies the process of iterating over a collection of
elements
3. The introduction of enhanced for loop will bring performance bottle-necks in an
Application
4. It is not possible to mix the older for loops as well as enhanced for loop in java
source code of version 5.0
Answer
7)1,2
The program recursively traverses over the directories and the files. Hence answer 1 holds
good.

8)Assume that in the current directory test.txt file is already exist. What will
happen when you execute the following code?

import java.io.*;
class Test
{
public static void main(String args[])
{
try
{
File file = new File("test.txt");
file.createNewFile();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
a)text.txt will be created and overwrite the old file
b)file will not be created
c)exception will be thrown
d)none of the above.
Answer
8)c)file will not be created.
New file cannot be created,when the File object refers to an actual file name that already
exists in the file system
9)What is the output of the following program?
public class Gen
{
G g;
Gen(G g)
{
this.g =g;
}
public static void main(String[] args)
{
Gen arr[] = new Gen[5]; //line 1
arr[0] = new Gen("Java"); //line 2
arr[1] = new Gen(1); //line 3
arr[2] = (Gen)new Gen(1); //line 4
arr[3] = (Gen)new Gen(1); //line 5
for(Gen o:arr)
{
System.out.println(o);
}
}
}
a)Compile time Error at line 1
b)Compile time Error at line 3
c)Compile time Error at line 4
d)Compile time Error at line 5
e)Run Time Error

Answer
9) d.
We can cast raw type to specific type but we cannot type cast Integer type to String type

10) what is the output of compiling an running the following code?
import java.util.*;
class CheckTest {
public static void main(String [] args) {
Hashtable ht = new Hashtable();
ht.put("chec", "check");
ht.put(1000, "check"); // line 1
ht.put("check", 20.01); // line 2
System.out.print(ht.get("chec") + " ");
System.out.print(ht.get(1000) + " "); //line 3
System.out.print(ht.get("check")); //line 4
}
}
a) Compilation fails due to error at line 1,2,3,4
b) Compilation fails due to error at line 3,4
c) Compiles fine and exception is thrown at runtime.
d) Compiles fine and prints "check check 20.01"
e) Compilation fails due to error at line 1,2
Answers

10)d
d is the correct answer because even Hashtable reference is created with Generic type the
reference is stored in non-generic variable. So it act as an old collection.

What is a Package & Define it?

A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Module. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.

* A package provides a unique namespace for the types it contains.
* Classes in the same package can access each others package-access members.

Define a Package.
  • Package pkg;[here pkg is the name of package ]
Define multilevel Package 
  • Package pkg1[.pkg2[.pkg3[.pkg4]]];   
Package Declaration

This keyword is usually the first keyword in source file.

package java.awt.event;

To use a package's classes inside a Java source file, it is convenient to import the classes from the package with an import statement.
import java.awt.event.*;

imports all classes from the java.awt.event package, while the next statement
import java.awt.event.ActionEvent;

imports only the ActionEvent class from the package.
ActionEvent myEvent = new ActionEvent();

Classes can also be used directly without an import statement by using the fully-qualified name of the class.
java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent();

Saturday, May 1, 2010

Types of operators in Java?

There are several types of operators, but before we go into them, you should understand a little thing we in the biz call operator precedence. Precedence determines in which order operators execute.

Operator Type
Operator Precedence
postfix
expr++ expr--
unary
++expr –expr +expr -expr ~ !
multiplicative
* / %
additive
+ -
shift
<< >> >>>
relational
< > <= >= instanceof
equality
“==” !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
logical AND
&&
logical OR
||
ternary
? :
assignment
“=” += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Tips

  • The Default value of uninitialized int variable is Zero.
  • Border layout or grid layout affected by the frame size this case with not apply flow layout.
  • When a class is properly encapsulated it is possible to change the class  implementation with out chnge it interface.
  • Implementation change do not affect other class which aside by this interface.
  • The Abstract Keywords must precede the method return type.
  • A Java package is a naming context for classes and & Interface.
  • A compilation unit is a java source code file.
  • Package name or statement appear as the first line in a source code file.
  • java.lang package is always imported by default.return type of a main method is void
  • argument of main method is always string type.