Search This Blog

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

Thursday, 15 November 2012

Why non static variable are not allow to use in static method in Java?

Most common thing about static variable we know, static means no need to create a instance. static variable can used with out instantiating class. Another fact about static variable is, we can not use non static variable inside a static method. if we forcefully go against it and use non static variable inside a static method then we get compile time error

      "Cannot make a static reference to the non-static field rectArea"   

Why it so ? why Java keeps such restriction? 

Compile this code -   


public class A {

 private static float rectArea;

 public static void main(String[] args) {
  A one = new A();
  one.setArea(200);
  A two = new A();
  two.setArea(300);
  A three = new A();
  three.setArea(400);
  System.out.print("Print Area = " + rectArea);
 }

 public void setArea(float areap) {
  rectArea = areap;
 }
}

This indicate a compile time error. So for a moment just ignore the error and let analyze our main issue. A class has instantiated three times. Variable rectArea has value corresponding to each instance.

  Lets go to System.out.print("Print Area = " + rectArea). 

We know we can access static variable without creating object, means static variable value does not depends on object of a class. Same things applied to methods.   So when we are trying to access rectArea which value depends on object of class A (as rectArea is not a static variable), it gives error. Because compiler get confused which value to use 200,300,or 400 for rectArea.  To avoiding this issue Java restrict that we can not use non static variable inside a static method. Same applies when you try to use non static method inside a static method 

Thursday, 8 November 2012

why two way exist to implement thread in java ?

Java has great concept called Thread. Thread is most discussed and assume to be most difficult  concept by people. while creating a simple thread, Java provide two ways

1) Extends Thread class 

public class Method1 extends Thread {

 public static void main(String[] args) {
  Method1 tm = new Method1();
  Thread th = new Thread(tm);
  th.start();
 }

 @Override
 public void run() {
  super.run();
  System.out.println("Extends Thread to create a Thread :)");
 }
}

2) Implement Runnable interface

public class Method2 implements Runnable {

 public static void main(String[] args) {
  Method2 tm = new Method2();
  Thread th = new Thread(tm);
  th.start();
 }

 @Override
 public void run() {
  System.out.print("Implement Runnable interface to create a Thread");
 }
}

So doubt goes increasing for a new programmer. Two ways to doing same thing ? why these necessity exists Let them clarify

Noted : Java provide inheritance . So we can use on class property inside another class by extending class. Consider class MN has method addSum(), iNeedMn want to use this addSum() then simple iNeedMn extends MN is solution. This is called single inheritance

    public class MN{
       
        public void addSum(){
            System.out.print("From MN");
        }
    }
   
    public class iNeedMn extends MN{
        @Override
        public void addSum() {
            super.addSum();
        }
    }

Consider now iNeedMn want to access the property of Thread class also (So called multiple Inheritance(is not allowed in JAVA) i.e one class can extends any number of class) or say iNeedMn need to be use as Thread somewhere. Impossible ???

Cause of providing two to make a thread is to avoid impact of banned multiple inheritance.We can not extends two classes but we can implement any number of interface

Which way to prefer ?

Implementing Runnable is preferred way.It's generally discouraged to extend the Thread class. The Thread class has a lot of overhead and the Runnable interface doesn't   

Difference between interface and abstract class in Java ?

Difference between interface and abstract class is most asked question in interview. Even i have face this question five times among 11 interviews.  Defination of abstract class and interface is completely different and easily undestandable but the main issue is to learn where to use abstract,interface.This post will contain a a example to clarify this issue

Main Difference between interface and abstract class


1) Interface allow only declaration of method, where as you can assign a body of a method inside a abstract class

 
public interface TestInterface {

 public String sumOfTwoNumber(int a,int b){    /// Abstract methods do not specify a body. So its not allowed
  int c = a + b;
  System.out.print(c);
  return String.valueOf(c);
 }
 
 public void abs(int a,int b);                 // Allowed
}

 
public abstract class TestAbstract {
 
       public String sumOfTwoNumber(int a, int b) {   // Allowed
  int c = a + b;
  System.out.print(c);
  return String.valueOf(c);
 }
 
 public abstract void sumb();                 // Allowed
}

2) By default every method of interface is abstract. but this is not true for abstract class. we can say that interface is implicitly abstract

3) Interface is fully abstract so we can not instantiate an interface. Making object of abstract class is not possible but it can revoke if its contain main
 like this

public abstract class StaticInner {

 public static void main(String[] args) {
  System.out.print("Invoked");
 }
} 
 

Now comes to general difference

 

