Tuesday, 31 March 2015

Assertion and For each loop in Java

Assertion:

Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose.

Advantage of Assertion:

It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:

There are two ways to use assertion. First way is:
1.    assert expression;  
and second way is:
1.    assert expression1 : expression2;  

Simple Example of Assertion in java:

1.    import java.util.Scanner;  
2.        
3.    class AssertionExample{  
4.     public static void main( String args[] ){  
5.      
6.      Scanner scanner = new Scanner( System.in );  
7.      System.out.print("Enter ur age ");  
8.        
9.      int value = scanner.nextInt();  
10.   assert value>=18:" Not valid";  
11.   
12.   System.out.println("value is "+value);  
13.  }   
14. }  


If you use assertion, It will not run simply because assertion is disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
Output: Enter ur age 11
        Exception in thread "main" java.lang.AssertionError: Not valid

Where not to use Assertion:

There are some situations where assertion should be avoid to use. They are:
  1. According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g. IllegalArgumentException, NullPointerException etc.
  2. Do not use assertion, if you don't want any error in any situation.


For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Advantage of for-each loop:

  • It makes the code more readable.
  • It elimnates the possibility of programming errors.

Syntax of for-each loop:

1.    for(data_type variable : array | collection){}  

Simple Example of for-each loop for traversing the array elements:

1.        
2.    class ForEachExample1{  
3.      public static void main(String args[]){  
4.       int arr[]={12,13,14,44};  
5.      
6.       for(int i:arr){  
7.         System.out.println(i);  
8.       }  
9.      
10.  }   
11. }  

      
Test it Now
Output:12
       13
       14
       44

Simple Example of for-each loop for traversing the collection elements:

1.    import java.util.*;  
2.    class ForEachExample2{  
3.      public static void main(String args[]){  
4.       ArrayList<String> list=new ArrayList<String>();  
5.       list.add("vimal");  
6.       list.add("sonoo");  
7.       list.add("ratan");  
8.      
9.       for(String s:list){  
10.      System.out.println(s);  
11.    }  
12.   
13.  }   
14. }  
     

Test it Now
Output:vimal
       sonoo
       ratan


JDBC Interview Questions

JDBC Interview Questions

A list of frequently asked jdbc interview questions with answers are given below.

1) What is JDBC?

JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connects to the database.

2) What is JDBC Driver?

JDBC Driver is a software component that enables java application to interact with the database.There are 4 types of JDBC drivers:
  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

3) What are the steps to connect to the database in java?

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

4) What are the JDBC API components?

The java.sql package contains interfaces and classes for JDBC API.
Interfaces:
  • Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • ResultSetMetaData
  • DatabaseMetaData
  • CallableStatement etc.
Classes:
  • DriverManager
  • Blob
  • Clob
  • Types
  • SQLException etc.

5) What are the JDBC statements?

There are 3 JDBC statements.
  1. Statement
  2. PreparedStatement
  3. CallableStatement

6) What is the difference between Statement and PreparedStatement interface?

In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.

7) How can we execute stored procedures and functions?

By using Callable statement interface, we can execute procedures and functions.

8) What is the role of JDBC DriverManager class?

The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

9) What does the JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

10) What does the JDBC ResultSet interface?

The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

11) What does the JDBC ResultSetMetaData interface?

The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

12) What does the JDBC DatabaseMetaData interface?

The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

13) Which interface is responsible for transaction management in JDBC?

The Connection interface provides methods for transaction management such as commit(), rollback() etc.

14) What is batch processing and how to perform batch processing in JDBC?

By using batch processing technique in JDBC, we can execute multiple queries. It makes the performance fast.

15) How can we store and retrieve images from the database?



By using PreparedStatement interface, we can store and retrieve images.

20 Java Collections Interview Questions

20 Java Collections Interview Questions

In java, collection interview questions are mostly asked by the interviewers. Here is the list of mostly asked collections interview questions with answers.

1) What is the difference between ArrayList and Vector?

No.
ArrayList
Vector
1)
ArrayList is not synchronized.
Vector is synchronized.
2)
ArrayList is not a legacy class.
Vector is a legacy class.
3)
ArrayList increases its size by 50% of the array size.
Vector increases its size by doubling the array size.

2) What is the difference between ArrayList and LinkedList?

No.
ArrayList
LinkedList
1)
ArrayList uses a dynamic array.
LinkedList uses doubly linked list.
2)
ArrayList is not efficient for manipulation because a lot of shifting is required.
LinkedList is efficient for manipulation.
3)
ArrayList is better to store and fetch data.
LinkedList is better to manipulate data.

3) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.
No.
Iterator
ListIterator
1)
Iterator traverses the elements in forward direction only.
ListIterator traverses the elements in backward and forward directions both.
2)
Iterator can be used in List, Set and Queue.
ListIterator can be used in List only.

4) What is the difference between Iterator and Enumeration?

No.
Iterator
Enumeration
1)
Iterator can traverse legacy and non-legacy elements.
Enumeration can traverse only legacy elements.
2)
Iterator is fail-fast.
Enumeration is not fail-fast.
3)
Iterator is slower than Enumeration.
Enumeration is faster than Iterator.

5) What is the difference between List and Set?

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

6) What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

7) What is the difference between Set and Map?

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

8) 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.

9) What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

10) What is the difference between HashMap and Hashtable?

No.
HashMap
Hashtable
1)
HashMap is not synchronized.
Hashtable is synchronized.
2)
HashMap can contain one null key and multiple null values.
Hashtable cannot contain any null key or null value.

11) 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.

12) What is the difference between Comparable and Comparator?

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

13) 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.

14) 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.

15) 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.

16) 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){}

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.

Java Multi threading Interview Questions

Java Multithreading Interview Questions

Multithreading and Synchronization is considered as the typical chapter in java programming. In game development company, mulithreading related interview questions are asked mostly. A list of frequently asked java multithreading interview questions are given below.

1) What is multithreading?

Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between process is low.

2) What is thread?

A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of execution because each thread runs in a separate stack frame.

3)What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

4) What does join() method?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

5) What is difference between wait() and sleep() method?

wait()
sleep()
1) The wait() method is defined in Object class.
The sleep() method is defined in Thread class.
2) wait() method releases the lock.
The sleep() method doesn't releases the lock.

6) Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If we does, it throws an exception.

7) Can we call the run() method instead of start()?

yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.

8) What about the daemon threads?

The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads.

9)Can we make the user thread as daemon thread if thread is started?

No, if you do so, it will throw IllegalThreadStateException

10)What is shutdown hook?

The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can use it perform clean up resource.

11)When should we interrupt a thread?

We should interrupt a thread if we want to break out the sleep or wait state of a thread.

12) What is synchronization?

Synchronization is the capabilility of control the access of multiple threads to any shared resource.It is used:

  1. To prevent thread interference.
  2. To prevent consistency problem.

13) What is the purpose of Synchronized block?

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.

14)Can Java object be locked down for exclusive use by a given thread?

Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

15) What is static synchronization?

If you make any static method as synchronized, the lock will be on the class not on object.

16)What is the difference between notify() and notifyAll()?

The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

17)What is deadlock?



Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...