Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Improved type inference in java 7

Before java 7, while using generics you had to supply type parameters to variables types and to their actual types. Now, it has been relieved a bit in this new java 7 feature, and a blank diamond on right side of declaration will work properly. Java 7 Compiler will identify that blank diamond infer to type defined on left hand side of declaration.

public class JavastuffOper {
    public static void main(String[] args) {
       Map<string , Double> params = new HashMap<>();  
// Rest of the code

}
}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

How to check the Compiler Version(JDK Version) of Compiled Java class file


We can use the javap utility that comes with the standard JDK. 
javap -verbose MyClass

Compiled from MyClass.java
public class MyClass extends java.lang.Object
SourceFile: MyClass.java
minor version: 3
major version: 45
The major version tells the Java version used. Here are some example values:
  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

How to make class as immutable in Java


1. All instance variables (state) must be set in the constructor alone. No other method should be provided to modify the state of the object. The constructor is automatically thread-safe and hence does not lead to problems.
2. It may be possible to override class methods to modify the state. In order to prevent this, declare the class as final. Declaring a class as final does not allow the class to be extended further.
3. All instance variables should be declared final so that they can be set only once, inside the constructor.
4. If any of the instance variables contain a reference to an object, the corresponding getter method should return a copy of the object it refers to, but not the actual object itself.

Example: 





public final class EmployeeModel {
//State
private final String firstName;
private final String lastName;
private final String SSN;
private final String address;
private final Car car;
//Constructor
public EmployeeModel(String fn, String ln, String ssn,
String addr, Car c) {
firstName = fn;
lastName = ln;
SSN = ssn;
address = addr;
car = c;
}
//Getters
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getSSN() {
return SSN;
}
public Car getCar() {
//return a copy of the car object
return (Car) car.clone();
}
public String getAddress() {
return address;
}
}

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Openings for Java Developers at Oracle

Publish Date: 16th April 2013  
Company Name:
Oracle India Pvt Ltd
Location: Bangalore
Experience: 7 – 12 years
Contact Mail : manish.soni@oracle.com
Company URL: http://www.oracle.com
Job Description:

  • BS/MS in Computer Science or related fields with 6+ years of professional experience preferably in product development companies.
  • Strong hands-on skills with Java, J2EE, SQL and XML
  • Knowledge and hands-on experience with Web Services, Web Services Security.
  • Relational database concepts
  • Understanding of cloud based computing and Platform-as-a-Service.
  • Knowledge of large volume, high throughput data and or messaging systems and technical understanding of achieving performance improvements.
  • Experience in implementing enterprise class products
  • Strong software engineering and debugging skills

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Difference between Vector, ArrayList and LinkedList in Java


Vector:
  • It is synchronized
  • Fast access to elements using index
  • Optimized for storage space
  • Not optimized for inserts and deletes
ArrayList:
  • Same as Vector except the methods are not synchronized.  
  • Better performance
Linkedlist:
  • Fast inserts and deletes
  • Stacks and Queues (accessing elements near the beginning or end)
  • Not optimized for random access


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

How Hashmap Works Internally in Java

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

The below example demonstrate how Hashmap worka internally.
import java.util.HashMap;
import java.util.Map;

