Search This Blog

Showing posts with label Java Interview Questions. Show all posts
Showing posts with label Java Interview Questions. Show all posts

Friday 20 January 2017

What's New in Java 8

Java Platform, Standard Edition 8 is a major feature release. Java 8 contains a large number of new features. Although all are important, the three most important one are:
  • Lambda expressions
  • The stream API in java.util.stream
  • Default interface methods

Lambda Expressions
The most important new Java 8 feature is the lambda expression.
Lambda expressions are very important as they add functional programming features to Java. Lambda expressions can simplify and reduce the amount of source code needed to create certain constructs, such as some types of anonymous classes. This is particularly helpful when implementing a number of commonly used event handlers.
To support lambda expressions Java has been expanded by the inclusion of a new operator (the –>) and a new syntax element.


To understand the benefits that lambda expressions bring, consider the following ActionEvent handler, which uses the traditional, anonymous class, approach:

myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
myLabel.setText("Button pressed.");
}
});

With JDK 8, this event handler can be written using a lambda expression

myButton.addActionListener(
(ae) -> myLabel.setText("Button pressed.")
);


As we observe code is shorter, that is more direct and to the point.



The Stream API
Another important feature of Java 8 is the new stream API, which is packaged in java.util.stream.
A stream represents a sequence of data. The key aspect of the stream API is its ability to perform pipeline operations that search, filter, map, or otherwise manipulate data.

Let’s assume we have a list that stores employee names, department, e-mail and phone numbers. Using the stream API, we can efficiently pipeline the operations that search for entries that match some criterion, for example department name, sort the matching items, and then extract only the e-mail addresses In many cases, such actions can be performed in parallel, thus providing a high level of efficiency. The stream API provides a powerful means of handling data in an efficient, yet easy to use way.

Default Methods
With the release of Java 8, it is now possible for an interface method to define a default implementation. This new capability is called the default method.

Default method enables us a means by which interfaces could be expanded without breaking pre-existing code.
In simple terms default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.


When a non-abstract class implements an interface, it must implement all methods defined by that interface. If a new method is to an existing interface, then the addition of that method would break pre-existing code, because no implementation would be found for that new method in pre-existing classes. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause pre-existing code to break. This enables interfaces to be gracefully evolved over time without negative consequences.


Thursday 22 December 2016

What is the difference between doGet () and doPost ()?

While using doGet() or doPost() prefer using doPost() because it is secured and it can send much more information to the server.

GET or doGet()

GET is the simples HTTP method, and its main purpose is to ask a server to get a resource and send it back. The resource can be an HTML page, an image , a PDF etc.

  • The request parameters are transmitted as a query string appended to the request.
  • All the parameters get appended to the URL in the address bar.
    http://example.com/search?emp_name=sanjay 
  • Allows browser bookmarks but not appropriate for transmitting private or sensitive information. 
  • In an HTML you can specify as follows:
    <form name=”myForm” method=”GET” >
  • GET was originally intended for static resource retrieval.
  • GET is not appropriate when large amounts of input data are being transferred.



POST or doPost()

HTTP Post request is more powerful and used by the browser to make complex requests on the server. For example the user fills up a form and submit the data , which is then supposed to be inserted into a database.

The request parameters are passed with the body of the request.

More secured. In HTML you can specify as follows:
<form name=” myForm” method=”POST” >
POST was intended for form submits where the state of the model and database are expected to change.

Since POST sends information through a socket back to the server and it won’t show up in the URL address bar, it can send much more information to the server.



Unlike doGet(), it is not restricted to sending only textual data. It can also send binary data such as serialized Java objects.

Saturday 10 December 2016

What Are RESTful Web Services

Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability and modifiability that enable services to work best on the Web.
In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web.
It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.
In REST architecture, a REST Server simply provides access to resources and REST client accesses and presents the resources. Each resource is identified by URIs/ global IDs. REST uses various representations to represent a resource like text, JSON and XML.  JSON is the most popular format being used in web services.
The following principles encourage RESTful applications to be simple, lightweight, and fast:
·         Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery.
·         Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, DELETE is used to remove a resource. GET retrieves the current state of a resource. POST is used to update an existing resource.
·         Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.

·         Stateful interactions: Every interaction with a resource is stateless. It is responsibility of the client to pass its context to server and then server can store this context to process client's further request.  Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. 

Monday 5 December 2016

What is MVC architecture in J2EE

MVC stands for Model-View-Controller architecture. It promotes loose coupling between components by separating the functionality of displaying and maintaining of the data. It is often used by applications that need the ability to maintain multiple views like HTML, WML, Swing, XML based Web service etc. Multiple views and controllers can interface with the same model. Even new types of views and controllers can interface with a model without forcing a change in the model design.

To summarize the MVC does the following
  • Separation of Model from View components makes it possible to implement several user interfaces that reuse the common core business logic.
  • Duplication of low-level Model code is eliminated across multiple UI implementations.
  • Decoupling of Model and View code results in an improved ability to write unit tests for the core business logic code.
  • Modularity of components allows core logic developers and UI developers to work simultaneously without affecting the other.

  
A model represents the core business logic and state. A model commonly also maps to data the database and will also contain core business logic.
  • Manages the app data and state
  • Not concerned with UI or presentation
  • Often persists somewhere
  • Same model should be reusable, unchanged in different interfaces

  
A view renders the contents of a model. A view accesses the data from the model and adds display logic to present the data. 
  • Present the Model to the user in an appropriate interface
  • Allows user to manipulate data
  • Does not store any data.
  • Easily reusable & configurable to display different data


