Showing posts with label java interviews. Show all posts
Showing posts with label java interviews. Show all posts

Thursday 29 August 2013

Top Most Java 1.7 features



'Java latest changes' or' 'Java 1.7 changes' are covered in this topic. Java 1.7 [ Dolphin] is major update after java 1.5 tiger release. It is done on 2011-07-28 after around 5 years of java release 1.6 [Mustang]. These are major changes in java 1.7 release and most important is definitely 'Auto closeable' of resources.

1) Autocloseable Try Statement defining Resources – Java 1.7 introduces all new try-with-resources statement using which declaration and initialization of one or more resources can happen. But only the resources that implement the interface “java.lang.AutoCloseable” can be declared. Example:
      try (BufferedReader bufferedReader = new BufferedReader( FileReader(path)))
         {             return bufferedReader.readLine();  
         }
  In this code snippet, sampleBufferedReader instance is created within the try statement. Note that the example does not include a finally block that contains a code to close sampleBufferedReader as in Java 1.6 or earlier versions. Java 1.7 automatically closes the resources that are instantiated within the try-with-resources statement as shown above.

2) Catch Block Handling Multiple Exceptions – In Java 1.5 and Java 1.6, a catch block can handle only one type of exception. But in Java 1.7 and later versions, a single catch block can handle multiple exceptions. Here is an example showing catch blocks in Java 1.6:
     try {    }
      catch(SQLException exp1)
      {     throw exp1;    }
       catch(IOException exp2)
       {    throw exp2;   }
The same code snippet can be modified in Java 1.7 as:
      try  {….      }
      catch(SQLException | IOException |ArrayIndexOutofBoundsException exp1)
      {     throw exp1;   }

3) String Object as Expression in Switch Statement – So far only integral types are used as expressions in switch statement. But Java 1.7 permits usage of String object as a valid expression. Example:
   example:           
                            case "CASE1":
                                     System.out.println(“CASE1”);
                                     break;

4) JDBC in Java 1.7
JDBC contained in Java 1.7 / Java SE 7 is JDBC 4.1 that is newly getting introduced. JDBC 4.1 is more efficient when compared to JDBC 4.0.

5) Language Enhancements in JDBC 1.7
Java 1.7 introduces many language enhancements:

  Integral Types as Binary Literals – In Java 1.7 / Java SE 7, the integral types namely byte, short, int and long can also be expressed with the binary number system. To specify these integral types as binary literals, add the prefix 0B or 0b to number. For example, here is a byte literal represented as 8-bit binary number:
     byte sampleByte = (byte)0b01001101;
   
  Underscores Between Digits in Numeric Literal – In Java 1.7 and all later versions, “_” can be used in-between digits in any numeric literal. “_” can be used to group the digits similar to what “,” does when a bigger number is specified. But “_” can be specified only between digits and not in the beginning or end of the number. Example:
long NUMBER = 444_67_3459L;
In this example, the switch expression contains a string called sampleString.  The value of this string is matched with every case label and when the string content matches with case label then the corresponding case gets executed. 

  Automatic Type Inference during the Generic Instance Creation – In Java 1.7 while creating a generic instance, empty parameters namely <> can be specified instead of specifying the exact type arguments. However, this is permitted only in cases where the compiler can infer the appropriate type arguments. For example, in Java 1.7 you can specify:
      sampleMap = new HashMap<>();
Thus HashMap<> can be specified instead of HashMap>;. This <>; empty parameters of Java 1.7 are named as diamond operator.

6) Suppress Warnings - When declaring varargs method that includes parameterized types, if the body of the varargs method does not throw any exceptions like ClassCastException (which occurs due to improper handling of the varargs formal parameter) then the warnings can be suppressed in Java 1.7 by three different ways: 
(1) Add annotation @SafeVarargs to static method declarations and non constructor method declarations 
(2) Add annotation @SuppressWarnings({"unchecked", "varargs"}) to varargs method declaration 
(3) Directly use compiler option “-Xlint:varargs.
By suppressing the warnings in varargs method, occurrence of unchecked warnings can be prevented at compile time thus preventing Heap Pollution.

