Tuesday, 29 November 2016

Java is Pass by Value and Not Pass by Reference

original reference : http://www.journaldev.com/3884/java-is-pass-by-value-and-not-pass-by-reference


First of all we should understand what is meant by pass by value or pass by reference.
  • Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.
  • Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

Java is always Pass by Value and not pass by reference, we can prove it with a simple example.
Let’s say we have a class Balloon like below.
package com.journaldev.test;

public class Balloon {

 private String color;

 public Balloon(){}
 
 public Balloon(String c){
  this.color=c;
 }
 
 public String getColor() {
  return color;
 }

 public void setColor(String color) {
  this.color = color;
 }
}
And we have a simple program with a generic method to swap two objects, the class looks like below.
package com.journaldev.test;

public class Test {

 public static void main(String[] args) {

  Balloon red = new Balloon("Red"); //memory reference 50
  Balloon blue = new Balloon("Blue"); //memory reference 100
  
  swap(red, blue);
  System.out.println("red color="+red.getColor());
  System.out.println("blue color="+blue.getColor());
  
  foo(blue);
  System.out.println("blue color="+blue.getColor());
  
 }

 private static void foo(Balloon balloon) { //baloon=100
  balloon.setColor("Red"); //baloon=100
  balloon = new Balloon("Green"); //baloon=200
  balloon.setColor("Blue"); //baloon = 200
 }

 //Generic swap method
 public static void swap(Object o1, Object o2){
  Object temp = o1;
  o1=o2;
  o2=temp;
 }
}
When we execute above program, we get following output.
red color=Red
blue color=Blue
blue color=Red
If you look at the first two lines of the output, it’s clear that swap method didn’t worked. This is because Java is pass by value, this swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.
Let’s analyze the program execution step by step.
Balloon red = new Balloon("Red");
Balloon blue = new Balloon("Blue");
When we use new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100 and these are the memory location of both Balloon objects.
Now when we are calling swap() method, two new variables o1 and o2 are created pointing to 50 and 100 respectively.
So below code snippet explains what happened in the swap() method execution.
public static void swap(Object o1, Object o2){ //o1=50, o2=100
 Object temp = o1; //temp=50, o1=50, o2=100
 o1=o2; //temp=50, o1=100, o2=100
 o2=temp; //temp=50, o1=100, o2=50
} //method terminated
Notice that we are changing values of o1 and o2 but they are copies of “red” and “blue” reference locations, so actually there is no change in the values of “red” and “blue” and hence the output.
If you have understood this far, you can easily understand the cause of confusion. Since the variables are just the reference to the objects, we get confused that we are passing the reference so java is pass by reference. However we are passing a copy of the reference and hence it’s pass by value. I hope it clear all the doubts now.
Now let’s analyze foo() method execution.
private static void foo(Balloon balloon) { //baloon=100
 balloon.setColor("Red"); //baloon=100
 balloon = new Balloon("Green"); //baloon=200
 balloon.setColor("Blue"); //baloon = 200
}
The first line is the important one, when we call a method the method is called on the Object at the reference location. At this point, balloon is pointing to 100 and hence it’s color is changed to Red.
In the next line, ballon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.
I hope above explanation clear all the doubts, just remember that variables are references or pointers and it’s copy is passed to the methods, so java is always pass by value. It would be more clear when you will learn about Heap and Stack memory and where different objects and references are stored, for a detailed explanation with reference to a program, read Java Heap vs Stack.
Update: I am getting a lot of comments and it seems that still there is a lot of confusion, so I have made a video tutorial to explain this in detail.

Q)What is difference between HashMap and HashTable ?


Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
  1. Hashmap is not synchronized in nature but hashtable is.
  2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
    Fail-safe -if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException?
  3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

Q) What is the difference between equals() and == ?


Ans) == operator is used to compare the references of the objects. 
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects.
String str1 = "MyName"; 
String str2 = "MyName";
String str3 = new String(str2);

if (str1 == str2) {
  System.out.println("Objects are equal")
}else{
  System.out.println("Objects are not equal")
}
if(str1.equals(str2)) {
  System.out.println("Objects are equal")
} else {
  System.out.println("Objects are not equal")
}

Output:
Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if (str2 == str3) {
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if (str3.equals(str2)) {
  System.out.println("Objects are equal")
} else {
  System.out.println("Objects are not equal")
}

Output:
Objects are equal
Objects are equal

Wednesday, 23 November 2016

Immutable class:

 

  • Make class final so that it should not be inherited.
  • All the variables should be private so should not be accessible outside of class. 
  • Make all variables final so that value can not be changed.
  • constructor to assign values to variables in class.
  • Do not add any setter methods.

Java Interview Program to Swap two numbers without using third variable in java

  1. public class SwapTwoNumbers {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. int number1=20;
  6. int number2=30;
  7.  
  8. System.out.println("Before Swapping");
  9. System.out.println("Value of number1 is :" + number1);
  10. System.out.println("Value of number2 is :" +number2); 
  11.  
  12. number1=number1+number2;
  13. number2=number1-number2;
  14. number1=number1-number2;
  15.  
  16. System.out.println("After Swapping");
  17. System.out.println("Value of number1 is :" + number1);
  18. System.out.println("Value of number2 is :" +number2);
  19.  
  20. }
  21. }



  1. public class SwapTwoNumbers {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. int number1=2;
  6. int number2=4;
  7.  
  8. System.out.println("Before Swapping");
  9. System.out.println("Value of number1 is :" + number1);
  10. System.out.println("Value of number2 is :" +number2); 
  11.  
  12. number1=number1^number2;
  13. number2=number1^number2;
  14. number1=number1^number2;
  15.  
  16. System.out.println("After Swapping");
  17. System.out.println("Value of number1 is :" + number1);
  18. System.out.println("Value of number2 is :" +number2);
  19.  
  20. }
  21. }

Java programming examples: Hashmap

Java programming examples: Hashmap

  1. public class HashMapJavaTricky{
  2.  
  3. public static void main(String[] args) {
  4.  
  5.     HashMap<Integer,String> hm= new HashMap<Integer, String>();  

  6.      hm.put(1, "one");
  7.      hm.put(2, "two");
  8.      hm.put(3, "three");
  9.  
  10.      hm.put(1, "ONE");
  11.      hm.put(null,null);
  12.  
  13.     System.out.println(hm.size()); 
  14.  
  15. for (Integer name: hm.keySet()){
  16.  
  17.    System.out.println(name + " " + hm.get(name)); 
  18.   
  19. }
  20.  
  21. }
  22. }


 


  1. 4
  2. null null
  3. 1 ONE
  4. 2 two
  5. 3 three

Java interview Program to find second Smallest number in an integer array by sorting the elements.

class SecondSmallestNumber{

public static void main(String args[])
{

int numbers[] = {6,3,37,12,46,5,64,21};

  Arrays.sort(numbers);

  System.out.println("Smallest Number: "+numbers[0]);
  System.out.println("Second Smallest Number: "+numbers[1]);

 }

}

Java interview Program to find second smallest number in an integer array without sorting the elements.
class SecondSmallestNumber{

int[] x ={10,11,12,13,14,6,3,-1};

        int small=x[0];

 for(int i=0;i<x.length;i++)
 {
        if(x[i]<small)
        {
        small=x[i];
        }
 }

   int sec_Small=x[0];

for(int i=0;i<x.length;i++)
 {
        if(x[i]<sec_Small && x[i]!=small)
        {
        sec_Small=x[i];
        }
  }

        System.out.println("Second Smallest Number: "sec_Small);
        }
}