Wednesday, 16 March 2016

What is the problem if you try to print object you created in System.out.print();?

Note : Interviewer gave me the code snippet given below and asked the questions :
1. Will there be any problem if I print e1 as shown in code? 
2. If there is any problem then how will you solve it?
-----------------------------------------------------------------------------------------------------
If we directly print the object in java using System.out.print() it will give hashcode value as output. Lets see it with the help of an example

public class Emp {
int empId;
String empName;

Emp(int id, String name){
this.empId=id;
this.empName=name;
}

public static void main(String[] args) {
Emp e1 = new Emp(54110, "Mukesh");
Emp e2 = new Emp(12243, "Rajnish");
 
System.out.println(e1);

}


}

OUTPUT :  Emp@3e25a5   
So what we get here is the hashcode value of the object. But we expected it to print the values contained by the object e1, something like this :
     54110, "Mukesh"
Isn't it?

How to overcome this problem?

override toString() method. Java compiler internally calls toString() so overriding this method will help us get the desired output as shown below 

public String toString(){
return name;
}

public class Emp {
int empId;
String empName;

Emp(int id, String name){
this.empId=id;
this.empName=name;
}

public String toString(){                                                                        
return empId + " - "+ empName;                                                             
}                                                                                                                           

public static void main(String[] args) {
Emp e1 = new Emp(54110, "Mukesh");
Emp e2 = new Emp(12243, "Rajnish");
 
System.out.println(e1);
System.out.println(e2);

}


}

OUTPUT :
54110 - Mukesh

12243 - Rajnish

Now we get what we expected. This is the magic of overriding toString() method. 


You may also like to read:



Monday, 14 March 2016

Switch case puzzle 1

public class CheckInt{
    public static void main(String[] args){
    int choice = 6;
   
    switch(choice){
        case 3 : System.out.println("Rule 3 is applicable");
        default: System.out.println("Wrong choice");
        case 9 : System.out.println("Rule 9 is applicable");
        case 1 : System.out.println("Rule 6 is applicable");
        case 10: System.out.println("Rule 10 is applicable");
    }
}
}

What is the output of the above code ?

OUTPUT :
Wrong choice
Rule 9 is applicable
Rule 6 is applicable
Rule 10 is applicable

REASON :
As you can see the value of choice is 6, and case 6 is not present so default case* statement would be the first to get executed. And since default doesn't have break statement after it prints  "Wrong choice" it would go on executing all the case one by one that follows until it finds break or it comes out of the switch.
* Default case is executed if there is no matching case present and if you haven't written default case in your code then the program gets executed with no output.

Now look at the code below, it contains break statement.

public class CheckInt{
    public static void main(String[] args){
    int choice = 6;
   
    switch(choice){
        case 3 : System.out.println("Rule 3 is applicable");
                 break;
        default: System.out.println("Wrong choice"); 
                 break;
        case 9 : System.out.println("Rule 9 is applicable");
                 break;
        case 1 : System.out.println("Rule 6 is applicable");
                 break;
        case 10: System.out.println("Rule 10 is applicable");
                 break;
    }
}
}

OUTPUT :

Wrong choice

* Change the value of choice as 1 and you will get output as  Rule 6 is applicable.

This Output is the result of break statement.

Friday, 11 March 2016

Why String is immutable in java?

A very well known fact about java's String is that it is immutable. It means that once a String object is created it cannot be modified. Let's understand how?
For example,
String mobile = "Samsung";

Here we can see that a new String object with name Samsung is created and this object is referenced by variable named mobile.
And this object would be stored in a String constant pool

Now change the above example as shown below,
String mobile = "Samsung" + "Duos";
Again a new object is created with name SamsungDuos and is stored in the pool. And mobile variable now has reference to SamsungDuos instead of Samsung. But Samsung object still remains in the pool but with no reference.

Note : We have both Samsung and SamsungDuos object in the String Constant Pool.

-------------------------------------------------------------------------------------------------------------------------
Suppose you again write, say
String company = "Samsung"; && 
String handset = "SamsungDuos";
This time as the Samsung and Samsung Duos object already exist in the pool so the same object would be used instead of creating new object. company would  have reference to Samsung object and Samsung Duos to handset respectively.

Note : Samsung Duos object is now referred by both mobile and handset variable. 
--------------------------------------------------------------------------------------------------------------------------

Think you have got the concept. Then have a look at the below given scenario :
String s1 = "Sita";
s1 += "Ram";
System.out.println(s1);
The above code works. So can you make out what's happening here?
  • At the beginning s1 = "Sita" and in the second line s1 = "SitaRam". So, Is the original String modified? Is the immutability rule violated?
  • And the answer is simply no. Remember what I said in the beginning. Same applies here as well. When you write 
  • s1 = "Sita", a new object Sita is getting created and stored in the constant String pool. And your s1 refers to this String object.
      When you concat Sita with Ram (s1 += "Ram";) at the same time a new String object is created and your variable s1 now refers to this object.
So overall concept is the string object is not getting modified rather when concatenation occurs a new object is created and the old reference changes to new one. Thus String object remains immutable throughout the journey after creation.


Another Example:


Java Radar



Advantages of String's immutability :

  • Existing object in the heap is referred by number of variables thus saving lot of memory space and relieving java from the task of creating new object again and again if it already exists in constant memory pool (clearly explained above). 
  • Due to immutable nature, the hash code of the String doesn't change and thus can be cached easily.
  • Due to immutable nature, String objects are naturally thread safe.



You may also want to know about :


Thursday, 10 March 2016

Can we declare constructor as final?

NO

This is the simple answer of the question.

If you ever try to declare a constructor as final then the fate of your program is fixed. The compiler will show the error - 'modifier final not allowed'

In Eclipse, try to write this :

public class check {
final check(){              // you will get compiler error at check()

}
}


You will get compiler error at check() with message :
'Illegal modifier for the constructor in type check; only public, protected & private are permitted'

Before we proceed further, take a note :
Constructor can never be inherited. (Learn why?)

Hope this will clear all the doubts!

Now why do we use final with any method or constructor?
Or why would you ever want a constructor to be final?

So that when a class is inherited then final constructor (or methods) of that class should not be overridden. But here we don't need to worry at all. Since constructor according to java rule book cannot be inherited so making it final doesn't make any sense.


You may also like to read:

Wednesday, 9 March 2016

Why main() method is static in java?

Being  a java programmer you must be aware that main() method is entry point for any java program.

Whenever you write any class and then run it, JVM (Java Virtual Machine) immediately looks for public static void main(String[] args) method in that class.

Now suppose, if you don't make main() method static then what wrong would happen?

static keyword in main() gives licence to JVM to access it without making instance of the class you are executing.

In absence of static keyword, it would have become necessary for JVM to first make an instance of the class containing main() method and then use that instance to call main() method of that class.

Now let's look at the scenario with an example;

public class check {

public void main(String args[]){              // static missing 

System.out.println("Checking without static");

}
}

Points to be noted here :
  • If we don't write static keyword with main() method, you won't get any compile time error. Reason for the same is that main() method can be overloaded in java. (Click to Learn how?) . Here overloaded version of main() is used.
  • But when you run it in Eclipse,   
  1.  A pop up window will open with message : "Fatal error occurred. Program will exit."
  2.  And then you will get run time error on the console,
        java.lang.NoSuchMethodError: main
        Exception in thread "main" 


Why this run time error?
Remember when you run this program, JVM tries to search the 
public static void main(String[] args)
as an entry point in your program. But it doesn't find one. Rather it find's public void main(String args[]) thus is not permitted the gate pass to execute or enter the program and the program exit with run time error.



--------------------------------------------------*-----------------------------------------------------------
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.






You may also like to read about:

Difference between == and equals() method in java

Believe me or not...
This is one of the most frequently asked java interview question. Apart from that you will use either of them while coding number of times.
So lets take a walk through to the difference between the two.

First thing that you should be aware of is that both are used to compare two objects. But this question is generally asked in relation to String because each of them when used to compare String Objects behaves differently.

= = operator


Java tutorial by java radar






















== operator checks if two object refers to same memory location or not. That is if two object refers to same memory location then == operator will evaluate to true. (Here you need to have clear idea about how String object are created, stored and assigned to variables...)
Let's try to analyze above program.
1) First, we have three int variables (primitive type) a, b and c. Here you can easily figure out that since a and c has same value so if(a==c) loop is getting executed. Simple!
2)Second, we have four String variable s1, s2 (commented), s3 and s4. Looking at the way String object God is assigned to different variables we can say that only s1 and s3 share same memory location (How? Click here to know).



