Tuesday, May 24, 2016

Why main method should be public static void main(String[] args) in java?

Hello friends, Once again welcome back to Java Jagran. today i am here with "Why main method should be public static void main(String[] args) in java?" We all know that thsi is the signature/prototype of main method, but the question is why this? And the reason is here:
For understanding this we have to first understand little bit about JVM. First we have to understand how JVM calls main method of our class? When ever we are starting JVM by calling:
                          cmd> java MyClass arg1 arg2 ...       
This "java" program is nothing but our JVM. So it will collect all the three arguments( MyClass, args1, args2 ...). Then after it will create one String array and stores arg1, arg2 ... in that array. Then it will calls main() method on our class by passing that String array. Now lets understand each and every key of main method.
  • public: It must be public because if we take it as private then it must be only called from inside that class, if we take it as default then it must be only called from inside that class or same package, if we take it as protected then it must be only called from same class, same package, child classes of other package also. But JVM class is the other class that is not available in same package and also not a child class of our class. So it must be public.
  • static: It must be static because JVM is not creating object of our class for calling main method. The reason why JVM use not to create object of our class is: If our class have constructors then how JVM will identify that which constructor they have to use for creating object. And if it is parametrized then what data they have to pass in parameter. For solving these problems only sun people given it as static.

  • void: It must be void because main method is called by JVM. And if it is having some return value then what JVM will do with that data. It's a useless. That why sun people kept it as void.
  • main(): It's name must me main because if this is not specified then how JVM will know which method they have to call. That why sun people written code in JVM that will call only method with name "main".
  • String[]: As I already said, JVM use to collect all arguments and create one String array and then pass it to main method. The reason they taken it as String[] only is: In String we can store any type of data. For example if they taken it as int then how can we pass float/double and String value, If they taken it as float/double then how can we pass String, boolean etc data. But in String we can pass any type of data like int, float, boolean, String etc.

Now lets understand how  JVM calling main method: When ever we are stating JVM by calling  
                             java MyClass arg1 arg2 ...
Then JVM do like this:
                             MyClass.main(new String[]{arg1, arg2, ...});


Now lets see possible prototype of main method:
  • public static void main(String []args) 
  • static public void main(String []args)
  • public static void main(String ...args)
  • public final synchronized strictfp static void main(String[] params)

Monday, May 23, 2016

Custom class object in for each loop

Hello friends, As i said i am here with "How to use our own class object in enhanced for loop". As we seen we can use collection classes object in enhanced for loop because root (super) interface for all collection classes is java.lang.Iterable. So same as we also have to create a class with implementing java.lang.Iterable. So lets create a class:

       public class Custom implements Iterable{ } 

Now we have to override only one available method of Iterable interface that is iterator();

       @Override                                      
       public Iterator iterator() {}           


Now we have to create an object of class that implements java.util.Iterator interface. And we have to return this object from iterator() method. Here i am going to create an anonymous inner class. But before doing this we have to create decide that what type of data we wants to return from our class object? and how many data? Here for example i am taking an String array:


        private String []data={                               
                                                  "first data",        
                                                  "second data",    
                                                  "third data",       
                                                  "fourth data"      
                                            };                              
        private int index=-1,size=data.length;
       


Now create an anonymous inner class and return its object from iterator() method:


        new Iterator() {                             
            @Override                                 
            public boolean hasNext() {       
                return ++index < size;          
            }                                                
            @Override                                 
            public String next() {                
                return data[index];                
            }                                                
            @Override                                 
            public void remove() {              
                size--;                                     
            }                                                
        };
                                                  

That's all, now our class is ready to work in enhanced for loop. Lets create an Test class to test our class object.


        Custom cust=new Custom();     
        for(Object s: cust){                    
            System.out.println(s);            
        }                                                 


Here the full code of custom class and test class with output:

 


Here an example with generics: 




I hope it is helpful for you all. So be Java Lover and keep reading...
You can also watch my video on you-tube about enhance for loop.   Watch now 

Saturday, May 21, 2016

Enhance for loop in Java part-2

Hello friends, welcome back to Java lover. We all know that we can use object (specially collection classes object) also in enhance for loop. . Not only collection classes object we can also use our own class object in enhance for loop. ( I will write how to create and use our own class in enhance for loop in next post....). So as i said today i am going to write about how how enhance for loop works with objects.

We all know that Objects not works based on index(in the case of List collection also we are calling a function that will return a object. It doesn't List collection having index. List collection internally store data in array that have index. For more details i will write a post related to this very soon...). Only arrays having index. Then the question is how collection objects works with enhance for loop.

Actually we all know that top most interface of collection hierarchy is java.util.Collection. But there is super interface for the java.util.Collection interface, that is java.lang.Iterable. This interface is only responsible for the using objects in enhance for loop(I will tell you mere details about this in next post). Lets see an example:

When ever compiler sees enhance for loop then compiler first identify that there is array or an object. If it is array then compiler convert the code based on index. But if it is an object then compiler convert like this:




Now how many time loop will execute and what data they return is based on hasNext() and next() methods. I will write about these all methods and how to create our own class that will work in enhance for loop in next post... For watching full enhance for loop video on you-tube Click here

Enhance for loop in Java part-1


Friends today i am going to explain about enhance for loop/ for each loop. As a name it is a next to for loop. In for loop we user to iterate an array or object based on index or some condition. But in case of enhance for loop we need not to do that( or we can say that we can't do that). Enhance for loop internally uses these index or condition to iterate the array/ object.

Basically there is no concept like enhance for loop in Java for JVM. Actually this enhance for loop is only for the compiler. Compiler only understands enhance for loop and convert it into simple for loop before generation byte code. So if you see the byte code then you haven't find any enhance for loop there. For example:  If we are writing a java code fro iterating an array using enhance for loop then that is look like this:





But When we will decompile this class file then we will get like this:




So friends, this how enhance for loop works. We all know that we can use object also in enhance for loop. In next post i will write about how enhance for loop works with objects. For watching full enhance for loop video on you-tube Click here