Why Should we override equals method in Java

In this tutorial,we will try to understand need for overriding equals method in Java.


Let's start this topic with something very basic i.e. object.What is Object?

Anything which has state and behavior can be treated as object in Object oriented language.

State - represented by instance variables of class
behavior - represented by methods of class

For example every one of us has some state and behavior.

Our state can be represented by
- name
- address
- fatherName
- motherName

and behavior can be represented by
- eat()
- sleep()
- work()

Now if have to give a name to the Class(group) to which these objects belong,we can name it HumanBeing and class will look like as below :

package nl.blogspot.javasolutionsguide;

class HumanBeing {
 String name;
 String address;
 String fatherName;
 String motherName;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public String getFatherName() {
  return fatherName;
 }

 public void setFatherName(String fatherName) {
  this.fatherName = fatherName;
 }

 public String getMotherName() {
  return motherName;
 }

 public void setMotherName(String motherName) {
  this.motherName = motherName;
 }

 public void eat() {
  System.out.println("Eat  like normal human beings");
 }

 public void sleep() {
  System.out.println("Sleep  like normal human beings");
 }

 public void work() {
  System.out.println("Work like normal human beings");
 }
}

Now this is general class representing all Human beings,but there are some special type of creatures in this world,who work day and night on computer to do coding and people call them Software developers,but they are human beings only,so let us create a class SoftwareDeveloper by extending HumanBeing class as below :

package nl.blogspot.javasolutionsguide;


class SoftwareDeveloper extends HumanBeing{
 
 String unit;
 String companyName;
 String technology;
 String totalExperience;
 public String getTotalExperience() {
  return totalExperience;
 }

 public void setTotalExperience(String totalExperience) {
  this.totalExperience = totalExperience;
 }
  
 public String getCompanyName() {
  return companyName;
 }

 public void setCompanyName(String companyName) {
  this.companyName = companyName;
 }

 public String getTechnology() {
  return technology;
 }

 public void setTechnology(String technology) {
  this.technology = technology;
 }

 public String getUnit() {
  return unit;
 }

 public void setUnit(String unit) {
  this.unit = unit;
 }

 public void work() {
  System.out.println("Keep Working");
 }
    
 public void eat(){
     System.out.println("Eat occasionally");
 }
    
 public void sleep(){
     System.out.println("Sleep occasionally");
 }
}

Let us now create a test Class where we will create objects of SoftwareDeveloper class and compare them.

package nl.blogspot.javasolutionsguide;

public class TestClass {

 public static void main(String[] args) {
  SoftwareDeveloper softwareDeveloper1 = new SoftwareDeveloper();
  softwareDeveloper1.setName("Gaurav");
  softwareDeveloper1.setCompanyName("ABC Limited");
  softwareDeveloper1.setTechnology("Java");
  softwareDeveloper1.setTotalExperience("8");
  softwareDeveloper1.setUnit("Fiancial Services");
  
  SoftwareDeveloper softwareDeveloper2 = new SoftwareDeveloper();
  softwareDeveloper2.setName("Gaurav");
  softwareDeveloper2.setCompanyName("ABC Limited");
  softwareDeveloper2.setTechnology("Java");
  softwareDeveloper2.setTotalExperience("8");
  softwareDeveloper2.setUnit("Fiancial Services");
  
  /*Below comparison is like saying that two physically existing 
      individuals(developer) are one and same or equal,which can never
      be the case we know.*/

  if(softwareDeveloper1 == softwareDeveloper2){
   System.out.println("Both are equally good");
  }else{
   System.out.println("Both are not equally good");
  }
  
 }
}

Output :
Both are not equally good

In the TestClass,we are creating two objects of SoftwareDeveloper class and both of them has exactly same state(properties),but still they are two different individuals,so we can not say that they are one ans same.

TakeAway 

When we compare objects using ==  it compares if they are same objects in memory and not the values (states) in the object.

What if we use equals in above TestClass to compare two SoftwareDeveloper instances


package com.test.equals;

public class TestClass {

 public static void main(String[] args) {
  SoftwareDeveloper softwareDeveloper1 = new SoftwareDeveloper();
  softwareDeveloper1.setName("Gaurav");
  softwareDeveloper1.setCompanyName("ABC Limited");
  softwareDeveloper1.setTechnology("Java");
  softwareDeveloper1.setTotalExperience("8");
  softwareDeveloper1.setUnit("Fiancial Services");
  
  SoftwareDeveloper softwareDeveloper2 = new SoftwareDeveloper();
  softwareDeveloper2.setName("Gaurav");
  softwareDeveloper2.setCompanyName("ABC Limited");
  softwareDeveloper2.setTechnology("Java");
  softwareDeveloper2.setTotalExperience("8");
  softwareDeveloper2.setUnit("Fiancial Services");
  
  if(softwareDeveloper1.equals(softwareDeveloper2)){
   System.out.println("Both are equally good");
  }else{
   System.out.println("Both are not equally good");
  }
 }
}