A controller acts as the glue between a model and a view. A controller translates interactions with the view into actions to be performed by the model. User interactions in a Web application appear as GET and POST HTTP  requests. The actions performed by a model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.
  • Intermediary between Model & View
  • Updates the view when the model changes
  • Updates the model when the user manipulates the view
MVC pattern decouples how data is manipulated from how data is displayed or stored. MVC is a way of developing apps by keeping the data (model) used in the program, and the visual (view) component separate from one another, each interacting only with a controller containing the logic. The view and the model interact only with the controller NEVER with each other.
MVC
MVC

Wednesday 30 November 2016

What is static class loading and dynamic class loading in Java

Static Loading
Classes are statically loaded in Java using new operator.

For Example :
class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}

A NoClassDefFoundException is thrown if a class is referenced with Java’s new operator but the runtime system cannot find the referenced class.


Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
The following specifies how classes are loaded dynamically in Java

Class.forName (String className); //static method which returns a Class
The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time.
Unlike the static loading, the dynamic loading will decide whether to load the class ClassXXX  or the class ClassYYY at runtime. Once the class is dynamically loaded the following method returns an instance of the loaded class.


class.newInstance (); //A non-static method, which creates an instance of a class
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.

. . . read more

Monday 21 November 2016

Handling Weeks in Java 7

Some applications in their business logic deals with the number of weeks in a year and the current week of the year. There are 52 weeks in a year, but 52 weeks multiplied by 7 days per week equals 364 days per year, not the actual 365 days. A week number is used to refer to the week of the year.

Java 7 has introduced several methods to support determining the week of the year.

Some implementations of the abstract java.util.Calendar class do not support week calculations. To determine if the Calendar implementation supports week calculations, we need to execute the isWeekDateSupported method. It returns true if the support is provided. To return the number of weeks for the current calendar year, use the getWeeksInWeekYear method. To determine the week for the current date, use the get method with the WEEK_OF_YEAR as its argument.

Below is the code to get total number of weeks and current week.
import java.util.Calendar;

public class WeeksInYear {
      public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            if(calendar.isWeekDateSupported()) {
                  System.out.println("Number of weeks in this year: " +
                              calendar.getWeeksInWeekYear());
                  System.out.println("Current week number: " + calendar.
                              get(Calendar.WEEK_OF_YEAR));
            }
      }
}


The above code will give the following out put
Number of weeks in this year: 53
Current week number: 47

Explanation of Code
An instance of the Calendar class is created, which is an instance of the

GregorianCalendar class. An if statement was controlled by the isWeekDateSupported method. It returned true, which resulted in the execution of the getWeeksInWeekYear and get methods. The get method was passed in the field WEEK_OF_YEAR, which returned the current week number.

Friday 11 November 2016

Using the try-with-resources block

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

This approach enables a better programming style as it avoids nested and excessive try-catch blocks. It also ensures accurate resource management, which is referred to as
Automated Resource Management (ARM).

The following example illustrates the use of try-with-resource

    try (BufferedReader br = new BufferedReader(new FileReader(path))) 


In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java  7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly.


Prior to Java  7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.

You may declare one or more resources in a try-with-resources statement. 
The following code snippet illustrates one or more resources in a try-with-resources statement. 
try (
        ZipFile zf = new java.ZipFile(zipFileName);
       BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset)
    ) {
               // To – Do
               }


In the above example, the try-with-resources statement contains two declarations that are separated by a semicolon

Example :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Java7TryResource {

public static void main(String[] args) {
 try (BufferedReader br = new BufferedReader(new FileReader(
    "C:\\myfile.txt"))) {
   System.out.println(br.readLine());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Wednesday 9 November 2016

Difference between String, StringBuffer and StringBuilder

String

The String class represents character strings. All string literals in Java programs, such as "xyz", are implemented as instances of String class.
Strings are constant, i.e. their values cannot be changed after they are created.
String objects are immutable and they can be shared.

For example:

     String str = "xyz";

is equivalent to:

     char data[] = {'x', 'y', 'z'};
     String str = new String(data);

The class String includes methods for
  • Examining individual characters of the sequence
  • Comparing strings
  • Searching strings
  • Extracting substrings
  • Creating a copy of a string with all characters translated to uppercase or to lowercase.



The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

String conversions are implemented through  toString method, which is defined in  Object class.

StringBuffer

StringBuffer is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
String buffers are safe for use by multiple threads. The methods of StringBuffer are synchronized.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type.
Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer.
The append method always adds these characters at the end of the buffer
The insert method adds the characters at a specified point.

For example,
if str refers to a string buffer object whose current contents are "pot",
then the method call z.append("s") would cause the string buffer to contain "pots",
whereas z.insert(2, "s") would alter the string buffer to contain "post".


If sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

StringBuilder


Since Java 1.5
StringBuilder is a  mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread
Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.


Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.




Friday 4 November 2016

What is JVM, JRE and JDK

Java Virtual Machine (JVM)
The Java Virtual machine (JVM) is the virtual machine that run the Java bytecodes. The JVM doesn't understand Java source code.
You compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM.
JVM makes Java to be a "portable language" (write once, run anywhere).
There are specific implementations of the JVM for different systems (Windows, Linux, MacOS) the aim is that with the same bytecodes they all give the same results.

Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications. If we want only to execute the programs written by others, then JRE alone will be sufficient.

Java Development Kit (JDK)
The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.