1) a class use interface by keyword implements and abstract class with keyword extends

2) one interface can not extends a class but can extends any number of interface

 public interface A {
  public void add();
 }

 public interface B {
  public void minus();
 }

 public interface C extends A, B {
  public void Div();
 }

an abstract class can extends only one class but can implement any number of interface

 public class ABC{
  
 }
 public abstract class CanExtendsOnlyABC extends ABC implements A,B,C{
  
 } 
 
Final Note : Java interface works slow in comparision of abstract class

Saturday, 3 November 2012

Garbage Collection, Heap in android and Java

Garbage collection (GC) is the process that aims to free up occupied memory that is no longer referenced by any reachable Java object, and is an essential part of the Java virtual machine's (JVM's) dynamic memory management system. In a typical garbage collection cycle all objects that are still referenced, and thus reachable, are kept.
 Object no longer have any reference are elligble for garbage collection.

Before going further we need to discuss some important term in Garbage  Collection in android as well java. it works similar

    
  Heap Size or Java Heap or Heap : Every device allocate a specific amount of memory to run a process. It does not allocate all memory to one  process to ensure multitasking. e.g Let an android example, a device with 2 GB memory have heap size of 48 MB(this is my assumption, Heap size depends on device density and other factor). So this device will allow 26  process to run at a time and rest memory used in running OS files. when a process load in memory. It start allocating memory to object. So heap size start increasing. Eventually, the Java heap will be full, which means that an allocating thread is unable to find a large-enough consecutive section of free memory for the object it wants to allocate.At that point, the JVM determines that a garbage collection needs to  happen and it notifies the garbage collector. A garbage collection can also be triggered when a Java program calls System.gc(). Using  System.gc() does not guarantee a garbage collection. Before any garbage collection can start, a GC mechanism will first determine whether it is  safe to start it
  
A garbage collector should never reclaim an actively referenced object; to do so would break the Java virtual machine specification. A garbage collector is also not required to immediately collect dead objects. Dead objects are eventually collected during subsequent garbage collection cycles. While there are many ways to implement garbage collection, these two assumptions are true for all varieties. The real challenge of garbage collection is to identify everything that is live (still referenced) and reclaim any unreferenced memory, but do so without impacting running applications any more than necessary

Two kinds of garbage collection are present to determine which object will garbage collect--

  • Reference counting collectors
  • Tracing collector algorithms

Tuesday, 30 October 2012

final keyword in java and android

final is very common keyword to discussion in Java. final used in different places with different meanings. but its inherit meaning remains same. Let discuss some case where we need to use final.

1) To prevent the inheritance  : Let have two class A and B. A extends by B. and it worked fine

 public class A {
  public void prind() {
   System.out.print("You can inherit me");
  }
 }
 public class B extends A{
  @Override
  public void prind() {
   super.prind();
  }
 }

But if you changes prind() method to final then you can not override this method in B class

 public class A {
  public final void prind() {
   System.out.print("You can not inherit me");
  }
 }
 public class B extends A{
  @Override
  public void prind() {  //   Cannot override the final method from A
  super.prind();                //   Quick fix -> remove final 
  }
 } 
 
2) Using as constant : a variable followed by final keyword works as a constant. you can not re assigned values inside this variable
                        private final int m = 10;
but now you can not re assign value inside m.if you do this, it will show compile time error
                  m = 10;         // Compile error ->The final field m cannot be assigned
         
But it will be exceptional when we talk about one Array followed by keyword final
            private final int[] a = new int[5];
assigning values to index of a is valid and works well
            this.a[0] = 30; // Successfully worked


Wait wait........Explain a bit - while creating private final int[] a = new int[5], we assign array a to size of 5. So its final now. we can not changes size of array. But the memory slot we assign for each element of array is not constant we can changes its values
so this.a[0] = 30; is valid but
        this.a=new int[10];          is invalid

Finally it works same for array also

Friday, 26 October 2012

Difference between Weak reference and Soft reference in android and Java as well

In java as well as android, two concept are highly important but people are not much aware about these concept. These are weak reference and soft reference. They ensure to avoid memory over flow error and ensure fast caching of images. By name, They both seems similar but had lots of difference  If i say they are just opposite to each other , then its true.

Weak references : Weak reference is reference to an object that does not put strong force to remain object in memory. It allow garbage collector to collect object that it pointing. Take an example of creating Weakreference

      HashMap<String, WeakReference<Bitmap>> cache = new HashMap<String, WeakReference<Bitmap>>();

 cache.get(key) will return a Bitmap object that is pointed by Weakreference . As we know it does not put much force to keep this reference So you never know when this Bitmap will garbage collected and it starts returning null. Weak reference avoid memory overflow error by allowing garbage collector to collect its object without any algorithm