Output :
Both are not equally good

As we can see still,these two software developers are not being considered equal.Reason being when we are calling equals() method on SoftwareDeveloper's instance,it is actually calling equals() method in the Object class,which is parent of all java classes and by default all public methods of Object class are available to all the Java classes.Below is implementation of equals() method in Object class:

public boolean equals(Object obj) {
      return (this == obj);
}

As we can see here also,it is using == ,hence same result.

Take Away 

If we do not override equals() method in our classes,the default implementation from Object class will be available to all the classes and if we will try to compare objects using equals(),it will compare using == and will consider two objects equal only when they are referring to same object in memory.

Now one may ask,are above two approaches to compare objects is wrong?

Answer is Yes as well as No.

No,because it depends upon our requirements.if our requirements is such that we do not want to consider two different objects in memory as same even when they have same values,then there is nothing wrong with above approaches.

Yes,because there might be requirements in the application in which above code is being used that if two SoftwareDevelopers have same experience ,then consider them as equal.For example for HR department,they may give same salary to two developers with same experience ,so for them two developers with same experience are equal,although still they are two different individuals(different objects in memory).

Now one may ask,how we can make HR module of application understand that two different objects in memory are actually equal.

Answer is: we need to override equals method such that two objects should be considered equal when the value of property(instance variables) totalExperience is same.

Let us override equals() method in  SoftwareDeveloper class,such that we consider two objects equal when they have same totalExperience.

  @Override
 public boolean equals(Object obj) {
 if (this == obj){
  return true;
 }
 if (obj == null){
  return false;
 }
 if (getClass() != obj.getClass()){
    return false;
 }
 SoftwareDeveloper other = (SoftwareDeveloper) obj;
 if (totalExperience == null) {
    if (other.totalExperience != null)
       return false;
    } else if (!totalExperience.equals(other.totalExperience)){
       return false;
    }
    return true;
 }

How above equals method is getting called 

if(softwareDeveloper1.equals(softwareDeveloper2)){
 System.out.println("Both are equally good");
}else{
 System.out.println("Both are not equally good");
}

Let us try to understand above equals method code:

if (this == obj){
    return true;
}
Here this refers to instance softwareDeveloper1 and obj refers to softwareDeveloper2 and we are comparing them with == .We are doing this first ,because if two objects are same objects in memory,obviously they are equal and there is no need to check for their values and equals method can return true in that case any ways.

if (obj == null){
   return false;
}

if we have reached inside equals method ,that means softwareDeveloper1 is definitely not null as we have invoked equals method on softwareDeveloper1 instance,but it is possible that softwareDeveloper2 will be null,in which they will not be == and hence equals should return false.

if (getClass() != obj.getClass()){
    return false;
}

getClass returns the runtime class of the object on which it is called.So here we are checking ,if softwareDeveloper1 and softwareDeveloper2 both belong to same class at runtime,if they are not belonging to same runtime class,obviously they are not equal,so equals return false.

Note : if you will print output of getClass() and obj.getClass(),you will get below :
class com.test.equals.SoftwareDeveloper
class com.test.equals.SoftwareDeveloper

SoftwareDeveloper other = (SoftwareDeveloper) obj;
if (totalExperience == null) {
   if (other.totalExperience != null)
      return false;
   } else if (!totalExperience.equals(other.totalExperience)){
     return false;
   }
   return true;
 

In above code,first we are checking whether totalExperience instance variable value of softwareDeveloper1 is null and of softwareDeveloper2 is not null.If this is the case then as totalExperience value is not equal,equals method will return false.

Next we check,if softwareDeveloper1's totalExperience is not equal to softwareDeveloper2's totalExperience ,then also equals method returns false.

And if we have crossed passed all above if,elses and equals method have not returned yet,that means totalExperience of softwareDeveloper1 and softwareDeveloper2 are equal.

Now ,after overriding equals method,if we run our TestClass code,we will get following output :

Both are equally good

Take Away :

