Core Java -----Question and Answers


Q1. What is the output for the below code ?


public class Test{
    int _$;
    int $7;
    int do;
public static void main(String argv[]){
  
  
Test test = new Test();
test.$7=7;
test.do=9;
  
System.out.println(test.$7);
System.out.println(test.do);
System.out.println(test._$);
  
}
} 1 7 9 0
2 7 0 0
3 Compile error - $7 is not valid identifier.
4 Compile error - do is not valid identifier. You have choosen : 4
Correct Answer is : 4
You were correct. Explanations : $7 is valid identifier. Identifiers must start with a letter, a currency character ($), or underscore ( _ ). Identifiers cannot start with a number. You can't use a Java keyword as an identifier. do is a Java keyword.





Q2. What is the output for the below code ?

public class B {  
    public static synchronized void printName(){
        try{
             System.out.println("printName");
                Thread.sleep(5*1000);
          
            }catch(InterruptedException e){              
            }
    }
  
    public synchronized void printValue(){      
             System.out.println("printValue");              
    }
}



public class Test extends Thread{
    B b = new B();
public static void main(String argv[]) throws Exception{
Test t = new Test();
Thread t1 = new Thread(t,"t1");
Thread t2 = new Thread(t,"t2");
t1.start();
t2.start();
}

public void run(){   
    if(Thread.currentThread().getName().equals("t1")){
        b.printName();
    }else{
        b.printValue();
    }   
}

}
1 print : printName , then wait for 5 seconds then print : printValue
2 print : printName then print : printValue
3 print : printName then wait for 5 minutes then print : printValue
4 Compilation succeed but Runtime Exception
You have choosen : 2
Correct Answer is : 2
You were correct.


Explanations : There is only one lock per object, if one thread has picked up the lock, no other thread can pick up the lock until the first thread releases the lock. In this case printName() is static , So lock is in class B not instance b, both method (one static and other no-static) can run simultaneously. A static synchronized method and a non static synchronized method will not block each other.








Q3. What is the output for the below code ?

public class D {
    int i;
    int j;
    public D(int i,int j){
        this.i=i;
        this.j=j;
    }
  
    public void printName() {
        System.out.println("Name-D");
    }  

}

1. public class Test{  
2.    public static void main (String[] args){
3.        D d = new D();
4.        d.printName();
5.      
6.    }
7. }
1 Name-D
2 Compilation fails due to an error on lines 3
3 Compilation fails due to an error on lines 4
4 Compilation succeed but no output

Correct Answer is : 2





Explanations : Since there is already a constructor in this class (public D(int i,int j)), the compiler won't supply a default constructor. If you want a no-argument constructor to overload the with-arguments version you already have, you have to define it by yourself. The constructor D() is undefined in class D. If you define explicit constructor then default constructor will not be available. You have to define explicitly like public D(){ } then the above code will work. If no constructor into your class , a default constructor will be automatically generated by the compiler.


Q4. What is the output for the below code ?

public class A {  
    public A(){
        System.out.println("A");
    }
    public A(int i){
        this();
        System.out.println(i);
    }
}


public class B extends A{      
    public B (){
        System.out.println("B");
    }
    public B (int i){
        this();
        System.out.println(i+3);
    }
}


public class Test{
  
    public static void main (String[] args){
        new B(5);
    }
} 1 A B 8
2 A 5 B 8
3 A B 5
4 B 8 A 5
You have choosen : 1
Correct Answer is : 1
You were correct. Explanations : Constructor of class B call their superclass constructor of class A (public A()) , which execute first, and that constructors can be overloaded. Then come to constructor of class B (public B (int i)).

Q5. What is the output for the bellow code?

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;


public class Test {
    public static void main(String... args) {

        Set s = new TreeSet();
         s.add("7");
         s.add(9);        
         Iterator itr = s.iterator();
         while (itr.hasNext())
         System.out.print(itr.next() + " ");

      
      
    }

}
1 Compile error
2 Runtime Exception
3 7 9
4 None of the above
Correct Answer is : 2

Explanation:
Treeset allows similar type of objects only. So Runtime exception will occurs.






Q6. If we do

ArrayList lst = new ArrayList();

What is the initial capacity of the ArrayList lst ?
1 10
2 8
3 15
4 12
You have choosen : 1
Correct Answer is : 1
You were correct.


Explanations : /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); }



Q7. What is the output for the below code ?

public class A {
  
    public A(int i){
        System.out.println(i);
    }  
      
}

1. public class B extends A{      
2.    public B(){
3.        super(6);
4.        this();
5.    }  
6. }

public class Test{  
    public static void main (String[] args){
        B b = new B();      
    }
}
1 6
2 0
3 Compilation fails due to an error on lines 3
4 Compilation fails due to an error on lines 4
You have choosen : 4
Correct Answer is : 4
You were correct. Explanations : A constructor can NOT have both super() and this(). Because each of those calls must be the first statement in a constructor, you can NOT use both in the same constructor.

Q8. What is the output for the below code ?

interface A {
    public void printValue();
}

1. public class Test{  
2.    public static void main (String[] args){
3.        A a1 = new A() {      
4.            public void printValue(){
5.                System.out.println("A");
6.            }
7.            };
8.            a1.printValue();  
9.            }
10. }
1 Compilation fails due to an error on line 3
2 A
3 Compilation fails due to an error on line 8
4 null
You have choosen : 2
Correct Answer is : 2
You were correct. Explanations : The A a1 reference variable refers not to an instance of interface A, but to an instance of an anonymous (unnamed) class. So no compilation error.






Class A {
    A(String s) {
    }
    A() {
    }
}

1. class B extends A {
2.    B() { }
3.    B(String s) {
4.        super(s);
5.    }
6.    void test() {
7.        // insert code here
8.    }
9. }

Which of the below code can be insert at line 7 to make clean compilation ?
1 A a = new B();
2 A a = new B(5);
3 A a = new A(String s);
4 All of the above
You have choosen : 1
Correct Answer is : 1
You were correct.


Explanations : A a = new B(); is correct because anonymous inner classes are no different from any other class when it comes to polymorphism.


Q11. What is the output for the below code ?

1. public class Test {          
2.    public static void main(String... args) {
3.        int x =5;
4.        x *= 3 + 7;
5.        System.out.println(x);
6.    }
7. } 1 22 2 50 3 10 4 Compilation fails with an error at line 4 You have choosen : 2
Correct Answer is : 2
You were correct. Explanations : x *= 3 + 7; is same as x = x * (3 +7) = 5 * (10) = 50 because expression on the right is always placed inside parentheses.










Q13. class A {
    class A1 {
        void printValue(){
            System.out.println("A.A1");
        }
    }
}

1. public class Test{  
2.    public static void main (String[] args){
3.        A a = new A();
4.        // INSERT CODE
5.        a1.printValue();
6.    }
7. }

Which of the below code inserted at line 4, compile and produce the output "A.A1"?
1 A.A1 a1 = new A.A1();
2 A.A1 a1 = a.new A1();
3 A a1 = new A.A1();
4 All of the above
You have choosen : 2
Correct Answer is : 2
You were correct.


Explanations : correct inner class instantiation syntax is A a = new A(); A.A1 a1 = a.new A1();





Q14. What is the output for the below code ?


public class Test{
    int $7;
public static void main(String argv[]){
    int k;
    Test test = new Test();
    test.$7=7;
System.out.println(test.$7);
    System.out.println(k);
}
}
1 7 0
2 0 0
3 Compile error - $7 is not valid identifier.
4 Compile error - The local variable k may not have been initialized.
You have choosen : 4
Correct Answer is : 4
You were correct. Explanations : The local variable k may not have been initialized. Local variable must be initialized before use. $7 is valid identifier. Identifiers must start with a letter, a currency character ($), or underscore ( _ ). Identifiers cannot start with a number.








Q15. What is the output for the below code ?

public class Test {
  
    public static void printValue(int i, int j, int k){
        System.out.println("int");
    }
    public static void printValue(byte...b){
        System.out.println("long");
    }
  
    public static void main(String... args) {
        byte b = 9;
        printValue(b,b,b);
    }
}
1 long
2 int
3 Compilation fails
4 Compilation clean but throws RuntimeException
You have choosen : 2
Correct Answer is : 2
You were correct.


Explanations : Primitive widening uses the smallest method argument possible. (For Example if you pass short value to a method but method with short argument is not available then compiler choose method with int argument). But in this case compiler will prefer the older style before it chooses the newer style, to keep existing code more robust. var-args method is looser than widen.

Q16. HashMap can be synchronized by _______ ?
1 Map m = Collections.synchronizeMap(hashMap);
2 Map m = hashMap.synchronizeMap();
3 Map m = Collection.synchronizeMap(hashMap);
4 None of the above
You have choosen : 1
Correct Answer is : 1
You were correct. Explanations : HashMap can be synchronized by Map m = Collections.synchronizeMap(hashMap);

Q17. Which of the following are methods of the Thread class?

1) yield()
2) sleep(long msec)
3) go()
4) stop()
1 1 , 2 and 4
2 1 and 3
3 3 only
4 None of the above
You have choosen : 1
Correct Answer is : 1
You were correct. Explanations : Check out the Java2 Docs for an explanation

Q18. What is the output for the below code ?

import java.io.FileNotFoundException;

public class A {  
    public void printName() throws FileNotFoundException {
        System.out.println("Value-A");
    }      
}

public class B extends A{      
    public void printName() throws NullPointerException{
        System.out.println("Name-B");
    }  
}


public class Test{      
    public static void main (String[] args) throws Exception{
        A a = new B();
        a.printName();
    }
  
}
1 Value-A
2 Compilation fails-Exception NullPointerException is not compatible with throws clause in A.printName()
3 Name-B
4 Compilation succeed but no output
Correct Answer is : 3
Explanations : The overriding method can throw any unchecked (runtime) exception, regardless of exception thrown by overridden method. NullPointerException is RuntimeException so compiler not complain.






Q19. What is the output for the below code?
public class A {
    public A() {
System.out.println("A");
}
}

public class B extends A implements Serializable {
    public B() {
System.out.println("B");
}

}

public class Test {
  
    public static void main(String... args) throws Exception {
        B b = new B();

ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("datafile"));
save.writeObject(b);
save.flush();


ObjectInputStream restore = new ObjectInputStream(new FileInputStream("datafile"));
B z = (B) restore.readObject();



    }
  
}
1 A B A
2 A B A B
3 B B
4 B

Correct Answer is : 1





Explanations : On the time of deserialization , the Serializable object not create new object. So constructor of class B does not called. A is not Serializable object so constructor is called.




Q22. What is the output for the below code ?

class A implements Runnable{
    public void run(){
        System.out.println(Thread.currentThread().getName());
    }
}

1. public class Test {      
2.    public static void main(String... args) {  
3.        A a = new A();
4.        Thread t = new Thread(a);
5.        t.setName("good");
6.        t.start();
7.    }
8. }
1 good
2 null
3 Compilation fails with an error at line 5
4 Compilation succeed but Runtime Exception
You have choosen : 1
Correct Answer is : 1
You were correct. Explanations : Thread.currentThread().getName() return name of the current thread.






Q23. What is the output for the below code ?

class A implements Runnable{  
    public void run(){
        try{
        for(int i=0;i < 4;i++){
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName());
        }
        }catch(InterruptedException e){
          
        }
    }
}


public class Test {
public static void main(String argv[]) throws Exception{
A a = new A();
Thread t = new Thread(a,"A");
Thread t1 = new Thread(a,"B");
t.start();
t.join();
t1.start();
}
}
1 A A A A B B B B
2 A B A B A B A B
3 Output order is not guaranteed
4 Compilation succeed but Runtime Exception
You have choosen : 1
Correct Answer is : 1
You were correct.


Explanations : t.join(); means Threat t must finish before Thread t1 start.


Q24. Which of the following statements about this code are true?

class A extends Thread{  
    public void run(){
        for(int i =0; i < 2; i++){
            System.out.println(i);
        }  
    }
}


