Friday, 31 March 2017

Difference between while and do-while loop

While loop and do while loop in java differ based on following parameter:

Execution process:

While loop checks the condition at the beginning of the loop.
If the condition is found to be true then only the statement inside the loop body gets executed.

int i= 7;
while(i<5){
//Inside while loop
System.out.print("condition is true");
i++;
}

From the above example, we see that first the condition, i<5, will be tested. And if the condition is true(in this case its false since i=7) then only the body inside loop will execute.
Since condition turns out to be false so the body inside while loop is not executed.


do while checks the condition at the end of the loop.
As the condition is tested at end of the loop so the body inside loop gets executed at least once, even in case the condition is found to be false.

int i= 7;
do{
//Inside do while loop
System.out.print("condition is true");
i++;
}while(i<5);

From the above example, we see that at first time entry inside loop there is no testing condition so the body inside do while loop gets executed. And then the condition, i<5, is getting checked at the end after body execution.
Even though the condition is false but the body gets executed once before the loop terminates.

Conclusion:

If you need a code where you want to execute your code at least once even if condition is false use do-while.
And if you are strict with condition check and don't want any execution for false outcome go for while loop.


You may also like to read:

Thursday, 30 March 2017

class variable vs instance variable in java

Before we proceed to find out the difference between class variable and instance variable, we must be aware that both of them are member variables. Both of these variables are associated with the class.

class variable vs instance variable Java radar
Member Variables


Instance variable:

int seasonName;
in above diagram is an instance variable.

Meaning is that every time an instance of the class Season is created, each instance will have its own copy of seasonName variable. If any of these instance modify the value of this variable then it will impact only that particular instance not the others.

So we can say that instance variable can be assigned with different value by each of different instances of the class.

As every instance has its own copy of the variable so memory requirement increases for the maintenance of instance variable for every instance.

In example program shown below, you can see each Human instance male, female, male1, etc can assign their own value to name variable. And if anyone of them later try to change the value it will only impact that particular instance without effecting other instances at all.


Example:

Source FileInstanceVariable.java

package variables;

public class InstanceVariable {

      public static void main(String[] args) {
            //assign different value to name(instance variable)of each instance
            Human male = new Human();
            male.name = "Rajneesh";

            Human female = new Human();
            female.name = "Shweta";

            //instance male assign value to name instance variable: Rajneesh
            System.out.println("Name of male:"+ " " + male); 
            //instance female assign value to name instance variable: Shweta
            System.out.println("Name of female:"+ " " + female); 

      }

}


Source FileHuman.java


package variables;

public class Human {
   public String name//instance variable  
  
   //overriding toString()
   public String toString(){
            return name;
      }

}


OUTPUT: 
Name of male: Rajneesh
Name of female: Shweta


Note:

For once just remove, 
public String toString(){return name;}
and see what you get?

You will get output something like this:
Name of male: variables.Human@15db9742
Name of female: variables.Human@6d06d69c




Class variable:

NOTE: static variable belongs to the class rather than to the instance of the class. It is variable that is common to all the objects. And this is achieved by declaring variable static.

static int seasonCount;
in above diagram is a class variable or static member variable.

Meaning all the instances of the class Seasons will share the same copy of the variable seasonCount.

And if any instance changes the value of the class variable then all the instances sharing this variable's data will get impacted.

As same copy is shared by every instance so memory consumption is less in comparison to maintenance of instance variable.

Try to write an example for static variable by yourself taking reference of instance variable example shown above. For reference you can follow the oracle documentation for class variable

Note: add static keyword to instance variable to change it to class variable.

int count;. // Instance variable
static int count; // class variable



You may also like to read:
                                                        

Difference: constructor and java method

Constructor and Method in java differ as illustrated below:

Name:

Constructor should be named same as the class name in which it is created.

Method may or may not bear the same name as that of the class name.

Return type:

A constructor does not have any return type in java.

A method should always be provided with return type in java.

Purpose:

Purpose of having constructor is to initialize state of an object.

Purpose of method is to expose the behaviour of an object.

Default provision:

A default constructor is always provided by java compiler if a programmar doesn't create any constructor.

Method needs to be created by programmar. Its never provided as default.

Wednesday, 29 March 2017

Can a java program be executed without having main()

We all have heard many times that main method is the entry point for any java program.

So whenever a program is executed, jvm starts searching for main method with
public static void main(String args[]){}
Signature.

And then whatever follows within main method starts getting executed.

But what if we omit the main method in a java program and still want the program to get executed.
There is still the way, if you are using version lesser than JDK 1.7

Solution is use static block

Try this example on your editor and execute it.

class noMainMethod{

    static{

      System.out.print("getting executed without main");

   }

}

So the solution is write your code in static block as shown above.

Note: Remeber this won't work if you are on JDK 1.7 or above version.

All you will get as output will be something like this

Output:

Error:Main method not found in class noMainMethod, please define the main method as: public static void main(String[] args)


You may also like to read:


--------------------------------------------------*-----------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java Head First
Click on the image link below to get it now.





Monday, 27 March 2017

Why would you ever mark a class final, if you can't change value of final variable, inherit final class or override final method?


You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. 

If you're deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation out from under you.

You'll notice many classes in the Java core libraries are final. 


For example, the String class cannot be sub-classed. And thus immutability gives confidence to use String as Username, Password, Database Connection parameters, key in the HashMap. It is just because we can rely upon String that is not going to be tampered anyhow later.

Use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods. Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer just like String.


Suggestion 


So unless you have a serious safety or security issue, assume that some day another programmer will need to extend your class.


You may also like to read:

Know what version of java you have?

Just to check your awareness and knowledge about java during interviews sometime you might be asked to tell what version of java you have worked upon in your last project.

Mostly beginner’s fail to answer this question as they have learned everything except this silly stuff.
So if you really don’t know then find its answer here as not answering this question might give bad impression about you to interviewer.

Process to know java version of the system

Window System :

Open command prompt( press windows key + r and then type cmd  and then press ok button) 
Command prompt will open.

In command prompt window, type

java –version

and hit enter.

You will be able to see the result showing the version of java your system has.

 Check online for any OS( windows, mac, etc):

1. Go to official java website. Click here
2. On this page click Agree and Continue button.
3. On next page click Verify Java Version button
4. You will be prompted ' Do you want to run this application'. Click on run
5. On the next page that appears will provide you the java version.



Sunday, 26 March 2017

LinkedHashSet in java

LinkedHashSet implements Set interface and extends HashSet class. It is part of java.util package.

Key feature of LinkedHashSet:

1.    LinkedHashSet is almost similar to HashSet except that it maintains the insertion order. If one use LinkedHashMap then you will get element returned in same order in which they were inserted.
To maintain insertion order, LinkedHashSet maintains a doubly-linked list running through all its entries.
2.    LinkedHashSet is non-Synchronized.
In order to Synchronize it, use Collections.synchronizedSet()
3.    Iterator returned by LinkedHashSet are fail-fast*.

*Fail-fast – If a set is modified at any time after the creation of iterator, except iterator’s own remove method, the iterator will throw ConcurrentModificationException.

Difference

·         HashSet vs LinkedHashSet
·         LinkedHashSet vs TreeSet

Wednesday, 22 March 2017

Difference : ArrayList vs LinkedList

Array List and Linked List both implements List interface. But which one to use when calls for a discussion. So lets look at the ways in which they differ to decide when to use ArrayList or LinkedList. 

Both differ based on following parameters:

1.       Insertion or Deletion of element
If there is need for lot of insertion or deletion of a elements in the List, then prefer Linked List as it provides faster insertion or deletion operation in comparison to Array List.

Reason
Array List requires lots of index shifting to be done for any insertion or deletion operation to be performed as a result performance time increases. Take a glimpse of insertion(13 needs to be inserted at index 2) in diagram given below:

java radar: insertion in array list