equals() method

Java tutorial by java radar























equals() method checks if the content of two object are same or not. Like in above program both s1 and s3 object has same content, God. 
s2 also has GOD (but in upper case) thus is not absolutely same as God. If you compare s2 with either s1 or s3 using equals then equals will return false. If you wish to ignore the case difference and evaluate to true then use s1.equalsIgnoreCase(s2) instead of just equals(). 
equalsIgnoreCase just checks the content without being concerned about case of the letters forming word.


You may also like to read about:



Tuesday, 8 March 2016

Inheritance and its purpose

Inheritance concept allows code defined in one class to be re-used in other classes. Or it can be said that Inheritance is the property by virtue of which sub-class can inherit all the property (except restricted ones) of its super-class.
If a class wants to inherit any other class then it must use keyword extends .
For example,

class Car{                                   //Car is superclass.
     int wheels = 4;
     int maxSpeed = 200;
     .................................
     public void cost(){.....}
     public void features(){.....}
}

Now suppose car manufacturer of Audi is planning to launch another car model 'Zoro'. So this model must inherit the core properties that a car possess.

class AudiZoro extends Car{    //AudiZoro is subclass that inherits(or extends) super class Car

}

Once you extend Car then what are the benefits that you get :

  • You can use all the variables and methods in the superclass Car in the subclass AudiZoro. So Inheritance provides scope for code re-usability.
  • You can override any method say cost or features to define it according to your own wish. So Inheritance provides scope for Polymorphism.

Overriding toString() method in java

Purpose : toString() method is overridden to get the String representation of the object.
If we directly print the object in java using System.out.print() it will give hashcode value as output. Lets see it with the help of an example

public class Emp {
       int empId;
       String empName;

       Emp(int id, String name){
              this.empId=id;
              this.empName=name;
       }

       public static void main(String[] args) {
              Emp e1 = new Emp(54110, "Mukesh");
              Emp e2 = new Emp(12243, "Rajnish");

              System.out.println(e1);
       }
}


OUTPUT :  Emp@3e25a5   
So what we get here is the hashcode value of the object. But we expected it to print the values contained by the object e1, something like this :
     54110, "Mukesh"
Isn't it?

How to overcome this problem?

override toString() method. Java compiler internally calls toString() so overriding this method will help us get the desired output as shown below 
public String toString(){
return xyz;
}

This time the above code override toString() :

public class Emp {
int empId;
String empName;

Emp(int id, String name){
this.empId=id;
this.empName=name;
}

public String toString(){                                                                        
return empId + " - "+ empName;                                                             
}                                                                                                                           

public static void main(String[] args) {
 Emp e1 = new Emp(54110, "Mukesh");
 Emp e2 = new Emp(12243, "Rajnish");
 
 System.out.println(e1);
 System.out.println(e2);

}


}

OUTPUT :
54110 - Mukesh

12243 - Rajnish

Now we get what we expected. This is the magic of overriding toString method. 

Example on StringBuilder in java


EXAMPLE 1 : Given a String "Maj1e4s57ti3c" You have to remove only digits from the given String to form a new String without any digit.

public class StrBuildr {
       public static void main(String args[]){
              String s = "Maj1e4s57ti3c";
              char[] cs = s.toCharArray();
             
              StringBuilder sb = new StringBuilder();
             
              for (char c : cs) {
                     if(!Character.isDigit(c)){
                           sb = sb.append(c);
                     }
              }
              String finalStr = sb.toString();
              System.out.println("After removing digits : "+ finalStr);
       }
}   

OUTPUT :
After removing digits : Majestic  




You may also like to know about :

Example on StringBuffer in java

EXAMPLE 1 : Given a String "Maj1e4s57ti3c" You have to remove only digits from the given String to form a new String without any digit.

public class StrBuffr {
       public static void main(String args[]){
              String s = "Maj1e4s57ti3c";
              char[] cs = s.toCharArray();
             
              StringBuffer sb = new StringBuffer();
             
              for (char c : cs) {
                     if(!Character.isDigit(c)){
                           sb = sb.append(c);
                     }
              }
              String finalStr = sb.toString();
              System.out.println("After removing digits : "+ finalStr);
       }
}   

OUTPUT :
After removing digits : Majestic   



You may also like to know about :

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
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.