Sunteți pe pagina 1din 9

Java 1.

7 features
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
the new Java 1.8 features:
Lambda expressions
Remove the Permanent Generation
Small VM
Parallel Array Sorting
Bulk Data Operations for Collections
Define a standard API for Base64 encoding and decoding
New Date & Time API
Provide stronger Password-Based-Encryption (PBE) algorithm implementations in the
SunJCE provider
Can abstract class have Constructor in Java - Interview Question
Yes, abstract class can have constructor in Java. You can either explicitly provide constructor to abstract class or if
you don't, compiler will add default constructor of no argument in abstract class. This is true for all classes and its
also applies on abstract class. For those who want to recall what is an abstract class in Java, its a class which can
not be instantiated with new() operator or any other ways. In order to use abstract class in Java, You need to
extend it and provide a concrete class. Abstract class is commonly used to define base class for a type hierarchy with
default implementation, which is applicable to all child classes. By the way difference between interface and abstract
class in Java is also one of the popular and tricky Java questions and should be prepared well for Java interviews.
Can we declare constructor on abstract class in Java is followup of other similar Java interview questions e.g. Can
we override static method in Java?. Why interviewer ask this questions? Mainly because, trying to confuse
programmer with fact that since abstract class can not be instantiated, why abstract class need constructor. In this
Java Interview question article we will see that Abstract class can have constructor in Java.

Can we instantiate abstract class?
You can't instantiate your abstract class, however you can instantiate a concrete subclass of your
abstract class.

Why abstract class have constructor in Java
Now if we say we can not create instance of abstract class then why do Java adds constructor in abstract class. One
of the reason which make sense is, when any class extend abstract class, constructor of sub class will invoke
constructor of super class either implicitly or explicitly. This chaining of constructors is one of the reason abstract
class can have constructors in Java. Here is an example Java program, which proves that abstract class can have
constructors in Java
public class AbstractConstructorTest {
public static void main(String args[]) {
Server server = new Tomcat("Apache Tomcat");
server.start();
}
}
abstract class Server{
protected final String name;

public Server(String name){
this.name = name;
}
public abstract boolean start();
}
class Tomcat extends Server{
public Tomcat(String name){
super(name);
}
@Override
public boolean start() {
System.out.println( this.name + " started successfully");
return true;
}
}
Output:
Apache Tomcat started successfully

Constructor in interface?
Interfaces do not have constructors - in fact, interfaces define the methods that should be implemented by which ever
class that "implements" it. Conceptually, constructors should not be mixed with interfaces - constructors belong in
implementations. An interface, on the other hand, is a "contract" for a class that implements it.

What is Difference between inheritance and delegation in java

package com.m;
class RealPrinter { // the "delegate"
void print() {
System.out.println("something");
}
}
class Printer { // the "delegator"
RealPrinter p = new RealPrinter(); // create the delegate
void print() {
p.print(); // delegation
}
}
public class Tester {
// to the outside world it looks like Printer actually prints.
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}

When you delegate, you are simply calling up some class which knows what must be done. You do not really care
how it does it, all you care about is that the class you are calling knows what needs doing.
If I were you though I would make an interface and name it IPrinter (or something along those lines) which has one
method named print. I would then make RealPrinter implement this interface. Finally, I would change this line:
RealPrinter p = new RealPrinter(); to this: IPrinter p = new RealPrinter().
Since RealPrinter implements IPrinter, then I know for sure that it has a print method. I can then use this method to
change the printing behaviour of my application by delegating it to the appropriate class.
This usually allows for more flexibility since you do not embed the behaviour in your specific class, but rather leave it
to another class.
In this case, to change the behaviour of your application with regards to printing, you just need to create another
class which implements IPrinter and then change this line: IPrinter p = new RealPrinter(); to IPrinter p = new
MyOtherPrinter();.

what is Java Serialization?
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes
that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type
information and bytes that represent the object and its data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform
and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for
serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one method in
particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class
contains the following method for deserializing an object:
public final Object readObject() throws IOException,
ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will
need to cast it to its appropriate data type.