7) Java Virtual Machine Enhancements in Java 1.7
Java SE 7 / Java 1.7 newly introduce a JVM instruction called “invokedynamic” instruction.  Using “invokedynamic” instruction, the dynamic types programming language implementation becomes simpler. Thus Java 1.7 enables JVM support for the non-java languages.  


Monday 19 August 2013

Top Most Java Producer and Consumer Implementation using Blocking Queue

'Java Consumer Producer' example - This is one of frequently asked questions to senior core java developer. Java concurrency producer and consumer solution is demonstrated below. 
Java Concurrency Queuing options:
 The java concurrent executors and task holding queues can be configured in three ways-
Direct handoffs :  A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.

Unbounded queues : Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.

Bounded queues : A bounded queue (for example, an ArrayBlockingQueue) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may be traded off for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.

   Example of PriorityBlockingQueue and see how the comparable is used with priority of task which depends on implementation of compare method in task.
From Java Docs-

The Blocking queue here is bounded with 11 as initial capacity as default constructor.  The queue is based on priority and least priority data is processed 

" An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError). This class does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityBlockingQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). Also, methoddrainTo can be used to remove some or all elements in priority order and place them in another collection."




Output
 Consumed Data [number=2, name=two]
 producer 0
 Consumed Data [number=10, name=ten]
 producer 1
 Consumed Data [number=20, name=twenty]
 producer 2
 Consumed Data [number=0, name=0]
 producer 3
 Consumed Data [number=1, name=1]
 producer 4
 Consumed Data [number=2, name=2]
 producer 5
 Consumed Data [number=3, name=3]


Consumer Producer Solution with Synchronisation:
This implementation with Synchronisation needs great care and it is more complicated in implementation:


Output 
The output will confim that there is no concurrency issue on putting data into same queue and wait() and notify() works perfectly fine.
 Got: 53613
 Put: 53614
 Got: 53614
 Put: 53615
 Got: 53615
 Put: 53616
 Got: 53616
 Put: 53617
 Got: 53617

Sunday 18 August 2013

Top Most Design Pattern in Java : Part 1

'Java investment bank interview' generally contains 'Java Design Pattern' questions. If you want to be a professional Java developer, you should know popular solutions for common\standard coding problems. Such solutions have been proved efficient and effective and always used by experienced developers. These solutions are described as so-called design patterns. Learning design patterns speeds up your experience accumulation in OOA/OOD. Once you grasped them, you would be benefit from them for all your life and jump up yourselves to be a master of designing and developing. Furthermore, you will be able to use these terms to communicate with your fellows more effectively.

Many programmers with many years experience don't know design patterns, but as an Object-Oriented programmer, you have to know them well, especially for new Java programmers. Actually, when you solved a coding problem, you have used a design pattern. 


        You may not use a popular name to describe it or may not choose an effective way to better intellectually control over what you built. Learning how the experienced developers to solve the coding problems and trying to use them in your project are a best way to earn your experience. We have mainly 3 type of design pattern and they are Creational, Structural and Behavioural.

There are frequently asked question in design pattern, and these were asked to me in java interviews:

1) Explain Singleton Design pattern and How to solve Double Check locking?
2) What is Abstract Factory Pattern?
3) What is Adapter pattern?
4) What is Decorator Design Pattern?
5) Where we should use Facade in application?
6) What is Proxy and Composite?
7) What is Observer Pattern? 
Creational Patterns
Factory:
The factory pattern \ factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."[1]
Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

The factory pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects. 
Example : Static factory method provided with Collections class like 
Collections.synchronizedMap( new HashMap()); 

Abstract Factory:
The abstract factory pattern is a software creational design pattern that provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.
An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() andcreateResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects).

Example : The best example will be configuring Database connection factory which hide underline Database type. We can configure Oracle, DB2 or Sybase Connection Factory in application.
    > java.util.Calendar#getInstance()
    > java.util.ResourceBundle#getBundle()
    > java.text.NumberFormat#getInstance()

