Java quiz 1


Ques 1 : Which declaration of the main method below would allow a class to be started as a standalone program.


(A) public static int main(char args[])


(B) public static void main(String args[])


(C) public static void MAIN(String args[])


(D) public static void main(String args)


Answer : public static void main(String args[])

Ques 2 : What is the meaning of the return data type void?


(A) An empty memory space is returned so that the developers can utilize it.


(B) void is not supported in Java


(C) void returns no data type.


(D) null


Answer : void returns no data type.

Ques 3 : Which of these are legal identifiers.


(A) number_1


(B) number_a


(C) $1234


(D) All of the above.


Answer : All of the above.

Ques 4 : Which of the following are Java keywords?


(A) throw


(B) void


(C) private


(D) All of the above.


Answer : All of the above.

Ques 5 : A lower precision can be assigned to a higher precision value in Java. For example a byte type data can be assigned to int type.


(A) True


(B) False


Answer : True

Ques 6 : Which of these are not legal identifiers.


(A) 1alpha


(B) xy+abc


(C) both A and B


(D) None of the above


Answer : both A and B

Ques 7 : Which of the following are legal definitions of the main method that can be used to execute a class.


(A) public static int main(String args[])


(B) public void main(String args)


(C) public static void main(String args[])


(D) public static void main(string args[])


Answer : public static void main(String args[])

Ques 8 : Which of the following statements about the Java language is true?


(A) Both procedural and OOP are supported in Java.


(B) Java supports only procedural approach towards programming.


(C) Java supports only OOP approach.


(D) None of the above.


Answer : Both procedural and OOP are supported in Java.

Ques 9 : Which of the following are keywords in Java.


(A) implement


(B) friend


(C) NULL


(D) synchronized


Answer : synchronized

Ques 10 : Which of these are legal array declarations or definitions?


(A) int[] []x[];


(B) int x[5];


(C) int *x;


(D) None of above


Answer : int[] []x[];

Ques 11 : What gets printed when the following code is compiled and run with the following command - java test 2 Select the one correct answer.






public class test {


public static void main(String args[]) {


Integer intObj=Integer.valueOf(args[args.length-1]);


int i = intObj.intValue();






if(args.length > 1)


System.out.println(i);


if(args.length > 0)


System.out.println(i - 1);


else


System.out.println(i - 2);


}


}









(A) test


(B) test -1


(C) 0


(D) 1


Answer : 1


Description :Note that the program gets one command line argument - 2. args.length will get set to 1. So the condition if(args.length > 1) will fail, and the second check if(args.length > 0) will return true.

Ques 12 : Which of the following statements is false about objects?


(A) An instance of a class is an object


(B) Objects can access both static and instance data


(C) Objects do not permit encapsulation


(D) Object is the super class of all other classes


Answer : Objects do not permit encapsulation

Ques 13 : Which of these are legal identifiers. Select the three correct answers.


a. number_1


b. number_a


c. $1234


d. -volatile



(A) a, b, c


(B) a, b


(C) a


(D) b


Answer : a, b, c

Ques 14 : The class Hashtable is used to implement which collection interface. Select the one correct answer.


(A) List


(B) Set


(C) Map


(D) SortedSet


Answer : Map


Description :


The collection interface Map has two implementation HashMap and Hashtable.







Ques 15 : TreeMap class is used to implement which collection interface. Select the one correct answer.


(A) Set


(B) SortedSet


(C) Tree


(D) SortedMap


Answer : SortedMap

Ques 16 : Given a one dimensional array arr, what is the correct way of getting the number of elements in arr. Select the one correct answer.


(A) arr.length


(B) arr.length - 1


(C) arr.size


(D) arr.length()


Answer : arr.length

Ques 17 : What happens when the following code is compiled and run. Select the one correct answer.






for(int i = 1; i < 3; i++)


for(int j = 3; j > i; j--)


assert i!=j {System.out.println(i); }



(A) The class compiles and runs, but does not print anything.


(B) The number 1 gets printed with AssertionError


(C) The program generates a compilation error.


(D) The number 2 gets printed with AssertionError


Answer : The program generates a compilation error.


Description :The condition in assert statement must be followed by a semi-colon.

Ques 18 : What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.





protected class example {


public static void main(String args[]) {


String test = "abc";


test = test + test;


System.out.println(test);


}


}



(A) The class does not compile because the top level class cannot be protected.


(B) The program prints "abc"


(C) The program prints "abcabc"


(D) The program does not compile because statement "test = test + test" is illegal.


Answer : The class does not compile because the top level class cannot be protected.

Ques 19 : In the following class definition, which is the first line (if any) that causes a compilation error. Select the one correct answer.





public class test {


public static void main(String args[]) {


char c;


int i;


c = 'A'; // 1


i = c; //2


c = i + 1; //3


c++; //4


}


}



(A) The line labeled 1.


(B) The line labeled 2.


(C) The line labeled 3.


(D) All the lines are correct and the program compiles.


Answer : The line labeled 3.


Description :It is not possible to assign an integer to a character in this case without a cast.

Ques 20 : Which of the following is a Java keyword. Select the four correct answers.


a. extern


b. synchronized


c. volatile


d. friend


e. friendly


f. transient


g. this


h. then



(A) b, c


(B) b, c, f, g


(C) e, g, h


(D) all of above.


Answer : b, c, f, g

Area of a Parallelogram-Hacker Rank Problem.

You are given a class Solution with a main method. Your task is to complete the given code so that it outputs the area of a parallelogram with breadth  and height . You should read the variables from standard input.
If  or  , the output should be "java.lang.Exception: Breadth and height must be positive" without quotes.
Input Format
Two lines of input. First line contains : breadth of parallelogram. Next line contains : height of parallelogram.
Constraints 
 
Output Format
If both values are greater than zero, then the main method must output the area of the parallelogram; else, print "java.lang.Exception: Breadth and height must be positive" without quotes.
Sample input 1
1
3
Sample output 1
3
Sample input 2
-1
2
Sample output 2
java.lang.Exception: Breadth and height must be positive
Solution :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
//Write your code here
static boolean flag=false;
static int B,H;
static{
 Scanner in= new Scanner(System.in);
 B=in.nextInt();
 H=in.nextInt();
 try{
  if(B<=0||H<=0)
   throw new Exception("Breadth and height must be positive");
  else{
   flag= true;
  }
 }
 catch(Exception e){
  System.out.println(e);
 }
}                                                                   public static void main(String[] args){
  if(flag){
   int area=B*H;
   System.out.print(area);
  }
  
 }//end of main

}//end of class

Print The Array-Hacker Rank Problem.

Let's say you have an integer array and a string array. You have to write a SINGLE method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays.
You are given code in the editor. You have to complete it so that it prints the following lines:
1
2
3
Hello
World
You should not use method overloading (your answer will not get accepted).
Solution 1: For printArray method :

import java.io.IOException;
import java.lang.reflect.Method;
class Printe
{
//Write your code here
class Printer
{
//Write your code here
public void printArray(Object[] ar){
for(int i=0;i<ar.length;i++){
System.out.println(ar[i].toString());
}
}
}
}

Solution 2 : For printArray Method :
import java.io.IOException;
import java.lang.reflect.Method;

class Printer
{
//Write your code here
class Printer
{
//Write your code here
public void printArray(Object[] ar){
for(Object obj: ar){
if(obj instanceof String || obj instanceof Integer){
System.out.println(obj.toString());
}

                    }
}


}


}

// Already Provided code by them for testing printArray Method.

public class Solution
{
    

    public static void main( String args[] )
    {
        Printer myPrinter=new Printer();
        Integer[] intArray = { 1, 2, 3 };
        String[] stringArray = {"Hello","World"};
        myPrinter.printArray( intArray  );
        myPrinter.printArray( stringArray );
        int count=0;
      for (Method method : Printer.class.getDeclaredMethods()) {
            String name = method.getName();
            if(name.equals("printArray"))
              count++;
        }
        
        if(count>1)System.out.println("Method overloading is not allowed!");
        assert count==1;

    } 
}






Weird Numbers solution HackerRank

Given an integer  as input, can you check the following:
  • If  is odd then print "Weird"
  • If  is even and, in between range 2 and 5(inclusive), print "Not Weird"
  • If  is even and, in between range 6 and 20(inclusive), print "Weird"
  • If  is even and , print "Not Weird"
Input Format
Single line of input: integer .
Constraints
Output Format
Print "Weird" if the number is weird; else, not "Not Weird" without the quotes.
Sample Input 1
3
Sample Output 1
Weird
Sample Input 2
24
Sample Output 2
Not Weird
Solution:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

 public static void main(String[] args) {
  /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
  Scanner in = new Scanner(System.in);
  int i = in.nextInt();
  if(i>=1&&i<=100){// Checking condition of 1<=N<=100
   if(!(i%2==0))//Checking if N is odd printing Weird.
   {
    System.out.println("Weird");
   }
   else if(i%2==0){
    if((i>=2&&i<=5)||i>20)
     System.out.println("Not Weird");
    if(i>=6&&i<=20)
     System.out.println("Weird");
   }
  }
 }    
}

Java Collections Interview questions

Java Collections Interview questions
  1. Java Collection hierarchy ?

  2. What is the difference between ArrayList and LinkedList ?

    Array ListLinked List
    ArrayList uses a dynamic array.LinkedList uses doubly linked list.
    ArrayList is not efficient for manipulation because a lot of shifting is required.LinkedList is efficient for manipulation.
    ArrayList is better to store and fetch data.LinkedList is better to manipulate data.

  3. What is the difference between List and Set?

    List can contain duplicate elements whereas Set contains only unique elements.

  4. What is the difference between ArrayList and Vector ?

    Array ListVector
    ArrayList is not synchronized. Vector is synchronized.
    ArrayList is not a legacy class.Vector is a legacy class.
    ArrayList increases its size by 50% of the array size.Vector increases its size by doubling the array size.

  5. What is the difference between Iterator and ListIterator ?

    IteratorListIterator
    Iterator traverses the elements in forward direction only.ListIterator traverses the elements in backward and forward directions both.
    Iterator can be used in List, Set and Queue.LinkedList is efficient for manipulation.
    ArrayList is better to store and fetch data.ListIterator can be used in List only.

  6. What is the difference between HashSet and TreeSet?

    HashSet maintains no order whereas TreeSet maintains ascending order.

  7. What is the difference between Iterator and Enumeration ?

    IteratorEnumeration
    Iterator can traverse legacy and non-legacy elements.Enumeration can traverse only legacy elements.
    Iterator is fail-fast.Enumeration is not fail-fast.
    Iterator is slower than Enumeration.Enumeration is faster than Iterator.

  8. What is the difference between Set and Map ?

    Set contains values only whereas Map contains key and values both.

  9. What is the difference between HashMap and Hashtable ?

    HashMapHashtable
    HashMap is not synchronized.Hashtable is synchronized.
    Iterator is fail-fast.Enumeration is not fail-fast.
    HashMap can contain one null key and multiple null values.Hashtable cannot contain any null key or null value.

  10. What is the difference between HashSet and HashMap?

    HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.

  11. What is the difference between Comparable and Comparator ?

    ComparableComparator
    Comparable provides only one sort of sequence.Comparator provides multiple sort of sequences.
    It provides one method named compareTo().It provides one method named compare().
    It is found in java.lang package.it is found in java.util package.
    If we implement Comparable interface, actual class is modified.Actual class is not modified.

  12. What is the difference between HashMap and TreeMap?

    HashMap maintains no order but TreeMap maintains ascending order.

  13. What is the difference between Collection and Collections?

    Collection is an interface whereas Collections is a class.
    Collection interface provides normal functionality of data structure to List, Set and Queue.
    But, Collections class is to sort and synchronize collection elements.

  14. What is the advantage of Properties file?

    If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

  15. What does the hashCode() method?

    The hashCode() method returns a hash code value (an integer number).
    The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.
    But, it is possible that two hash code numbers can have different or same keys.

  16. Why we override equals() method?

    The equals method is used to check whether two objects are same or not.
    It needs to be overridden if we want to check the objects based on property.

    For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.


  17. What is the advantage of generic collection?

    If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

  18. What is hash-collision in Hashtable and how it is handled in Java?

    Two different keys with the same hash value is known as hash-collision.
    Two different entries will be kept in a single hash bucket to avoid the collision.

  19. What is the Dictionary class?

    The Dictionary class provides the capability to store key-value pairs.

  20. What is the default size of load factor in hashing based collection?

    The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor.
    For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

  21. How to synchronize List, Set and Map elements?

    Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
    • public static List synchronizedList(List l){}
    • public static Set synchronizedSet(Set s){}
    • public static SortedSet synchronizedSortedSet(SortedSet s){}
    • public static Map synchronizedMap(Map m){}
    • public static SortedMap synchronizedSortedMap(SortedMap m){}





Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...