Linked List does not require shifting of many nodes. It just effects three nodes. One which is to be inserted. And the other two are between which it needs to be inserted. Take a glimpse of insertion(node having element 2 needs to be inserted between 1 and 3) in diagram given below.

Java Radar : Insertion into Linked List
Since lots of element don't need to be shifted for performing insertion or deletion operation in case of Linked List (which is in case of Array List), so it performs faster insertion and deletion operation. 




2.       Searching element from List
If one needs to search or get element from the List then for better performance opt for Array List as it provides faster search operation in comparison to Linked List.

3.       Memory consideration
Linked List consumes more memory space in comparison to Array List.

Reason 

Linked List has to maintain extra memory space for storing address data in both forward & backward pointer for each and every node apart from storing the element. Array List does not bother at all about storing any address detail so no extra memory requirement. 

      4.    Storage Mechanism
ArrayList uses dynamic array to store the elements.  
LinkedList uses doubly linked list to store the elements.

      5. Role
Arraylist can only perform the role of a List as it implements only List interface.
LinkedList can perform the role of both List and Queue as it implements both List and Deque interfaces

Example


package ListExample;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListExample {

      public static void main(String[] args) {

            //create ArrayList
            List<String> arrayList = new ArrayList<String>(); 
            //add element to ArrayList
            arrayList.add("Rajneesh");
            arrayList.add("Shweta");
            arrayList.add("Anup");

            //create LinkedList 
           List<String> linkedList = new LinkedList<String>();
            //add elements to LinkedList
            linkedList.add("Puja");
            linkedList.add("Mukesh");
            linkedList.add("Titli");

      }

}



You may also like to read:



Tuesday, 21 March 2017

Difference : ArrayList vs HashSet

ArrayList and HashSet differs based on the following parameters:➡➡

1.       Duplicate Object
ArrayList allows duplicate elements to be stored in it.
HashSet doesn’t allow duplicate element. All the element needs to be unique.

2.       Order Maintenance
Being a List implementation, ArrayList maintains the insertion order.
In HashSet, insertion order is not maintained. (HashSet-> order not guaranteed, LinkedHashSet-> Order is maintained)

3.       Null value
In ArrayList, one can store unlimited null values
In HashSet, only one null value is permitted.

4.       Implementations
ArrayList class implements List interface.
HashSet implements Set interface.

5.       Traversal
You can use both ListIterator and Iterator to traverse elements in ArrayList.
You cannot use ListIterator to iterate HashSet. To traverse HashSet use Iterator.


5.       Example
                                                            ArrayList Example

package javaRadarArrayList;

import java.util.ArrayList;
import java.util.Iterator;

public class ItrTraversal {

      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = new ArrayList<String>();
            //Add elements to ArrayList
            javaRadarList.add("Java");
            javaRadarList.add("Java");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");

            //creating iterator to traverse over javaRadarList
            Iterator<String> listIterator = javaRadarList.iterator();

            while(listIterator.hasNext()){
                  System.out.println(listIterator.next());
            }
      }

}

OUTPUT:
Java 
Java    // duplicate java is accepted by List
Spring
Hibernate

EJB


                              HashSet Example

package javaRadarHashSet;

import java.util.HashSet;
import java.util.Iterator;

public class ItrTraversal {

      public static void main(String[] args) {
            //create Array List
            HashSet<String> javaRadarSet = new HashSet<String>();
            //Add elements to ArrayList
            javaRadarSet.add("Java");
            javaRadarSet.add("Java");
            javaRadarSet.add("Spring");
            javaRadarSet.add("Hibernate");
            javaRadarSet.add("EJB");

            //creating iterator to traverse over javaRadarList
            Iterator<String> setIterator = javaRadarSet.iterator();

            while(setIterator.hasNext()){
                  System.out.println(setIterator.next());
            }
      }

}

OUTPUT:
Java      // duplicate java is not accepted by Set
Hibernate
Spring
EJB


You may also like to read:



-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.