Singleton:
The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
In the second edition of his book Effective JavaJoshua Bloch claims that "a single-element enum type is the best way to implement a singleton" for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
 Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). More details on Singleton Pattern.
Example: Getting Runtime environment using Runtime class is example of Singleton design pattern -- java.lang.Runtime#getRuntime()

Builder:
The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects. Often, the builder pattern is used to build products in accordance with the composite pattern.The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.

Builder
Abstract interface for creating objects (product).
Concrete Builder
     Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.
Example : Builder pattern is frequently used in Java classes where We need special purpose classes like StingBuilder and StringBuffer.
    > java.lang.StringBuilder#append() 
    > java.lang.StringBuffer#append() 
    > java.nio.ByteBuffer#put()


Prototype:
The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
  • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.
The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.
Example: Best example will be Java.lang.Object#clone() method. Class has be implement Cloneable interface to use this.  

Structural Patterns

Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities. These design patterns help us on similar programming structure in application and help us in application wide coding standard. 
Adapter:
the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer (i.e. flags) but the client requires individual boolean values, the adapter would be responsible for extracting the appropriate values from the integer value. Another example is transforming the format of dates (e.g. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).
Example: Adapter Pattern is useful where we want to do integration from one format to another
  > java.util.Arrays#asList()
  > java.io.InputStreamReader(InputStream) (returns a Reader)
  > java.io.OutputStreamWriter(OutputStream) (returns a Writer)


Facade:
A facade Patern is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).
Example: Facade pattern is used to make any library classes and It help us to build module as service. 
  > javax.servlet.http.HttpSession
 > javax.servlet.http.HttpServletRequest
 > javax.servlet.http.HttpServletResponse
 > javax.faces.context.ExternalContext

Proxy:
A proxy, in its most general form, is a class functioning as an interface to do something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
A well-known example of the proxy pattern is a reference counting pointer object.
In situations where multiple copies of a complex object must exist, the proxy pattern can be adapted to incorporate the flyweight pattern in order to reduce the application's memory footprint. Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.
Example: This pattern is useful to create surrogate service, where client does not know about actual implementation.  java.rmi.* service uses Proxy pattern to communicate on network.

Bridge:
The bridge pattern is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulationaggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.
The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class "adapter pattern", e.g. in the Java code below.
Example: The Bridge pattern is an application of the old advice, "prefer composition over inheritance". It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape has a Color and to implement a hierarchy of colors, and that is the Bridge Pattern.

Composite:
Composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Component
  • is the abstraction for all components, including composite ones
  • declares the interface for objects in the composition
  • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
Leaf
  • represents leaf objects in the composition .
  • implements all Component methods
Composite
  • represents a composite Component (component having children)
  • implements methods to manipulate children
  • implements all Component methods, generally by delegating them to its children
Example: This pattern is used in making Rule engine or validation pattern, where composite and single rule can be used in same way.

    Decorator:
    the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:
    1. Subclass the original "Decorator" class into a "Component" class (see UML diagram);
    2. In the Decorator class, add a Component pointer as a field;
    3. Pass a Component to the Decorator constructor to initialize the Component pointer;
    4. In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
    5. In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
    This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).
    The decorator pattern is an alternative to subclassing. Subclassing adds behavior atcompile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.
    This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.
    Example for this: Java collections object using Collections.synchronized() method to synchronize the collection at run time. All subclasses of java.io.InputStreamOutputStreamReader and Writer have a constructor taking an instance of same type. Another good example is javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper.

    Flyweight:
    A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.
    A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning.
    In other contexts the idea of sharing identical data structures is called hash consing.
    Sample Code for Fly weight pattern.
    Example :  This pattern is used with method overloading and  java.lang.Integer#valueOf(int) (also on BooleanByteCharacterShort and Long) is example of this.

    Part 2 Continues on Behavioural Patterns.


    LinkWithin

    Related Posts Plugin for WordPress, Blogger...

    Labels

    Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt