Friday, 27 December 2013

Why we use constructor in Java?

Some people think that Constructor are used to create object , they are totally wrong. In actual constructor are used to construct the object, you cannot make object without invoking a constructor in java.

You cannot make a new object without invoking not only constructor of object's  actual class type but also the constructor of each of its superclasses

Constructor are the code that runs whenever you use the keyword new .

So every class must have constructor including Abstract classes.
Points to remember for constructors are
1. dont have return type
2. name must match the class name

So why we use them ?
Actually constructors are used to initialize the instance variable state as follows

class Demo{
 int age;
Demo(int age)
{
this.age=age;
}
}

Do you know each constructor must call their super constructor.

in the previous code block compiler will automatically add super() after this.age=age; line.

If we dont write any constructor in our java class then compiler automatically create default constructor .

Thursday, 26 December 2013

Why we need encapsulation in Java?

Why we need Encapsulation in Java ?

Suppose many programmer in your company wrote program that used your class.Now imagine later on you want to change an instance variable's value because the value set(by some other programmer using you class) to those variable are producing errors for you. Lets take an example

your class Demo1
{
int age;
getCalculatedAge()
{
//Code for calculation of age
}
}

Now suppose another programmer using your code

Demo2()
{
Demo1 d1=new Demo1();
d1.age= -4; // Suppose this causes some problem
d1.getCalculatedAge();
}
And now you're in trouble. How are you going to change the class in a way that lets you handle the issues that come up when somebody changes the age variable to a value that causes problems?

Your only choice is to go back a write a method setAge(int) for getting the age and handle the problem as well as you have to protect your age variable with private access modifier.

But as soon as you make your changes you break everyone else's code.

The ability to make changes in your implementation code without breaking the 
code of others who use your code is a key benefit of encapsulation.

If you want maintainability, flexibility, and extensibility (and of course, you do),your design must include encapsulation. How do you do that?

1. Keep instance variable protected (e.i private )
2.Make public setter or getter method so you can access and set the value to those variable.

public void setAge(int a)
{
age=a;
}
 
public int getAge()
{
return age;
}

This will prevent the direct access of your instance variable.Wait a minute...how useful is the previous code? 

Now what benefit can be there from getter and setter, Now in future if you want any processing or validation while getting the age from the setAge method you can do that without affecting anyone else's code which are using your class. Even if today you don't think you really need validation or processing of the data, good OO design dictates that you plan for the future. To be safe, force calling code to go through your methods rather than going directly to instance variables. Always. Then you're free to rework your method implementations later, without risking the wrath of those dozen programmers who know where you live.

Thursday, 12 December 2013

What is String Literal or Constant pool?



If you've done any preparation for the SCJP exam (and quite possibly even if you haven't), you've probably heard of the "String Literal Pool." What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects. Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

Yeah, so that doesn't really explain what the pool is, or what it's for, does it? Well, because String objects are immutable, it's safe for multiple references to "share" the same String object. Take a look at this example:


Source Code

public class ImmutableStrings {
 public static void main(String[] args)
 {
 String one = "techArcher";
 String two = "techArcher"; 
 System.out.println(one.equals(two)); 
 System.out.println(one == two); } } 

 // Output true true




In such a case, there is really no need to make two instances of an identical String object. If a String object could be changed, as a StringBuffer can be changed, we would be forced to create two separate objects. But, as we know that String objects cannot change, we can safely share a String object among the two String references, one and two. This is done through the String literal pool. Here's how it is accomplished:

When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.

So, in the example shown above, there would be only one entry in the String Literal Pool, which would refer to a String object that contained the word "techArcher". Both of the local variables, one andtwo, would be assigned a reference to that single String object. You can see that this is true by looking at the output of the above program. While the equals() method checks to see if the String objects contain the same data ("techArcher"), the == operator, when used on objects, checks for referential equality - that means that it will return true if and only if the two reference variables refer to the exact same object. In such a case, the references are equal. From the above output, you can see that the local variables, one and two, not only refer to Strings that contain the same data, they refer to the same object.

Graphically, our objects and references would look something like this:




Note, however, that this is a special behavior for String Literals. Constructing Strings using the "new" keyword implies a different sort of behavior. Let's look at an example:


Source Code
public class ImmutableStrings 

 public static void main(String[] args) 
 {
 String one = "techArcher"; 
 String two = new String("techArcher"); 
 System.out.println(one.equals(two)); 
 System.out.println(one == two); 
 }
 } 

 // Output true false




In this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to the two String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.

In such a case, although the two String references refer to String objects that contain the same data, "techArcher", they do not refer to the same object. That can be seen from the output of the program. While the equals() method returns true, the == operator, which checks for referential equality, returns false, indicating that the two variables refer to distinct String objects.

Once again, if you'd like to see this graphically, it would look something like this. Note that the String object referenced from the String Literal Pool is created when the class is loaded while the other String object is created at runtime, when the "new String..." line is executed.




If you'd like to get both of these local variables to refer to the same object, you can use the intern() method defined in String. Invoking two.intern() will look for a String object referenced from the String Literal Pool that has the same value as the one you invoked the intern method upon. If one is found, a reference to that String is returned and can be assigned to your local variable. If you did so, you'd have a picture that looks just like the one above, with both local variables, one and two, referring to the same String object, which is also referenced from the String Literal Pool. At that point, the second String object, which was created at run-time, would be eligible for garbage collection.

String is immutable?

This is one of the most popular String interview question in Java, this question some time may be asked as Why String is final in Java.

There may be many reason for this according to the creator of String in Java but few of my points are as:

1. String pool :- It is a special memory area in heap for storing the String literals. if the instance is already exist in the String constant pool then this new instance is mapped to the already existing instance,If not then a new Java String instance is created and stored in the pool.
There are several way to create an object of String, the only way to use the String Constant pool is using Literals

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists.
Lets take an example

String literal = "techArcher"; 
String one = new String(literal);
String two = "techArcher"; 
System.out.println(literal == two); //true 
System.out.println(one == two); //false

String is immutable means String object cannot be changed lets take another example

public class ImmutableStrings 
 public static void main(String[] args)
 { 
    String start = "Hello"; 
    String end = start.concat(" World!"); 
    System.out.println(end); 
 }
 } 
 // Output Hello World!

Well look at that, the String changed...or did it? In that code, no String object was ever changed. We start by assigning "Hello" to our variable, start. That causes a new String object to be created on the heap and a reference to that object is stored in start. Next, we invoke the method concat(String) on that object. Well, here's the trick, if we look at the API Spec for String, you'll see this in the description of the concat(String) method:

Concatenates the specified string to the end of this string. 

If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Notice the part I've highlighted in bold. When you concatenate one String to another, it doesn't actually change the String object, it simply creates a new one that contains the contents of both of the original Strings, one after the other. That's exactly what we did above. The String object referenced by the local variable start never changed. In fact, if you added the statementSystem.out.println(start); after you invoked the concat method, you would see that start still referenced a String object that contained just "Hello". And just in case you were wondering, the '+' operator does the exact same thing as the concat() method.

Strings really are immutable.

Wednesday, 11 December 2013

Java Programming interview questions

Sometimes in interviews you may asked to solve some programming questions based on the oops concept, so some questions related to the OOPs concepts are given below.

1.What would be the output of the given code snippets.

public static void methodA(Object o)
{
System.out.println("called from object");
}
public static void methodA(String s)
{
System.out.println("Called from string ");
}
public static void main(String[] a)
{
methodA(null);
}


So the answer would be
Called from string


because
Whenever there's Method Overloading, the JVM will search for the method from the most specific type to least specific type.


2.What would be the output of given program
class A
{
public void display()
{
System.out.println("class A");
}
}
public class B extends A
{
public void display()
{
System.out.println("class B");
}
public static void main(String[] args)
{
A a=new B();
a.display();
}
}



Ans:
class B

what happened here, we are calling the method from class A's reference variable but called the B's display method why?

This concept is called dynamic method dispatch, which is basically used by runtime environment for checking the actual type of objects.So here reference variable a contains the class B object actual so runtime called the method from class B.

Polymorphic method invocations apply only to instance methods. You can always refer to an object with a more general reference variable type (a superclass or interface),
but at runtime, the ONLY things that are dynamically selected based on the actual object (rather than the reference type) are instance methods. Not static methods. Not variables. Only overridden instance methods are dynamically invoked based on the real object's type.

3.What would be the output of the given question.

class A
{
public void show()
{
System.out.println("hi");
}
}
public class B extends A
{
public void display()
{
System.out.println("hi display");
}
public static void main(String[] args)
{
A a=new B();
a.show();
a.display();
}
}


Ans.
Compile time error

But why we are getting compile time error a reference variable referring B class object and B class has both the method then why this error.
Reason for this error is that at compile time, compiler don't check the type of the Object referred by the reference variable a, compiler only see the reference variable's class and checks whether called method through this reference variable exist in the class or not,If not found error occurred.


4.Why Java does not support multiple inheritance.

As we know that multiple inheritance is not supported in Java but the question is Why they did not introduce multiple inheritance like C++.
Lets clear one thing what is multiple inheritance ?
Multiple Inheritance:- This is the capability which allow a class to extend more than one other class.

Note:- Inheritance is used for code re-usability.

The reason that Java's creators chose not to allow multiple inheritance is that it can become quite messy.

The problem is that if a class extended two other classes,and both super classes had, say, a doStuff() method, which version of doStuff() would the subclass inherit? This issue can lead to a scenario known as the "Deadly Diamond of Death" because of the shape of the class diagram that can be created in a multiple inheritance design. The diamond is formed when classes B and C both extend A, and both B and C inherit a method from A. If class D extends both B and C, and both B and C have overridden the method
in A, class D has, in theory, inherited two different implementations of the same method. Drawn as a class diagram, the shape of the four classes looks like a diamond.



So the compiler will be confused which version of doStuff() will be called, That's why multiple inheritance is not allowed in Java.


5. Some Rules for overriding a method


  • The argument list must exactly match that of the overridden method
  • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass
  • The access level can't be more restrictive than the overridden method's. e.g You cann't use protected access level if superclass method have public access.
  • The access level CAN be less restrictive than that of the overridden method.
  • The overriding method CAN throw any unchecked (runtime) exception,regardless of whether the overridden method declares the exception.
  • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
  • The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass's exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what theoverridden method declares.
  • You cannot override a method marked final.
  • If a method can't be inherited, you cannot override it. Remember that overriding implies that you're reimplementing a method you inherited!
6.Rules for method overloading
Overloaded methods must change the argument list.
Overloaded methods can change the return type
Overloaded methods can change the access modifier
Overloaded methods can declare new or broader checked exception.
Remember one thing that the reference type not actual object type determines which overloaded method is invoked but which overridden version of the method to call is decided at runtime based on object type.
But which overloaded version of the method to call is based on the reference type of the argument list at compile time.

6.Why we used abstract class even if we have interfaces?

Both abstract class and interface are used to achieve abstraction in java.But what to choose is very good interview question. So abstract class is used where we want to provide some default behaviour , But interface is used where we are not providing any default behaviour , user can give any implementation for the behaviour of the interface .

One more thing that interface have all the method public if you want to make any method more restrictive then you can use abstract class.

But we also know that java doesn't provide multiple inheritance so its better to go for interface.