Where its Useful ?

Now the question arise when to use Weakreference,where memory reclaim highly needed. In simple case,avoiding Weakreference is recommended.

Soft Reference : Soft reference provide a strong reference to an object so that i will garbage collected as late as possible . Lets create one example
  
               private HashMap<String, SoftReference<Bitmap>> cache = new HashMap<String, SoftReference<Bitmap>>();

Soft Reference is helpful while you want to cache images to avoid time frame that consume in loading from Disk every time. It will make navigation fast and interactive. cache.get(key) will not return null as late as possible. It will garbage collected when VM running out memory.

Mechanism for garbage collection of soft reference from android developer official site

The system may delay clearing and en-queue soft references, yet all SoftReferences pointing to softly reachable objects will be cleared before the run time throws an   OutOfMemoryError.

Unlike a WeakReference, a SoftReference will not be cleared and en-queue until the run time must reclaim memory to satisfy an allocation.

From Oracle About Soft reference-

All soft references to softly-reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError. Otherwise no constraints are placed upon the time at which a soft reference will be cleared or the order in which a set of such references to different objects will be cleared. Virtual machine implementations are, however, encouraged to bias against clearing recently-created or recently-used soft references.

Conclusion

  •     SoftReference should be cleared and en-queue as late as possible, that is, in case the VM is in danger of running out of memory.

  •    WeakReference may be cleared and en-queue as soon as is known to be weakly-referenced. WeakReference garbage collected as soon as possible when VM needed memory

Monday, 22 October 2012

Advance Java : Inner Classes Concept in Java

Inner classes was introduces in JDK 1.1. And Inner class refer to a class appear with in

• class declarations
• method bodies
• expressions

Reason To Use Nested Classes From docs.oracle.com

Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.

Scope of an Inner class differ according to which type of Inner class you are using. We have four type in Inner Class

  •   Member Inner (MI) Classes
  •   Local Inner (LI) Classes
  •   Anonymous Inner (AI) Classes
  •   Static Inner (SI) Classes


  Let see one Example of Member Inner Class

public class A {

 public static void main(String[] args) {
  /**
   * Accessing Member Inner Classes
   */
  MemberInnerClass member = new A().new MemberInnerClass();
  member.printMessage();
 }

 public class MemberInnerClass {

  public void printMessage() {
   System.out.print("I am inside Member Inner Claas");
  }
 }
} 
  
 To accessing MI you have to create Object of Parent class(outer class). You can make MI Read Only by creating on private constructor

Local Inner Class is created inside a Method and its scope remains same method Member Variables


public class A {

 public static void main(String[] args) {
  /**
   * Accessing Local Inner Classes
   */
  new A().LocalLimit("I am inside Local Inner Class");
 }

 public void LocalLimit(final String message) {
  
  class LocalInnerCalss {
   public void printMessage() {
    System.out.print(message);
   }
  }
  new LocalInnerCalss().printMessage();
 }
}

Static Inner Class-- Its useful when modeling tightly coupled entities.Static class also provide Providing meaningful namespaces


public class StaticInner {
 public static void main(String[] args) {
  /**
   * Accessing Static Inner Classes
   */
  StaticInner.MemberInnerClass member = new StaticInner.MemberInnerClass();
  member.printMessage();
 }

 public static class MemberInnerClass {

  public void printMessage() {
   System.out.print("I am inside Static Inner Claas");
  }
 }
}

About Anonymous Inner Class, I will explain in a separate article as its need more explanation.

Now At the End some Use full tips to remember

Remember while declaring an inner class
• MI and SI appear within the body of a class
• LI and AI appear within the body of a method

Remember while accessing outer fields
• Both MI, LI and AI can refer to fields of their enclosing scope
• A SI can’t, since it doesn’t have an enclosing instance!

Article You May Like

Synchronization Of thread in Java, Anonymous Inner Class Explanation

Saturday, 29 September 2012

Java Interview Questions

Java is my all time favorite programming language because of its strong networking support and other strong features. Facing interview in java is always a challenge because of it broad view of concept.  Some question are repeatedly ask in interview while you goes for java as experience person or as fresher. Some of question i have faced two or three times . I am listing them below so that you guys does not struggle to give answer to them.

Q1. What is the difference between String and String Builder/String Buffer?

Ans. String object is immutable , immutable means we can not change the values store inside a string object. Let a example
                                 String temp="Hello";
If you append anything to temp then it will create a new object if append a different string to temp.
                                temp="Hello"+ "Check";

Printing temp will show "Hello check" but internally we have created two object while append "Check" to temp. Same process goes when you use trim method of String. So to improve performance we recommend to use String Buffer/String Builder. Both are mutable and we can changes the value of them without generating a new object.

Now important point is that String Buffer is synchronized and String Builder is not. So if you are not using threading , use String Builder else String Buffer. String Builder was introduce in java 1.4 but String String Buffer was launched in Java 1.5 version

Q2. What is the difference between Design Pattern and Framework?

Ans. Design Pattern is the Pattern designed by Java to make Java Application. It describe how to divide our complete java application into three part i.e MVC


  • Model : This part will handle only Business logic (Communication with Data Base).
  • View : This part only have presentation logic.
  • Controller : This part of logic contain the overall control flow (What should application has to do when a request comes from a Client).
Framework is a small s/w which has been designed by using Design Pattern. And it contain Web Application deployment architecture 

i.e  Spring, EJB 

Q3. What is the difference between passivation and activation?

Ans. While we client is not using any data then its store on secondary storage, this is called passivation but when client send a request to use that piece of data then it loaded into main memory  and this refers as activation process.

Q4. Explain Difference HashTable and HashMap?

Ans. Here is some key difference between them ---
  •  Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as un synchronized Objects typically perform better than synchronized ones.
  • Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  • One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Q5. Differnce between Vector and Array List?

Ans. Vector is synchronized whereas Array List is not synchronized . Using Vector inside threading application is recommended as it avoid insertion and deletion at once by throwing UnSupportedException

Q6. What is difference between Abstract class and Interface ?

Ans. Java does not support multiple inheritance so this restriction is some what avoided using interface . You can implement multiple interface in a single class but can not extends more than one class at time.
  • When you implement an interface to a class then its compulsory to override all method of interface (if class is abstract then its not necessary). But if you extends a abstract , there is no such necessity 
  • Abstract class implementation is fast
  • Interface provide only signature of method not code. but abstract class can have code for method
  • Interface'method is implicitly abstract

Saturday, 21 April 2012

Thread Synchronization in Java and Android

Java is always fun love for me. Thread was the only thing that make feared so study it hard and now want to make sure that it will not happen with any one now. I have discussed about how to create simple Thread. But most important is to Synchronization of two thread.

For example -We have one file. And we have two thread one for reading this file and second for writing file. So in this case if we want to read everything that has to be written by write thread.Then Read thread to wait (if write is running) until Write does not complete it task.

For Thread Synchronization important thing is to note that we can synchronize only on one object.
Although i will write code in android technology but in java and Blackberry its almost same.For this i need to take two thread

Thread 1

private class Thread2 extends Thread{
        
        private SynDemo d;
        public Thread2(SynDemo sDemo) {
            d=sDemo;
        }
        @Override
        public void run() {
            super.run();
            d.printNumber("Thread2");
        }
    }                                                                           

This Thread will print number from 0 to 2000.Next thread also will doing the same.

Thread 2

Thursday, 19 April 2012

Simple Thread example in java

Before posting this example i would to thank Herbert Shield


The simple example shown in full on the previous page defines two classes: SimpleThread and TwoThreadsTest. Let's begin our exploration of the application with the SimpleThread class: a subclass of the Thread class that is provided by the java.lang package.
class SimpleThread extends Thread {
    public SimpleThread(String str) {
 super(str);
    }
    public void run() {
 for (int i = 0; i < 10; i++) {
     System.out.println(i + " " + getName());
            try {
  sleep((int)(Math.random() * 1000));
     } catch (InterruptedException e) {}
 }
 System.out.println("DONE! " + getName());
    }
}
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is only interesting to us because it sets the Thread's name which is used later in the program.
The next method in the SimpleThread class is the run() method. The run() method is the heart of any Thread--it's where the action of the Thread takes place. The run() method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread then sleeps for a random interval between 0 and 1 second. After the loop has finished, the run() method prints "DONE!" along with the name of the thread. That's it for the SimpleThread class.
The TwoThreadsTest class provides a main() method that creates two SimpleThread threads: one is named "Jamaica" and the other is named "Fiji". (If you can't decide on where to go for vacation you can use this program to help you decide--go to the island whose thread prints "DONE!" first.)
class TwoThreadsTest {
    public static void main (String args[]) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}
Android News and source code