class Employee {
 String name;
 
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((name == null) ? 0 : name.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

public class HashmapExample{
 /**
  * @param args
  */
 public static void main(String[] args) {

  Map map = new HashMap();
  Employee e1 = new Employee();
  e1.setName("Java");
  Employee e2 = new Employee();
  e2.setName("Java");
  System.out.println("e1 Hashcode=" + e1.hashCode());
  System.out.println("e2 Hashcode=" + e2.hashCode());
  map.put(e1, "Java Stuff");
  map.put(e2, "Java Tech");
  System.out.println("Map Elements: "+map);

 }
}


Output:

e1 Hashcode=2301537
e2 Hashcode=2301537
Map Elements: {Employee@231e61=Java Tech}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Difference between & and && in Java With Example

  • '&' is bitwise. & evaluates both sides of the operation.
  • '&&' is logical.&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.This is known as shortcircuiting and may be considered an optimisation. This is especially useful in guarding against nullness.
if( x != null && x.equals("JavaStuff.in") {
  then do something with x...
}

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Synchronization in Java

Synchronization of threads is needed for in order to control threads coordination, mainly in order to prevent simultaneous operations on data.

A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account may cause conflict.


For simple synchronization Java provides the synchronized keyword. For more sophisticated locking mechanisms, starting from Java 5, the package java.concurrent.locks provides additional locking options.

Synchronizing instance methods and static methods:  

A synchronized method acquires a lock before it executes. In the case of an instance method, the lock is on the object for which the method was invoked. In the case of a static method, the lock is on the class. If one thread invokes a synchronized instance method (respectively, static method) on an object, the lock of that object (respectively, class) is acquired first, then the method is executed, and finally the lock is released. Another thread invoking the same method of that object (respectively, class) is blocked until the lock is released.

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

Synchronizing blocks: 

A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block.

public void addName(String name) {
  synchronized (this) {
    lastName = name;
    nameCount++;
    }
    nameList.add(name);
}


When synchronizing a block, key for the locking should be supplied (usually would be this) The advantage of not synchronizing the entire method is efficiency.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

What is Serialization and How it works ?

What is Serialization ?

Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. The Java Serialization API provides a standard mechanism for developers to handle object serialization.
  • Allows the persistent storage of objects
  • Uses the java.io.Serializable interface
  • ObjectInputStream and ObjectOutputStream
  • Allows you to save objects to file and load them at a later date
  • Really should only be used for temporary storage of objects

What is actually saved?

  • Only class name and object’s data is saved
  • If that data is an object, it is also saved
  • Each object is given a serial number
  • If an object has already been saved (e.g. within a graph) then only the serial number is saved
  • Methods are not saved
  • Static information not saved 

Making an object serializable :

  1. Implement the Serializable interface
    • Does not require any methods to be implemented
  2. Implement the Externalizable interface
    • default behaviour only saves class name
    • must implement readExternal and writeExternal

To save and load an Object:

To save the objects to file:

FileOutputStream file = new FileOutputStream("data.ser");
ObjectOutputStream output = new ObjectOutputStream(file);
output.writeObject(family);
output.close();

To load the objects from file:

FileInputStream file = new FileInputStream("data.ser");
ObjectInputStream input = new ObjectInputStream(file);
Family family = (Family) input.readObject();
input.close();

Note: .ser file naming convention.

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Difference between comparable and comparator interface in java


The Comparable interface is used to define the "natural order" of a class.  The Comparable interface imposes the definition of the compareTo() method onto the class which is used during the sort process. 

It is true that some classes, such as the String and wrapper classes, have a natural order, but this is because they implement the Comparable interface and have a compareTo() method defined. Note that it is common to use these classes and methods when defining the sort criteria for other classes. 

The Comparator interface imposes the definition of a compare() method onto the implementing class. Similar to the Comparable interface, the compare() method is used during the sort process to arrange an array or collection of objects in the defined order. 

Both compareTo() and compare() return an int value (-1, 0, or 1), indicating to the sort process whether the two objects being compared should be exchanged or not. 

A class can implement each, although if more than two sort criteria are needed, it is common to implement the Comparator interface using a series of inner classes, perhaps anonymous. The Comparator interface can also be implemented by an external class on behalf of another class. Conversely, a class must implement its own Comparable interface to define its natural order. 

The advantage of the Comparable interface is that it's compareTo() method is used by default by a sort() method. With the Comparator interface, a reference to an object defining the particular compare() method to be used must be specified. 

Note that since version 1.5, generic versions of each interface are available, so the compareTo() and compare() parameters are defined in terms of the object types being sorted, not Object objects. 


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

Most Useful Java Programming Tips

Try to write self-documented programs: Use logical variable names and function names :    
not :  int x;     
but :  int studentCount;

Comments :
Use comments whenever something is unclear. Think that you are telling some other person about your code. (After a long time, this person might be you)

What is the use of serialization version UID in java ?


The purpose of the serialization version UID is to keep track of different versions of a class in order to perform valid serialization of objects.
The idea is to generate an ID that is unique to a certain version of an class, which is then changed when there are new details added to the class, such as a new field, which would affect the structure of the serialized object.
Always using the same ID, such as 1L means that in the future, if the class definition is changed which causes changes to the structure of the serialized object, there will be a good chance that problems when trying to deserialize an object.
If the ID is omitted, Java will actually calculate the ID for you based on fields of the object, but I believe it is an expensive process, so providing one manually will improve performance.

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email

What NOT to do when Java Coding ?

1) Do not hide exceptions
Exceptions are usefull. They are not something to be ashamed of and do not need to be hidden.
E.g.

try {
  ...
} catch (Exception e) {
  //do nothing here
}

By doing this you just swallow all Exceptions (including RuntimeExceptions). No one will ever notice that something went wrong. Catch only those Exceptions you really want to catch and you are capable (and willing) to handle at that time.

2) Do not be too generic with your exceptions
E.g.
  
  public void someMethod() throws Exception {
      ...
    }

Try to tell the users of your code what might happen in your method. Don't be afraid of doing something like

public void someMethod() throws NoSuchElementException, ConcurrentModificationException, IllegalArgumentException, InterruptedException {
      ...
    }

Admitted, this looks a bit extreme (and is just a random example), but it tells what might happen and what the user of your code has to be prepared of.

3) Do not be afraid of defining your own exceptions
There is a huge amount of exceptions out there, but still, there might be none for your special case. If you need an exception that e.g. happens when your webcam isn't available then define a WebcamUnavailableException or something alike.
Sometimes it is also a good idea to not use a fitting exception but to create one that fits even more. E.g. you want to load an image taken by your webcam which isn't there, a FleNotFoundException will perfectly fit, however, a NoImageToLoadException will fit even more.

4) Declaring Data Members as Public
Honsetly, there is no reason to declare data members as public. Data members should be limited to private (or protected when you really have to).
Accessing those members should be done using set\get methods only.

Interviews By Company :

How to decide whether to use Interface or Abstract Class ?

Choosing Interfaces and Abstract Classes is not an either/or proposition. If you need to change your design, make it an Interface. However, you may have Abstract Classes that provide some default behavior. Abstract Classes are excellent candidates inside of application frameworks. Abstract Classes let you define some behaviors; they force your subclasses to provide others.

  For example, if you have an application framework, an Abstract Class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. 

 So instead of trying to define that behavior itself, the Abstract Base Class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an Abstract Class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the Abstract Class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

abstract class Human {

void hand(){
System.out.print("Two Hands");
}

void leg(){
System.out.print("Two Leg");

void head(){
System.out.print("One Head")
}
void language();
void language();

}

public class southIndia extends Human{

void dressCode(){
//Traditional dress Code
}
void language(){
// Telugu, Tamil, Kanada,Kokani
}
public class NorthIndia extends Human{

void dressCode(){
// Traditional Dress Code of North India
} 
void language(){
//Hindi
}

}

What is difference between instanceof and isInstance(Object obj)?

1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.


if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}

2) instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

How to change the heap size of a JVM?

The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email