public class Test{
    public static void main(String argv[]){
        Test t = new Test();
        t.check(new A(){});  
    }
    public void check(A a){
        a.start();
        }

}
1 0 0
2 Compilation error, class A has no start method
3 0 1
4 Compilation succeed but runtime exception
Correct Answer is : 3
. Explanations : class A extends Thread means the anonymous instance that is passed to check() method has a start method which then calls the run method

Q25. What happens when the following code is compiled and run.
Select the one correct answer.

for(int i = 2; i < 4; i++)
for(int j = 2; j < 4; j++)
if(i < j)
assert i!=j : i;
1 The class compiles and runs, but does not print anything.
2 The number 2 gets printed with AssertionError
3 compile error
4 The number 3 gets printed with AssertionError
Correct Answer is : 1
Explanations : When if condition returns true, the assert statement also returns true. Hence AssertionError does not get generated. .


Q26. Which of the following statement is true about jar command?
1 The jar command creates the META-INF directory implicitly.
2 The jar command creates the MANIFEST.MF file implicitly.
3 The jar command would not place any of your files in META-INF directory.
4 All of the above are true You have choosen : 1
Correct Answer is : 1
You were correct.


Q27. What will be the result of compiling and run the following code:

public class Test {
  
    public static void main(String... args) throws Exception {
        Integer i = 34;
        int l = 34;
        if(i.equals(l)){
            System.out.println(true);
        }else{
            System.out.println(false);
        }

    }
  
}
1 true
2 false
3 Compile error
4 None of the above
You have choosen : 1
Correct Answer is : 1
You were correct. Explanations : equals() method for the integer wrappers will only return true if the two primitive types and the two values are equal.

Q28. What is the output ?

public class Test {
  
    public static void main(String... args) {

        Pattern p = Pattern.compile("a+b?c*");
        Matcher m = p.matcher("ab");
        boolean b = m.matches();
        System.out.println(b);

      

    }
}
1 true
2 false
3 Compile error
4 None of the above
Correct Answer is : 1
Explanations : X? X, once or not at all X* X, zero or more times X+ X, one or more times

Q29. What is the output for the below code ?

1. public class Test {
2. public static void main(String[] args){
3.    byte i = 128;
4.    System.out.println(i);
5.    }
6. }
1 128
2 0
3 Compilation fails with an error at line 3
4 Compilation fails with an error at line 4
You have choosen : 3
Correct Answer is : 3
You were correct. Explanations : byte can only hold up to 127. So compiler complain about possible loss of precision.

Q30. What is the output for the below code?

import java.util.Iterator;
import java.util.TreeSet;


public class Test {
    public static void main(String... args) {

        TreeSet s1 = new TreeSet();
        s1.add("one");
        s1.add("two");
        s1.add("three");
        s1.add("one");
      
         Iterator it = s1.iterator();
         while (it.hasNext() ) {
         System.out.print( it.next() + " " );
         }

      
      
    }

}
1 one three two 2 Runtime Exception 3 one three two one 4 one two three You have choosen : 1
Correct Answer is : 1
You were correct.


Q31. What is the output for the below code ?

public class A {
public void printValue(){
     System.out.println("A");
}
}

public class B extends A {
    public void printValue(){
         System.out.println("B");
     }
}

1. public class Test {      
2.    public static void main(String... args) {
3.        A b = new B();
4.        newValue(b);      
5.    }
6.    public static void newValue(A a){
7.        if(a instanceof B){
8.            ((B)a).printValue();
9.        }
10.    }
11. }
1 A
2 B
3 Compilation fails with an error at line 4
4 Compilation fails with an error at line 8
Correct Answer is : 2
Explanations : instanceof operator is used for object reference variables to check whether an object is of a particular type. In newValue(b); b is instance of B So works properly.

Q32. You have a java file name Test.java inside src folder of javaproject directory.
You have also classes folder inside javaproject directory.

you have issued below command from command prompt.

cd javaproject

Which of the below command puts Test.class file inside classes folder ?
1 javac -d classes src/Test.java
2 javac Test.java
3 javac src/Test.java
4 javac classes src/Test.java
You have choosen : 1
Correct Answer is : 1
You were correct. Explanations : The -d option lets you tell the compiler in which directory to put the .class file it generates (d for destination)

Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams