Tuesday, 30 April 2013

W: GPG error: http://ppa.launchpad.net precise Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6AF0E1940624A220

It all started when i executed -
sudo apt-get update 
on my Ubuntu 12.04(Precise Pangolin). After fetching the required updates it showed me an error at the bottom - W: GPG error: http://ppa.launchpad.net precise Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6AF0E1940624A220

Screen-shot for the same is given below -

Clearly we need to download the key from Ubuntu key server.

Things to check before you see Approach 1 and 2.
  1. Open the file ~/.gnupg/gpg.conf with the editor.
  2. From the terminal gedit ~/.gnupg/gpg.conf
  3. Go to 116th like
    keyserver hkp://keys.gnupg.net
  4. Comment this out and add line above it so the setup now looks like
    keyserver http://keyserver.ubuntu.com
    # keyserver hkp://keys.gnupg.net
    # keyserver mailto:pgp-public-keys@keys.nl.pgp.net
    # keyserver ldap://keyserver.pgp.com
  5. Save the file.

Trying Reset(Did not help. Same error persisted)

Enter the following command on the terminal - 
sudo rm /var/lib/apt/lists/* -vf
and then update your system using following command - 
sudo apt-get update && sudo apt-get upgrade

  • 1st Approach(Did not Work for me)

    Run the following command -
    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6AF0E1940624A220This did not solve my problem. I got connection timed out.
    Generally Ubuntu key-server uses port 11371 which may be blocked by tour firewall. So you can use 80 as the port -
    sudo gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 6AF0E1940624A220

    But even this did not solve my problem -
    Errors i got by following both methods in this approach are in below screen-shot.


    Note :  Here if you are getting Connection refused then this may be a proxy problem. Check if you are behind any proxy or firewall.

  • 2nd Approach(Worked for me)

       If the command are not doing it for you, you have to do it on your own. After a long research on this problem i finally decided that the best thing to do was manually download the key and add it.This is how i did it.






    Go to Ubuntu Key-server(Click here). Here you can search your key. In my case it was 6AF0E1940624A220. Note while searching for key pre-append the key with 0x. So search for 0x6AF0E1940624A220


    Click on the link provided in the pub section.

    Copy the whole text(highlighted in below screen shot) from the page and save it in a file(say filename is key1).



Once you have copied the data to file. Save it. Then run the following command
sudo apt-key add key1

You will get an "OK" response.

aniket@aniket-Compaq-610:~/Desktop$ sudo apt-key add key1
[sudo] password for aniket:
OK


And you are done. Repeat the procedure of other keys that might be missing.
Then you can run
sudo apt-get update
and you will not get any error. Update happens smoothly. Do let me know if you still have any doubts.

Related Links

Collection in Java

 What is Collection?

 Collection if we go by name means group of some entities. From a bit more technical perspective it means an object that groups multiple elements into single unit.Collections are used to store, retrieve, manipulate and communicate aggregate data.

Collection framework in Java

    A collection framework is a unified architecture for representing and manipulating collections.All collection frameworks contain the following - 

All of the collection framework is represented by the following picture -

Each of the above will be taken individually and explained but lets take one example to understand Collection frameworks.

First thing to note is that Collection interface is the top most entity in the entire Collection tree.Yes it is an interface and all other entities in Collection(List,Set,Queue) implement this Collection interface.Collection interface also implements an interface called Iterable which allows us to iterate over the elements stored in the collection but do not worry about it for now.We will explain it separately.
        If you see above picture List is a Collection.Note again that List is still an interface and multiple implementations of it are possible. Example we can have ArrayList, LinkedList, Stack, Vector etc. Each concrete implementations just mentioned will have different Algorithms associated with them.

Note :  Map interface and it's concrete implementations do not form a part of Collections i.e Map interface does not implement Collection yet it is a part of Java Collection framework. Also since Map interface does not extend Collection interface(which in turn implements Iterable interface) Map cannot be directly iterated over it's elements. There is another way of-course but we shall see it later.

Collections summed up!





Saturday, 27 April 2013

Installing Compiz On The Unity Desktop On Ubuntu 12.04 (Precise Pangolin)

Compiz is a tool to create various Desktop effects in various Linux distros. Desktop cube, Water effect, Wobbly windows are some of the effects. It uses OpenGl library as an interface to the graphics hardware.

Installing compiz

   Open your terminal(ctrl+alt+t in Ubuntu) and type in the following command - 

sudo apt-get install compiz compizconfig-settings-manager compiz-fusion-plugins-extra compiz-fusion-plugins-main compiz-plugins

Configuring CompizConfig settings manager

   Open CompizConfig settings manager by searching for ccsm on Dash.
Scroll down to Desktop section. Click on Ubuntu Unity Plugin.


Note : If you are not able to launch ConpizConfig Settings Manager from Dash you can simply type ccsm in terminal to open it.

Next click on the Ubuntu Unity Plugin. Inside it make sure Enable Ubuntu Unity Plugin check-box is ticked.


Click Back to go to the main menu. Now you can choose which ever effects and plugins you wish to enable/Disable.


Enabling Desktop Cube

   By default you will have Desktop Wall enabled. In your CompizConfig Settings manager tick the Desktop Cube and Rotate Cube options under Desktop section.

Now go to General section and click General Options.


In it go to Desktop Size Tab and select what sizes you prefer. By default a cube will have 4 vertical side, you can change it to the value you want.


Now go back to main menu by clicking Back button. You are now all set for Desktop Cube now. Check it's working by clicking combination ctrl+alt+left/right. You can also use ctrl+alt and rotate using mouse.
Following is a screen shot from my Ubuntu 12.04. 


Enabling Wobbly Windows Effect

    This is again very simple. In the main menu go to Effects section. Here tick the Wobbly Windows check box and you are all set. 

Drag some windows to see the effect. Following is again a screen shot of Wobbly Windows effect.



Note : You may get some notifications to disable some features while enabling some. As i mentioned previously for example you wish to enable Desktop Cube Compiz will ask you to Disable Desktop Wall first. So act accordingly.


How to disable Pidgin Notifications in Ubuntu?

After installing Pidgin most users complaint about the constant notification pop-ups. Yes they may become irritating at some point of time.There is an very easy way to disable these notifications.

To see how to install Pidgin refer the earlier post on How to Configure Pidgin on Ubuntu?

Notifications look something like below -


To remove these constant notification pop-ups do the following -
 In Pidgin go to Tools -> Plugin or just press crtl+u

 Plugins window must now open. Select the plug in shown in the following picture and select configure plugin



Now just Un-check the check box corresponding to Buddy signs on.
Picture for the same is as follows -

And you are Done :)


Friday, 26 April 2013

How to configure Pidgin for Google Talk in Ubuntu?

A lot of beginners face this problem. Specially people using GTalk on Windows find themselves with no chat client on Linux. Let me explain how to configure your Pidgin with Google account -

To install Pidgin open the terminal and type in the following Command -
sudo apt-get install pidgin

After you install it you can directly launch it from your Dash Home by searching for pidgin or just type the following command in the terminal -
pidgin &

Note :  & after the pidgin command is just to inform the terminal to run the process in background. This can be used for any process you wish to tun in the background.

Once you launch Pidgin go to
Accounts ->Manage Accounts -> Add

In Basic tab set the settings as shown in the following image -
 

Note :  If you are using Google's 2 Step Verification you need to generate password for this application. If you don't know about this or haven't set it up you can proceed.

Next in the Advanced tab set the fields as show in below image -


You can set proxy in the Proxy tab if you are using any proxy. Inside it you will have many options like manually setting your proxy or using Gnome Proxy or No proxy at all.

Just click on Add button and you are done.

Note : Above images are from modify account rather that Add new Account but the settings remain the same. Only difference being you will see a Add button instead of Save button at the bottom.

Note : Sometimes buddy list may not show up. This is a bug. Just Exit pidgin and restart again.
What i would recommend is do as follows -
Open the terminal and type
killall pidgin
and then start it again using -f flag
pidgin -f

How to check your Ubuntu and Unity version?

There are two ways to check your Ubuntu version -
  1. Through System settings
  2. Command Line(Terminal)

Using System settings

     You can check Ubuntu version by going to -
     System settings -> System ->Details
You can see below screen - 
From here you can change default applications, view removable media etc.

Using Command Line(Terminal)

  Just open your terminal and type in command -
  lsb_release -a

You can see output as follows

Checking Unity version

    Checking unity version is again fairly simple. Just open the terminal and type in the command  
unity --version
You will then see output as follows - 

What are the Meta, Super, and Hyper keys in Linux/Unix?

Meta, Super and Hyper keys are referenced most often in various Linux Distros but many users are unaware what these really are.So let me explain each -


  •  Meta :
    The Meta key is not found on modern keyboard, it's use is sometimes emulated with AltGr (on some international layouts) or the right Alt key on the others. In addition:
    1. Sun keyboards have a meta key () as well
    2. Emacs calls Esc the Meta key
  •  Super :
    The Super key is equivalent to the windows logo key or the (command) key. In Ubuntu, it's just another name for the windows logo key.
  • Hyper :
    Hyper is the fourth (counting Ctrl) and last modifier on the Space cadet keyboard. In Ubuntu, its function is undefined (I think), but it can be mapped, as in the screen shot above, to the windows logo key, should it be needed
Though above are default setting you can change the mappings.
I am using Ubuntu 12.04 LTS and in this we can change this mapping from

System Settings -> Keyboard Layout -> options -> Alt/Win key behavior.



Wednesday, 24 April 2013

Linux Command Line Cheat Sheet

Bash Commands

 uname -a Show system and kernel
head -n1 /etc/issue Show distri­bution
mount Show mounted filesy­stems
date Show system date
uptime Show uptime
whoami Show your username
man command Show manual for command

Directory option

pwd Show current directory
mkdir dir Make directory dir
cd dir Change directory to dir
cd .. Go up a directory
ls List files

ls commands

-a Show all (including hidden)
-R Recursive list
-r Reverse order
-t Sort by last modified
-S Sort by file size
-l Long listing format
-1 One file per line
-m Comma-­sep­arated output
-Q Quoted output

Search Files

grep pattern files Search for pattern in files
grep -i Case insens­itive search
grep -r Recursive search
grep -v Inverted search
grep -o Show matched part of file only
find /dir/ -name name* Find files starting with name in dir
find /dir/ -user name Find files owned by name in dir
find /dir/ -mmin num Find files modifed less than num minutes ago in dir
whereis command Find binary / source / manual for command
locate file Find file (quick search of system index)

File operations

touch file1 Create file1
cat file1 file2 Concat­enate files and output
less file1 View and paginate file1
file file1 Get type of file1
cp file1 file2 Copy file1 to file2
mv file1 file2 Move file1 to file2
rm file1 Delete file1
head file1 Show first 10 lines of file1
tail file1 Show last 10 lines of file1
tail -f file1 Output last lines of file1 as it changes

Process management

ps Show snapshot of processes
top Show real time processes
kill pid Kill process with id pid
pkill name Kill process with name name
killall name Kill all processes with names beginning name

File Permissions

chmod 775 file Change mode of file to 775
chmod -R 600 folder Recurs­ively chmod folder to 600
chown user­:g­roup file Change file owner to user and group to group

Tuesday, 23 April 2013

Interfaces in Java

Having learned what are abstract classes and functions we are all set to dig a bit more into polymorphism. Interfaces are based on these two features.



We saw Java does not support multiple inheritance to avoid the problem of Deadly Diamond of Death. To provide functionalities that multiple inheritance support Java provides Interfaces. Interfaces are entities just like classes. We define them one per file and file name must be same as the interface name.

   Synatx for creating an interface is as follows -

    public interface interfaceName{ //code goes here}

Example of an interface is as follows -

public interface Animal{
    public void move();
}


Couple of things to note in Interfaces
  • All functions in an interface are public and  abstract by default. This means all interface contains is function prototype. It's concrete implementation will be in the class which implements it.Note the semicolon after the function. No implementation.
  • For sub class inheriting from super class we say classA extends classB whereas for interfaces we say classA implements interfaceB.
  • You can define variables in interfaces but they are final and static by default.
  • You cannot create objects of interfaces. You can think them as abstract classes for your understanding because after all it contains abstract functions and we know that non-abstract classes can't have abstract function. only abstract classes can.
 Note : If you have an abstract class will all abstract methods as per convention you should go for interface rather than abstract class (As per Java specs).
Let take a look at any class that may implement interface defined above.

 public class Dog implements Animal{
    public void move() {
        System.out.println("Moving..");
    }

    public static void main(String args[]) {
        Animal animal = new Dog();
        animal.move();
    }
}


output Moving..
as expected.


Note in above code we have made use of polymorphism. We are using a Animal reference to refer to a Dog object. All rules of polymorphism will follow.

Note :  We can use interface as polymorphic references in method arguments and return types. Meaning you can have a method that return Object of type Animal. At runtime you can return any class Object that implements Animal interface.


Why are the advantages of using interfaces?

  • A class can implement multiple interfaces but can extend only one class.
  • Interfaces can be used across inheritance trees. This means a class from one inheritance tree can implement interface from another inheritance tree.
  • Advantages of polymorphism follows.
  • In later parts of tutorials on Java you will realize generics , design pattens etc depend on this.

One of the OOP principle is "Code for the interface not for implementation" meaning always thing how to design your interface then to worry about your implementation.

Note :  If you have abstract class with all abstract methods (no non-abstract methods) it is better to go for an interface.

Sunday, 21 April 2013

Why do we use Linux?


We tell people we use Linux because it's secure or it's free or it's customizable or it has excellent community support.
     But all of this is just marketing bullshit. We tell that to non Linux users because they wouldn't understand the real reason and when we say those false reasons enough we might even start to believe them ourselves.

   But deep underneath , the real reason remain - We use Linux because it's fun! It's fun to tinker with your system. It's fun to change all the settings, break the system, then have to go back to recovery mode to fix it.It's fun to have a 100 distros to choose from.It's fun to use command line.
    Let me say that again - it's fun to use command line.No wonder non Linux users won't understand.

     The point with Linux fan is we use Linux for it's own sake.Sure, we like to get work done. Sure, we like to be secure from virus.Sure, we like to save money but these are only the side effects.What we really like is playing with the system, poking around and discovering fascinating facts about the software that lies underneath it.
 

Saturday, 20 April 2013

Interview Question #9 Why multiple inheritance is not supported by Java?

Multiple inheritance has a problem known as The Deadly Diamond of Death.

Refer to the following diagram to understand The Deadly Diamond of Death-


Explanation -  

     Suppose you have class C which extends two classes A and B.Lets say A and B both have a function with same prototype eg. public int getData(). Now if we create an object of class C and call the function i.e ObjC.getData() which function will be called? Decision is ambiguous unless we have set some rules and priorities. To avoid such ambiguity Java does not allow multiple inheritance.


A language that allows Deadly Diamond of Death can lead to some ugly complexities, because you have to have special rules to deal with the potential ambiguities.

Java is designed to be simple. Java (unlike C++) protects you from having to think about Deadly Death of Diamond.

To provide similar functionality Java provides interfaces.
So Java can implement two or more interfaces but can extends only one super class.

Friday, 19 April 2013

Abstract classes and functions in java

Abstract classes are the basis for what is yet to come - interfaces. So lets understand what are abstract classes and why are these important.

In the tutorial on polymorphism we saw how reference of type Animal can be used to point at object of various types like Cat,Dog,Lion,Wolf,Hippo etc. 
 
Just to revise things we now know we can say -

Wolf aWolf = new Wolf();


or we can also say -

Animal aHippo = new Hippo (); 


 but what happens when we do -

Animal animal = new Animal();

Perfectly Valid Java syntax. But what does this Animal look like?

This only makes sense when we have some concrete Animal like Dog,Cat etc . In short it does not make any sense to create objects of class Animal or in other words it does not  make any sense to use new() operator with Animal class. In this case we declare the class as abstract. Such abstract classes are used in polymorphism.

Syntax for making abstract classes
abstract public class Animal

Note: Though we cannot create objects of abstract classes we can use them as reference (like in Polymorphism).

Also remember you cannot use functions of subclass through super class reference(polymorphism) unless the function is defined in the super class. But also we cannot implement the function in the super class as the implementation will be subclass specific( eg different implementation for Dog,Cat etc). To sum thing up, for using polymorphism effectively we need function declared in super class and it's concrete implementation in the subclass. Hence we define the functions to be abstract.

Syntax for abstract function -
abstract returnType functionName(Arguments);

Note : No Method body. No brace brackets. Just a semicolon after method declaration. 


 Observe the semi colon after function prototype.  We just declare it and put a semi colon after it. Implementation of this function will be in the first concrete class which implements this abstract class. There is no use of abstract class if no class implement it(i.e if there are no subclasses of abstract class).

Note: There can be non-abstract functions in abstract classes but there can never be abstract functions in a non-abstract class. So if you have abstract functions you must declare your class to be abstract.

Also note there is no such thing as abstract variables. In java we just have abstract classes and abstract function.

Few points to note

  1. A non abstract class cannot have abstract method. If a class has abstract method it has to be made abstract.
  2. We cannot instantiate abstract classes.
  3. An abstract class can have non abstract methods .
  4. If your abstract class has all abstract method it is better to go for an interface instead.









Thursday, 18 April 2013

Polymorphism in Java

Before we begin learning what is polymorphism and how is it useful let us step back and see how references and objects are created in Java.

Consider following line of Code

Dog myDog = new Dog();

It may look like a simple instance creation but includes multiple statements.
So when we say Dog myDog = new Dog() what actually happens is as follows - myDog is a reference(or you can visualize it as a pointer) which can refer to an object of type Dog. Note this reference is on the stack and not on the heap. When we use the new operator object is allocated memory on the heap and the reference points to this object. This is when we say object is created.

Important point to note here is that the reference type and the object type are the same i.e both are of type Dog.

But with polymorphism reference type and the object type can be different!!

All of polymorphism can be stated in a single line. Do keep this statement in mind -
"Super class reference for subclass object"

This means reference type mentioned above can be any super class of the subclass object to which it is pointing.

So if we have Class Dog extends Animal which means Animal is the super class of Dog then we can say
Animal myDog = new Dog(); 

To explain this further let us take an example -
Lets say we have an array of type Animal 

Animal[] animals = new Animal[5];

This means we have 5 references of type Animal
Now if Dog,Cat,Lion,Tiger,Wolf are subclasses of Animal then we can say -

animals[0] = new Dog(); 
animals[1] = new Cat();  
animals[2] = new Lion(); 
animals[3] = new Tiger(); 
animals[4] = new Wolf(); 

So we have multiple object references in the same array. Realizing the usefulness of polymorphism yet? Well there is more to come.
    
Now lets say we do something like -

for(int i=0; i< animals.length; i++)
{
    animals[i].eat();


What happens now?At runtime JVM will figure out that animals[i] say animals[0] refers to object of type Dog and call the .eat() function in Dog class. But there is a catch .eat() function must be defined in Animal class.  You must define a function in the super class and then you may override it in sub class according to your implementation.

You can use polymorphism in passing arguments in a function as well as while returning values.
Example -

public void feedAnimal(Animal animal){//implementation}
or
public Animal getPet(String sound)
{
   if(sound.equals("bark"))
    {
         Dog myDog = new Dog();
         return  myDog;
     } 
    // more code 
}

I hope you get the point of polymorphism by now. You need not create separate function getPet() for each type of Animal or you need not create feedAnimal() function for each type of Animal.



Polymorphism will be used in a lot of codes without mentioning. We will refer to this post whenever possible but keep this concept in mind.

Sunday, 14 April 2013

Interview Question #8 What happens when a class implements two interfaces with same method?

This is a very interesting question. If you still don't get it let me give an example to explain it further -
We have two interfaces  - InterfaceA and InterfaceB. Then we have a concrete class which implements these interfaces.

Code of InterfaceA

package testCodes;

public interface InterfaceA {
    public void color();
}


Code for InterfaceB

package testCodes;

public interface InterfaceB {
    public void color();
}


Code for class ConcreteClass

package testCodes;

public class ConcreteClass implements InterfaceA, InterfaceB {
    public void color() {
        System.out.println("Red");
    }
}


Note that though we have same method in both interface we need to implement it only once in our concrete subclass. So it does not matter if we have two interfaces with same method. It will be implemented only once.

Problem arises when.....

   Problem will arise when there are two interfaces having method with same name and parameter but different return type. When a class will implement these two interface it will have to implement these two methods with same name and parameters but different return type. But this is not allowed. JVM will not allow this code to be compiled. Functions can have same name(function overloading) but they must have different signatures(different parameters.)



Inheritance in Java

When we said Java is an Object oriented programming language we mentioned some of it's features like Inheritance, polymorphism, Data Encapsulation etc.In this tutorial we will see what is inheritance, why do we need it and how do we use it in Java.

Why do we need inheritance?

Lets say you want to make different classes like Dog, Cat, Lion, Tiger etc. Each class will have some common attributes like food,picture,location etc. and some common methods like eat(), makeNoise() etc.
To avoid duplicate code we create a common class with common code(variables and functions) and then make other requires classes as subclasses of animal class.

So we need inheritance to avoid duplication of code and make our program more sensible and understandable.

Understanding inheritance in Java

   It is very simple to use inheritance in Java. Keyword that we use in this context is extends. A subclass extends a super class.Before looking at how to actually use it it is very important to decide when can we use inheritance? There is a simple 

IS-A Test : When ever you want to decide if inheritance is applicable, You can always use this test. So in above case we say Dog is an Animal, Tiger is an animal.. and so on.

 Let us see now how do we actually use inheritance in Java..

First we write class  Animal which is the super class.

package animalsData;

public class Animal {

    public String food;
    public String noise;

    public void run() {
        System.out.println("Running");
    }
}

Then we write the subclass Dog

package animalsData;

public class Dog extends Animal {
   
    public void eat()
    {
        System.out.println("Eating bone \n");
    }
}

and finally the Coordinator class to run our code.

package animalsData;

public class Coordinator {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.run();
    }
}
output : Eating bone
             Running

eat() is a function  of class Dog whereas run() is a function of class Animal which is inherited by class Dog.
We can inherit any such class by using extends keyword. Note that Java does not support multiple inheritance. This means that a single subclass cannot inherit from multiple subclasses. To avoid duplicate data in Java we can also use interfaces which we will see in our next tutorial.

Remember to apply IS-A test to indentify inheritance.

If Class 'X' extends Class 'Y' then Class 'X' IS-A 'Y'. This holds true in the entire inheritance tree. So if 'X' extends 'Y' and 'Z' extends X then 'Z' IS-A 'Y'.

Why multiple inheritance is not supported in Java?

  Java does not support multiple inheritance for the sake of simplicity for which it is built. Consider the Diamond problem of multiple inheritance - 



We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C? Here we have an ambiguity.

Java provides means to tackle this and that is interfaces.
We will see interfaces in our next tutorial. 

Saturday, 13 April 2013

Understanding equals() and hashCode() methods in Java.

You must have heard that whenever you write a class of your own, you must always override equals() and hashCode()  methods.Lets us understand these methods and why it is important to override these methods.

Both these methods are defined in the Object class which is the top most class in the inheritance hierarchy. All classes implicitly extend object class and hence all class have these methods. Hence you must override these methods to suit your class requirements. Why and where they are used - we will come to it in some time.

Understanding motive behind the functions

     .equals() method is used to compare two objects. Since you only know the structure of your class you are the only one who can implement the comparison logic. For more details on this you can refer post on .equals() method. 

   .hashCode() method is used to return a unique integer value for each unique object. This unique number is used in various cases like while storing the objects in Map etc.So the motive is if two objects are same i.e if they return true on .equals() method then they must also return the same hashcode. So logic similar to .equlas() must be added to return a unique integer(hashcode) for unique objects.

Note : Reverse is not true. If two objects return the same hashcode they may or may not be same objects.

Default Implementation

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

public int hashCode() {
    return VMMemoryManager.getIdentityHashCode(this);
}

Summary

   Both your equals() and hashCode() are implementations of the programmer. Make sure to use same attributes in both these function. Whenever you override equals() method make it a point to override
hashCode() too. Key point to remember is if two objects are same they must return true from .equals() method and also they must return same hashcode from .hashCode() method.

If you are using an IDE like eclipse you can directly generate hashCode() and equals() just like generating getter and setter methods.Then add your overriding logic. Here is a snapshot of eclipse - 


Difference between using == operator and equals() method in Java

This is a very basic question and most frequently asked in interviews.  It is very important to understand the difference before you write complex Java programs.

   Let us start with == operator first.We know this is a comparator operator but the question is how does it actually work and how is it different from .equals() method?

== operator

       == operator compares whether the two references that are compared point to the same object or not. Result will be true if both references point to the same object else it is false.Lets take an example to understand this better.

package testCodes;

public class Test {
   
    public static void main(String args[])
    {
        String name1 = new String("John");
        String name2 = name1;
        if(name1 == name2)
        {
            System.out.println("Both references point to the same object \n");
        }

        else

        {   

            System.out.println("Both references point to different objects \n");

         }
    }
}

output : Both references point to the same object

In above code we create a String object name1 with value John. Then we create a reference name2 and make it point to the same object created earlier. Then we compare both references and as both references point to same object with value John == operator return true and hence we get our desired output. Lets say we do something like below -

String name1 = new String("John");

String name2 = new String("John");

if(name1 == name2)

{
    System.out.println("Both references point to the same object \n");

} 

else

{   

    System.out.println("Both references point to different objects \n");

}


 output : Both references point to different objects

As expected if we create two different objects, though both contain the same value John we get false from == operator as references point to two different object and else part is printed.

Note if you do something like

String name1 = "John";

String name2 = "John";

if(name1 == name2)

{
    System.out.println("Both references point to the same object \n");

} 

else

{   

    System.out.println("Both references point to different objects \n");

}


 output : Both references point to the same object

This is because when you don't create explicit objects, Java internally stores this data in a pool on the heap and any string created with  John as the value will point to this data in the pool.This is data is stored in an object called interned String objec. Hence they refer to same object and == return true. For more details refer the tutorial on Difference between String Object and String Literal.

To sum this up == operator check whether the two references which are being compared point to same object or not.

.equals() method

     This method is very much straight forward. It will simple check if the two objects are internally same or not. In case of String it will check if both objects have same value or not. If you are creating an object of your own you must override this  method to handle equality.

The default implementation of .equals() method is as follows -  

public boolean equals(Object other) 
     return this == other;   

Yes that's right! By default .equals() method is same as using == operator. Hence for custom classes you must override this method by adding logic to compare  your objects.

For example if you are making a Coordinate class which has x and y coordinates as instance variable you may override .equals() method as follows - 


public boolean equals(Object other) 
     if((Coordinate)other.x == this.x  && (Coordinate)other.y == this.y)
     {
         return true;
      }
    else
     {
        return false;
      } 

Above code just compare if x coordinate and y coordinate of both coordinate objects are same. If yes then the objects are similar and true is returned else false is returned. I hope you get the point.Also don't forget to override hashCode()method. We will learn this hashCode() method and why to override this in next tutorials but for now just keep that in mind.



Summary


    == operator check whether both the objects compared point to the same object or not while .equals() method is overridden and implemented by the programmer. .equals() method is provide to provide functionality to compare similarity of two objects. If it is not overridden then it is same as using ==  operator.


Related Links




Difference between string object and string literal

Background


Everybody is familiar with Strings as a data type. Strings can be used as literals 
  • String name = "John";
or they can be used as objects
  • String name = new String("John");
They may behave the same way and may serve our purpose equally but do we really understand what are the differences between the two. How both the Strings behave and how would it affect our programming logic.

Lets understand the differences between the two and when we would use each....

Note 1: First thing everyone must remember is that Strings are immutable i.e they cannot be changed or altered. Of-course you can perform operations on it like substring()  but this will give you entirely different String. Point here is that once you create a String you cannot modify it.

Using String as a Literal

    You create a String literal simply as below - 
  • String name = "John";
  When you create a String literal it is stored in PermGen area of the Heap(The PermGen normally consists of the string literal pool and loaded classes).

Note 1: From Java 7, String pool is moved from permgen to normal heap area. This was primarily because permgen ares is of fixed size and may led to "java.lang.OutOfMemoryError: PermGen space" finally leading your JVM to crash.  

Note 2: From Java 8 there is no permgen area. All classes are loaded in normal heap are only. 

So now when you create a String as a literal reference point to an object called interned String object which is created in the PermGen of the Heap i.e name will refer to an interned String object. This means, that the character sequence "John" will be stored at a central place and whenever the same literal "John" is used again, the JVM will not create a new String object but use the reference of the 'cached' String.

Note : String literals are interened by default.


To clarify this further lets take an example - 

String name1 = "John";
String name2 = "John";
if(name1 == name2)
{
   System.out.println("Both point to same object \n"); 
}
if(name1.equals(name2))
{

    System.out.println("Both have same value \n");
}

output :
 Both point to same object
 
Both have same value

Hope you get the point now. Object is the same (created once in PermGen area) and is referred every time a literal with same value is referred. So to summarize objects are same and obvious the value too.

Lets understand creating String as an object now.

Using String as an Object

     Creating String as an object is as follows -
  •    String name = new String("John");
Here name  is an individual instance of the java.lang.String class. This object is created just as other objects in the heap.Two objects created with new keyword will always point to two different objects even if their values are same.
Let's take an example to understand this - 


String name1 = new String("John");
String name2 = new String("John");
if(name1 == name2)
{
   System.out.println("Both point to same object \n");
}
if(name1.equals(name2))
{

    System.out.println("Both have same value \n");
}

output :
Both have same value           

As expected we did not get  Both point to same object as our output as both objects are entirely different and are allocated separate memory.But note that they have same value i.e  John and hence we got the output as Both have same value.


As I mentioned earlier String literals are interened by default. But if you need to intern an String Object you need to call  intern() on it.

        String name1 = new String("John").intern();
        String name2 = new String("John").intern();
        if(name1 == name2)
        {
           System.out.println("Both point to same object \n");
        }
        if(name1.equals(name2))
        {
        
            System.out.println("Both have same value \n");
        }
output :
 Both point to same object
 
Both have same value

String pool values are garbage collected

Irrespective of which version of Java you use and where you String pool resides, values of String pool are eligible for GC and follow normal GC rules i.e if they are not reachable from from program GC roots then they are eligible for garbage collection.

Though this is true String literals may not be candidates for GC in most of the cases.  String literals will always be accessible from GC roots as the code will have implicit reference to it. For example a method that uses a string literal will always have a reference to it. So this literal will be garbage collected only if that code referencing it is GCed and that is not possible unless the class/code is dynamically loaded.

If the literal was defined in a class that was dynamically loaded (e.g. using Class.forName(...)), then it is possible to arrange that the class is unloaded. If that happens, then the String object for the literal will be unreachable, and will be reclaimed when the heap containing the interned String gets GC'ed. 

Also this happens on full GC.

Summary

   To summarize what we learned above -  When we create String as a literal it is created as an interned object in PermGen area of the Heap (Normal area of heap from Java 7) and will be referred every time a  literal is created with same value. On the other hand separate object is created every time String is created as an object using new keyword.


Related Links

Sunday, 7 April 2013

MCQ #13

Question) Given this code what is the output?

class Exam
{
    protected String level = "Easy";

    public void printLevel()
     {
         System.out.println(level);
      }


Class IITExam extends Exam
{
     private String level = "Difficult";


 IITExam  iitExam = new IITExam();
 iitExam .printLevel();
 
Options)


  • Difficult
  • Easy
Answer) Easy

Explanation) Methods can be overridden not the attributes. Rest is self explanatory.

MCQ #12

Question) Given this code what is the output?

boolean b = false;
if(b = true)
{
   System.out.println("Yes");
}

Options)

  • Yes
  • Nothing is printed
Answer) Yes

Explanation) If you are puzzled looking at the output observe the code again. Inside the if condition you have an assignment operator(=) and not a equality operator(==) . Assignment will always be true regardless of anything and hence the code inside the for loop will always execute. Hence the output will be "Yes". Also note that b will be set to "True".

Saturday, 6 April 2013

MCQ #11

Question) Are you allowed to have more than one top level (non inner) class definition per source file?

Options)

  • No
  • Yes
Answer) Yes

Explanation) Yes you can have multiple top level class definitions per source file. Yeah, it's also true that the source file name must be same as that of the class name. To resolve both these constraints Java states some basic rules which are -
  1. Out of the multiple top level classes defined only one can be public.
  2. Source file name must match this public class name.

Interview Question #7 What is final in java?

A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

If you want a variable to be owned by the class and not by it's individual instances(objects) and also you want the value of the variable to be constant you can declare it as static and final both.

 For Example
       private final static String name = "JavaForGeeks";

The concept is interpreted a bit different way for Objects, Collections. You can change the data inside the object/Collection but cannot make the reference(which is final) point to different Object.

For example

public class HelloWorld {
   
    String greetings;
   
    public String getGreetings() {
        return greetings;
    }
    public void setGreetings(String greetings) {
        this.greetings = greetings;
    }

}


Even if the HellowWorld instance is defined final you can call setter method of it's data.

    public static void main(String args[]){
        final HelloWorld hw = new HelloWorld();
        hw.setGreetings("test");  //allowed
        //hw = new HelloWorld(); //not allowed
    }



Same goes for Collections

    public static void main(String args[]){
        final List<String> myList = new ArrayList<String>();
        myList.add("Test");    //allowed
        //myList = new ArrayList<String>();    //not allowed
    }

 
t> UA-39527780-1 back to top