Depending upon our functional requirements,we would like to consider two different objects in memory as equal by overriding equals method where in we can check for equality of the property(ies) of two instances and can decide whether they should be considered equal or not.

In the next tutorial we will see why we should override hashCode() method when we override equals().

Thanks for reading!!!

[Solved] validation errors for already well tested third party JavaScript libraries

Problem : Sometimes Eclipse gives validation errors for already well tested third party javascript libraries while you build your code.

Solution :

Step 1 :

Right click on the project ->Properties->JavaScript->Include path.


Step 2 : 

Select Excluded under Source tab by clicking on it.


Step 3 :

Click on Edit… button.


Step 4 :

Click on “Add Multiple…” button in Exclusion pattern section and select java script files which are giving errors and for which you don’t want  validation to happen, from Your project’s folder.
Click ok.

Step 5 :

You will see all the selected scripts in exclusion patterns as below .Click on Finish.


Step 6 : 

Click Ok on below popup.



Clean build the project again and your validation errors will be gone.

Thanks.

[Solved] There are No resources that can be added or removed from the server - Tomcat

Issue : User created a dynamic web project in Eclipse and then try to deploy it on embedded Tomcat in eclipse by right clicking on server and clicking on "Add and Remove..." option.

User gets message "There are No resources that can be added or removed from the server"

Solution :

Right click on project -> Properties->Type "Project Facets"-> Select "Project Facets" -> tick Dynamic Web Module checkbox -> Select appropriate version -> Click Apply.


Now again right click on server and select "Add and Remove..." option,you should be able to deploy project as can be seen in below screenshot.


Thanks for reading!!!!

How to Install SVN Plugin in Eclipse

Hi Friends,
In this tutorial we will see how to install SVN plugin in eclipse.
Prerequisite : You should have internet connection.
Steps :

It is a two step process:

Step 1 : Install Subversive Plugin
Step 2 : Install SVN Connector

Step 1 : Install Subversive Plugin
1) Open eclipse 
2) Go to Help menu option -->install new software and click on install new software.
  
3) Click add button in front of work with drop down.
   
4) In the opened pop up,give any name in "Name" textbox and in "Location" textbox enter following url:
    and click ok.

   Note : Visit https://eclipse.org/subversive/downloads.php for latest subversive release.
   
5) Wait for some time it will search for plugins.Select required plugin(s),click next,next and finish and it      will install required plugins.
6) It will ask for restart.Restart Eclipse.

Step 2 : Install SVN Connector

7) Once you have installed subversive plugin and you restart eclipse,subversive will automatically show the dialog that shows Subversive SVN Connectors compatible with the installed version of the plug-in.I selected Native JavaHL 1.8.15 and installed it.
8) Go to Windows -> Show View -> type SVN and select SVN Repositories
   
8) You will find SVN Repositories tab in eclipse as can be seen in below screenshot

9) You can create a new repository location in the above mentioned tab by right clicking and then selecting New->Repository Location.. and then by entering required SVN URL along with username/password.

Additional Tips 

1) You can download SVN Connector by going to Window->Preferences->SVN->SVN Connector as well.
OR
2) You can download SVN Connector by going to Help-> Install New Software...->Get latest and compatible(with Subversive and OS) Url from  https://www.polarion.com/products/svn/subversive/download and enter in Work With box and click add and then procedd with installation just like you did for subversive above.

That's all.With this we saw that how we can add SVN plugin in eclipse.
If you have any suggestion to add something more to this post,please post in comments section.

Can we overload or override main method in Java

Hello Friends,

In this tutorial,we will see whether we can overload or override main method in Java.This is very common interview question as well and the answer is really simple,if we don't overthink :)


To understand What is main method and what it does thoroughly,please read What does main method do in Java? Why main method is public,static,void?

Can we overload main method in Java?

Short answer is YES,we can overload main method in Java.

main method's specialty is that it provides starting point for a standalone java application.It's signature is such that JVM understands that signature and calls main method with specific signature.

main method signature is as follows :
public static void main( String[] args );

which means if we define another method in same class with another signature,JVM will still call main method with above mentioned signature only.
So it is perfectly fine to have another main method in same class with different signature and we very well know that methods with same name and different signatures within a class are known as overloads.

Let us see it working with example.
public class Application {
    public static void main( String[] args )
    {
        System.out.println( "In JVM called main method" );
        System.out.println("Before calling overloaded main method");
        System.out.println("Result of calling overloaded main method from JVM called" + 
           "main method:"+main(10,20));
    }
    public static int main(int a,int b){
        System.out.println( "In overloaded main method" );
        return a + b;
    }
}
Output :
In JVM called main method
Before calling overloaded main method
In overloaded main method
Result of Calling overloaded main method from JVM called main method:30

So we can see from above example that 
- When we ran Application.java ,JVM called main method with following signature only
   public static void main( String[] args );
- We can have overloaded version of main method also.Here we had overloaded main             method with following signature
  public static int main(int a,int b);
- We can call overloaded main method just like any other method.In our example we called      overloaded main method from JVM called main method as below
  System.out.println("Result of calling overloaded main method from JVM called""main method:"+main(10,20));

So with this we learnt that main method just like any other method can be overloaded.Now let us see whether it is possible to override main method in java.

Can we override main method in java ?

Short answer is NO,we can not override main method in java.
Reason is very simple.As main method is static and we know very well that we can not override static methods in Java,hence main method could not be overridden. So what will happen if we will try to override main method in subclass.

Let us see with an example 
public class Application {
    public static void main( String[] args )    {
        System.out.println("Application class main method");
    }
}
public class AnotherApp extends Application{
   public static void main(String[] args) {
  System.out.println("AnotherApp main method");
   }
}
public class TestClass {
    public static void main(String[] args) {
  Application application = new Application();
  application.main(new String[1]);
  Application application1 = new AnotherApp();
  application1.main(new String[1]);
 }
}
Output :
Application class main method
Application class main method

So we can see from above example that 
- We defined main method in Application.java
- AnotherApp class extended Application class
- AnotherApp class also defined main method with exactly same signature.But we should note here
  that main method defined here in AnotherApp class is just another method and it is not a overriding
  Application class's main method.
- To prove that main method of AnotherApp is not overriding Application class's main method,we created
  TestClass,in which we tried to call main method's of Application and AnotherApp polymorphically as below
 Application application = new Application();
 application.main(new String[1]);
  
Application application1 = new AnotherApp();

 // In case main method would have overridden,main method of AnotherApp would have got called through below method call.
    application1.main(new String[1]);

But as we can see in output ,in both calls ,main method of Application class is called.

So with this we learnt that main method can be overloaded but can not be overridden in Java.

If you have any comment on the post,please post in comments section.

Thanks for reading!!!

How to SetUp Eclipse on Mac machine to run Java Programs

Dear Friends,

In this tutorial we will see how to setup Eclipse on Mac machine to run Java programs.So here are the steps :

My Operating System : OS X EI Capitan

1) Download latest stable version of Eclipse,which is Eclipse Mars  from following link

http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/mars/2/eclipse-jee-mars-2-macosx-cocoa-x86_64.tar.gz





Note : You can download the earlier versions also.Below is the link which has hyperlinks to all eclipse versions

http://www.eclipse.org/downloads/packages/


2) Unzip the downloaded file and we will see the eclipse application Icon placed at the same location where we downloaded the eclipse tar.gz file.



3) Now we need to install JDK.The latest version is JDK 1.8.

2.1) Download JDK 1.8 from below link

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

We need to download  jdk-8u91-macosx-x64.dmg from below options for Mac.


2.2 ) After downloading/saving jdk-8u91-macosx-x64.dmg file on system,we need to install JDK,for that double click on jdk-8u91-macosx-x64.dmg  and we will see following screen


2.3) As mentioned in above screen shot double click on the icon and we will get following screen



2.4) Click on Continue and we will see following screen


2.5) Click on Install and your installation will be done automatically and finally we will get following screen with success message


3) Now open your Eclipse by double clicking on eclipse icon that got created after extraction of.tar.gz file and give the location wherever you want to create workspace and click ok.


4) You will get following screen.





5) Close welcome screen and create a new Java Project by selecting File->New-> Project.. ->Java  Project. Give any name to project for example FirstMacProject and click Finish.



6) You will  get following screen



7) Create a package with name "in.blogspot.javaSolutionsGuide" and create a class with name "MyFirstMacClass".Add sysout with "Hello Mac" message in it.



8) Right Click on java file and select Run as -> Java Application


9) You will see output "Hello Mac" on console


 So with this we learnt how to setup Eclipse to run Java program on Mac machine.

 Thanks for reading !!!

Why we have private data and public getters setters to access them

It is common norm in Object oriented languages like Java to keep data which belongs to class as private and provide a public interface in the form of getter and setter method to access the data.

This wrapping up of data and methods which act on this data within single class has been named as encapsulation.In this post,let us try to understand what is the benefit we achieve out of keeping data private and with public getter ,setters to access data.



[Solved] - Cannot create a server using the selected type

Issue : User goes to New -> Server -> Apache -> Tomcat v<version> Server ,in the console of eclipse to create a server instance in eclipse,but gets message "Cannot create a server using the selected type"

as shown in below screenshot ,so user could not proceed with server definition.



    Solution : Try one or all of following 

    1) Go to Window–>Preferences–>Server–>Runtime Environments->Edit and correct path to the              tomcat directory.


2) Go to your workspace folder.You can find path to your workspace by going to File-> Switch Workspace->Other. 

3) Now Go to following directory <workspace folder>\.metadata\.plugins\org.eclipse.core.runtime\.settings

4) Delete org.eclipse.jst.server.tomcat.core.prefs

5) Delete org.eclipse.wst.server.core.prefs

6) Restart Eclipse.

Thanks for reading.

Share it people for whom you find this info useful.

What does main method do in Java? Why main method is public,static,void?

Lets try to understand, What does main method do in Java?

main method is entry point(like main gate of your house) of your stand alone java application.Having said that it means that if we have a Java project(Not a Web Project) which has many classes in it with lot of code(business logic),you need some starting point such that your code starts executing.main method is this starting point or entry gate,which then can call other classes code.
Lets take an example to check how main method gets called and how it calls other method
package com.test.main;
public class TestClass {
public static void main(String[] args) {
               System.out.println("In TestClass");
               System.out.println(new TestClass1().display());  // calling TestClass1 display method
}
}
package com.test.main;
public class TestClass1 {
        public String display(){
        return "In TestClass1";
       }
}
Let us run TestClass from command prompt or from within eclipse
command prompt :
java TestClass
Eclipse : Right click on class having main method or right click on project name ,then select Run as -> Java Applicaiton
Output :
In TestClass
In TestClass1
Additional Info :
1) If you right click on a class which does not have main method ,eclipse will not show you Run as->Java application option.
2) If you remove any of public,static,void or arguments of main method,it will not be identified by JVM, but it will be considered as overload of main method and hence will not be called by JVM.So we need to be sure that we are using correct signature of main method,if we want JVM to call this method and below are the possible signatures of main method :

Before Java 5 :

public static void main(String[] args);

After Java 5 :

public static void main(String... args);

Or

public static void main(String[] args);
Why main method is public,static,void and with String array argument?
Why main method is Public :

There are four access modifiers in Java viz. private,default,protected,public.

Class members : Instance variables + methods 

private : Class members with private access modifier can be accessed only from within that same class.

So what if main method would have been private?It could not be called by JVM which calls main from outside the class containing main method,but methods with private access are accessible only from within that class.

default : There is no such keyword as such "default",but class members without any access modifier have default access which is also called as package-private access,which means that such class members can be accessed from any class which are within same package as the class whose members we want to access.

So what if main method would have been defined with default level access,it could still not be called by JVM, as methods with default access can only be accessed from classes which are in same package.

protected : class members with protected access can be accessed from any class within same package plus from subclasses outside the package.

So what if main method would have been defined with protected access,it could still not be called by JVM,as methods with protected access can be accessed only from classes within same package and subclasses outside package.
public : class members with public access can be accessed from any class outside the class,be it classes in same package or classes in different package.
Now as JVM is sitting somewhere outside of classes of your project,so to call main method of your project,main method must have public access.
why main method is static
As main method is invoked by JVM and by that time(when JVM invokes main method) no object of class in which main method is defined exists,there should be some way to call main method.This is the reason main method has been forced by java specifications to be static.Now as static methods belong to class(and not objects),it can be called by JVM using class name.

why main method has void return type

As main method does not need to return anything to JVM,return type of main method is void.

What is the use of String array arguments in main method


main method accepts array of String.These are called command line arguments.
Consider following example :
package com.test.main;
public class TestClass {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println("In TestClass")
}
}
So if you are executing java program from command prompt as below :
java TestClass "hello"
Output will be :
hello
in TestClass
If you want to pass more than 1 argument,you can do like
Consider following example :
package com.test.main;
public class TestClass {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println("In TestClass")
}
}
java TestClass "hello" "Quora"
and output will be
hello
Quora
in TestClass
This was just an example.In real projects you can pass some relevant arguments which will be required to your application at start up.
For example ,you can pass name of the applicationContext file(xml) in application using Spring,which then can be used in main method to load applicationContext.
Hope this article was helpful.If you have any comments,feedback,please dont hestitate to provide same in below comments section.