Hey Guys, I am creating this blog to share deep knowledge in Java, JSP, Servlets, JDBC, Hibernate, Spring and Spring MVC in details.

Can you access non-static variable in static context?


Can you access non-static variable in static context?
Static-variable in Java belongs to Class and its value remains the same for all instances. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instance and they get created when the instance of an object is created either by using a new() operator or using reflection like Class.newInstance(). So if you try to access a non-static variable without any instance compiler will complain because of those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance.
Example of accessing a non-static variable inside a static context:
public class StaticTest {
            private int count= 0;

            public static void main(String args[]) {
            StaticTest test = new StaticTest();
            System.out.println(test.count++);
            }
}
Types of memory areas are allocated by JVM :
·         Class(Method) Area
·         Heap
·         Stack
·         Program Counter Register
·         Native Method Stack
Share:

What is the immutable object? What is the difference between creating String as new () and literal? What is difference between Strings vs. StringBuffer vs. StringBuilder in Java?


What is the immutable object? What is the difference between creating String as new () and literal? What is difference between Strings vs. StringBuffer vs. StringBuilder in Java?
Immutable object:
Immutable classes are Java classes whose objects cannot be modified once created. Any modification in Immutable object results in a new object. For example, is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve the same functionality by making member as non-final but private and not modifying them except in constructor.
Difference between creating String as new() and literal:
·         String with new() Operator, it’s created in heap and not added into string pool.
·         String created using literal are created in String pool itself which exists in PermGen area of heap.
            String s = new String("Test");
·         Does not put the object in String pool, we need to call String.intern() method which is used to put them into the String pool explicitly.
·         It’s only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
Difference between Strings vs. StringBuffer vs. StringBuilder in Java:
·         String is immutable whereas StringBuffer and StringBuilder are mutable classes.
·         StringBuffer is thread-safe and synchronized whereas StringBuilder is not, that’s why StringBuilder is faster than StringBuffer.
·         String concat + operator internally uses StringBuffer or StringBuilder class.
·         For String manipulations in a non-multi threaded environment, we should use StringBuilder else use StringBuffer class.
Share:

Why Constructors are not inherited in Java?


Why Constructors are not inherited in Java?
Constructor is a block of code that allows you to create an object of the class and has the same name as a class with no explicit return type.
Whenever a class (child class) extends another class (parent class), the subclass inherits state and behavior in the form of variables and methods from its superclass but it does not inherit constructor of superclass because of following reasons:
Constructors are special and have the same name as the class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have the same name as the class name.
class Parent {
            public Parent() {
            }

            public void print() {
            }
}
public class Child extends Parent {
            public Parent()
    {
    }
            public void print() {
            }
public static void main(String[] args) {
  Child c1 = new Child(); // allowed
  Child c2 = new Parent(); // not allowed
            }
}
If we define Parent class constructor inside Child class it will give compile time error Return type for the method is missing and consider it a method. But for print method it does not give any compile time error and consider it an overriding method.
Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class’s constructor we can access/initialize private members of a class.
A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation. i.e.
 Child c = new Parent();
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.


Share:

What is the Singleton Design Pattern and its implementation in Java?



What are the Singleton Design Pattern and its implementation in Java?
Singleton is a design pattern which ensures there is only one object of the class is created for the entire application.
Step to make the Singleton pattern:
1.     Declare constructor as private.
2.     Create a private static final field and assign an instance of the same class.
3.     Create a public static method which returns the reference of the instance of the same class.

1: Classical Implementation
public class Singleton {
            private static Singleton obj1;
            private Singleton() {
            }
            public static Singleton getInstance() {
                        if (obj1== null)
                                    obj1new Singleton();
                        return obj1;
            }
}
Here we have declared getInstance() static so that we can call it without instantiating the class. The first time getInstance() is called it creates a new singleton object and after that, it just returns the same object. Note that Singleton obj1 is not created until we need it and call getInstance() method. This is called lazy instantiation.
The main problem with the above method is that it is not threaded safe. Consider the following execution sequence.
 This execution sequence creates two objects for the singleton. Therefore this classic implementation is not thread-safe.

2: make getInstance() method synchronized
class Singleton {
            private static Singleton obj1;
            private Singleton() {
            }
public static synchronized Singleton getInstance() {
                        if (obj1== null)
                                    obj1new Singleton();
                        return obj1;
            }
}
Here using synchronized makes sure that only one thread at a time can execute getInstance().
The main disadvantage of this is method is that using synchronized every time while creating the singleton object is expensive and may decrease the performance of your program. However, if performance of getInstance() is not critical for your application this method provides a clean and simple solution.

 3: Eager Instantiation
class Singleton {
   private static Singleton obj1new Singleton();
   private Singleton() {
   }
   public static Singleton getInstance() {
       return obj1;
   }
}
Here we have created an instance of a singleton in a static initializer. JVM executes static initializer when the class is loaded and hence this is guaranteed to be thread-safe. Use this method only when your singleton class is light and is used throughout the execution of your program.

4: Use Double-Checked Locking
If you notice carefully once an object is created synchronization is no longer useful because now obj1 will not be null and any sequence of operations will lead to consistent results.
So we will only acquire a lock on the getInstance() once when the obj1 is null. This way we only synchronize the first way through, just what we want.

class Singleton {
            private volatile static Singleton obj1;
            private Singleton() {
            }
            public static Singleton getInstance() {
              if (obj1== null) {
                 synchronized (Singleton.class) {
                    if (obj1== null)
                         obj1new Singleton();
                     }
                  }
            return obj1;
            }
}
We have declared the obj1 volatile which ensures that multiple threads offer the obj1 variable correctly when it is being initialized to Singleton instance. This method drastically reduces the overhead of calling the synchronized method every time.
Share:

Can we overload the static method and can we override the final method in Java?


Can we overload the static method in Java?

Yes, you can overload a static method in Java. You can declare as many static methods of the same name as you wish provided all of them have different method signatures.

public class Test {
            public static void Show(int i) {
                        System.out.println("i : " + i);
            }
            public static void Show(int i, int j) {
                        System.out.println("i : " + i + " and j : " + j);
            }
            public static void main(String args[]) {
                        Show(10);
                        Show(10, 20);
            }
}
 Output:
  i: 10
  i: 10 and j: 20

Can we override the final method in Java?
No, you cannot override a final method in Java; final keyword with the method is to prevent method overriding. You use final when you don't want subclass changing the logic of your method by overriding it due to security reason. This is why the String class is final in Java. This concept is also used in the template design pattern where the template method is made final to prevent overriding.

Share:

Popular Posts

Recent Posts