Externalization in Java ?
Before going into what externalization is, you need to have some knowledge on what serialization is because
externalization is nothing but serialization but an alternative for it and Externalizable interface extends Serializable
interface. Check Serialization article for information on serialization. Just as an overview, Serialization is the process
of converting an object's state (including its references) to a sequence of bytes, as well as the process of rebuilding
those bytes into a live object at some future time. Serialization can be achieved by an object by implementing
Serializable interface or Externalizable interface.
Well, when serialization by implementing Serializable interface is serving your purpose, why should you go for
externalization?
Good question! Serializing by implementing Serializable interface has some issues. Lets see one by one what they
are.
Serialization is a recursive algorithm. What I mean to say here is, apart from the fields that are required,
starting from a single object, until all the objects that can be reached from that object by following instance
variables, are also serialized. This includes the super class of the object until it reaches the "Object" class
and the same way the super class of the instance variables until it reaches the "Object" class of those
variables. Basically all the objects that it can read. This leads to lot of overheads. Say for example, you need
only car type and licence number but using serialization, you cannot stop there. All the information that
includes description of car, its parts, blah blah will be serialized. Obviously this slows down the performance.

Both serializing and deserializing require the serialization mechanism to discover information about the
instance it is serializing. Using the default serialization mechanism, will use reflection to discover all the field
values. Also the information about class description is added to the stream which includes the descption of
all the serializable superclasses, the description of the class and the instance data associated with the
specific instance of the class. Lots of data and metadata and again performance issue.

You know that serialization needs serialVersionUID, a unique Id to identify the information persisted. If you
dont explicitly set a serialiVersionUID, serialization will compute the serialiVersionUID by going through all
the fields and methods. So based on the size of the class, again serialization mechanism takes respective
amount of time to calculate the value. A third performance issue.

Above three points confirm serialization has performance issues. Apart from performance issues,

When an object that implements Serializable interface, is serialized or de-serialized, no constructor of the
object is called and hence any initialization which is done in the constructor cannot be done. Although there
is an alternative of writing all initialization logic in a separate method and call it in constructor and readObject
methods so that when an object is created or deserialized, the initialization process can happen but it
definitely is a messy approach.
The solution for all the above issues is Externalization. Cool. Here enters the actual topic.
So what is externalization?
Externalization is nothing but serialization but by implementing Externalizable interface to persist and restore the
object. To externalize your object, you need to implement Externalizable interface that extends Serializable interface.
Here only the identity of the class is written in the serialization stream and it is the responsibility of the class to save
and restore the contents of its instances which means you will have complete control of what to serialize and what not
to serialize. But with serialization the identity of all the classes, its superclasses, instance variables and then the
contents for these items is written to the serialization stream. But to externalize an object, you need a default public
constructor.
Unlike Serializable interface, Externalizable interface is not a marker interface and it provides two methods -
writeExternal and readExternal. These methods are implemented by the class to give the class a complete control
over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate
with the supertype to save its state. These methods supersede customized implementations of writeObject and
readObject methods.
How serialization happens? JVM first checks for the Externalizable interface and if object supports Externalizable
interface, then serializes the object using writeExternal method. If the object does not support Externalizable but
implement Serializable, then the object is saved using ObjectOutputStream. Now when an Externalizable object is
reconstructed, an instance is created first using the public no-arg constructor, then the readExternal method is called.
Again if the object does not support Externalizable, then Serializable objects are restored by reading them from an
ObjectInputStream.
import java.io.*;
public class Car implements Externalizable {
String name;
int year;
/*
* mandatory public no-arg constructor
*/
public Car() { super(); }
Car(String n, int y) {
name = n;
year = y;
}
/**
* Mandatory writeExernal method.
*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(year);
}
/**
* Mandatory readExternal method.
*/
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
name = (String) in.readObject();
year = in.readInt();
}
/**
* Prints out the fields. used for testing!
*/
public String toString() {
return("Name: " + name + "\n" + "Year: " + year);
}
}

import java.io.*;
public class ExternExample {
public static void main(String args[]) {
// create a Car object
Car car = new Car("Mitsubishi", 2009);
Car newCar = null;
//serialize the car
try {
FileOutputStream fo = new FileOutputStream("tmp");
ObjectOutputStream so = new ObjectOutputStream(fo);
so.writeObject(car);
so.flush();
} catch (Exception e) {
System.out.println(e);
System.exit(1);
}
// de-serialize the Car
try {
FileInputStream fi = new FileInputStream("tmp");
ObjectInputStream si = new ObjectInputStream(fi);
newCar = (Car) si.readObject();
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
/*
* Print out the original and new car information
*/
System.out.println("The original car is ");
System.out.println(car);
System.out.println("The new car is ");
System.out.println(newCar);
}
}
What is transient ?
transient is a Java keyword which marks a member variable not to be serialized when it is persisted to
streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'.
Serialization converts the object state to serial bytes.

Difference between transient and volatile keyword in Java
volatile and transient are two completely different keywords from different areas of Java programming
language. transient keyword is used during serialization of Java object while volatile is related to visibility of
variables modified by multiple thread during concurrent programming. Only similarity between volatile and
transient is that they are less used or uncommon keywords and not as popular as public, static or final.

1) transient keyword is used along with instance variables to exclude them from serialization process. if a field is
transient its value will not be persisted. On the other hand volatile keyword can also be used in variables to
indicate compiler and JVM that always read its value from main memory and follow happens-before relationship
on visibility of volatile variable among multiple thread.
2) transient keyword can not be used along with static keyword but volatile can be used along with
static.

3) transient variables are initialized with default value during de-serialization and there assignment or restoration
of value has to be handled by application code.

Thats all on difference between transient and volatile keyword in java. As I said this interview question
doesnt really test you and just try to find whether you are familiar with those less known keywords in java or not. Let
us know if you come across any other difference between volatile and transient keyword in java.

What is the native keyword in Java for?
The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java
Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware
and operating system platform) and libraries written in other languages such as C, C++ and assembly.

Difference between Stack vs Heap in Java?
1) Main difference between heap and stack is that stack memory is used to store local variables and function call,
while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member
variable, local variable or class variable, they are always created inside heap space in Java.

2) Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly you can
also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -
Xmx is maximum size of java heap.

3) If there is no memory left in stack for storing function call or local variable, JVM will throw
java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw
java.lang.OutOfMemoryError: Java Heap Space.

4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference
between stack and heap is that size of stack memory is lot lesser than size of heap memory in Java.
5) Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all
thread. In other words stack memory is kind of private memory of Java Threads, while heap memory is shared among
all threads.

synchronized block vs synchronized method?
Method:
public synchronized void method() { // blocks "this" from here....
...
...
...
} // to here
Block
public void method() {
synchronized( this ) { // blocks "this" from here ....
....
....
....
} /// to here...
}

Blocks do have advantages over methods, most of all in flexibility because you can use other object as
lock whereas syncing the method would lock the complete class.

How to Create Java Custom Exception ?
Sometimes it is required to develop meaningful exceptions based on application requirements. We can
create our own exceptions by extending 'Exception' class. Below example shows how to create custom
exception by extending Exception class.


package com.myjava.exceptions;
public class MyOwnException {
public static void main(String[] a){
try{
MyOwnException.myTest(null);
} catch(MyAppException mae){
System.out.println("Inside catch block: "+mae.getMessage());
}
}
static void myTest(String str) throws MyAppException{
if(str == null){
throw new MyAppException("String val is null");
}
}
}
class MyAppException extends Exception {
private String message = null;
public MyAppException() {
super();
}
public MyAppException(String message) {
super(message);
this.message = message;
}
public MyAppException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}

S-ar putea să vă placă și