Monday 25 April 2016

Swap two numbers in java

Scenario : You have two variables a and b with values assigned to them as 100 and 101 respectively. Write a program in java using third variable two swap the values within the a and b.
Input :  a = 100 and b = 101 
Output : a = 101 and b = 100

public class swap {

       public static void main(String[] args) {
              int a = 100;
              int b = 101;
              System.out.println("Before swapping, a :"+ a +" and b : "+ b);
              swapValue(a, b);

       public static void swapValue(int a, int b){   //mind the use of static here*
              int temp;                              //temp is the third variable
              temp = a;
              a = b;
              b = temp;
              System.out.println("After swapping, a : "+ a +" and b : "+ b);

Before swapping, a : 100 and b : 101
After swapping,  a : 101 and b : 100

mind the use of static here*
Try removing static from this line, public static void swapValue(int a, int b) and see what you get.
You will get compile-time error at swapValue(a, b); saying "Cannot make a static reference to the non-static method swapValue(int, int) from the type swap".

Why so? (Learn here)

Don't sit relaxed!
Do you really think the original value of variable a and b has been swapped?

To check it, do just as I instruct. Try to print the value of a and b after the swapValue(a, b) method complete its task. 

public class swap {

       public static void main(String[] args) {

              int a = 100;
              int b = 101;
              System.out.println("Before swapping, a :"+ a +" and b : "+ b);
              swapValue(a, b);
              System.out.println("Is swapping done? a :"+ a +" and b : "+ b);

       public static void swapValue(int a, int b){   //mind the use of static here*
              int temp;                 //temp is the third variable
              temp = a;
              a = b;
              b = temp;
              System.out.println("After swapping, a : "+ a +" and b : "+ b);

And surprisingly you will see the println in red would print the original value of a and b. i.e. a = 100 and b = 101

Even though swapValue() method shows that the value of the two variable is swapped then why this crap???
Reason is pretty simple... Look at these two lines again,
swapValue(a, b);              //a, b are the variables declared in main() method
public static void swapValue(int a, int b)  //here a, b are the local variable of this                                                     // swapValue() method. 

I can also write the second line as,
public static void swapValue(int c, int d)

Now what is happening in above line. The value a, b passed by swapValue(a, b) from the main() method is copied in the local variable c(will hold value of a) and d (will hold value of b) of 
            public static void swapValue(int c, int d){
              int temp;                 //temp is the third variable
              temp = c;
              c = d;
              d = temp;
              System.out.println("After swapping, c : "+ c +" and d : "+ d);
So the logic written inside this method is actually swapping c, d which is local variable of this method containing copied value of a, b passed in calling function swapValue(a, b) from main(). 
Thus we can see it is not the value of a, b passed in the calling function from main() method is swapped but local variable in called function is getting swapped.

Hope I made it clear to you...
If not please ask me again

Sunday 24 April 2016

Why you can't mark a class as both abstract and final?

Abstract and final have nearly opposite meanings. An abstract class must be subclassed, whereas a final class must not be subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.

You may also like to read:

Thursday 21 April 2016

Garbage collection in java

Garbage collection is the part of effective memory management.

Java provides automatic garbage collection. Thus it frees the programmer from the headache of adding any memory management logic.

Before we proceed, can you tell me? 
Where is the objects that you create gets stored?
Always remember, any object created in java gets its memory space in heap.  

I guess, now you can think of where entire garbage collection process takes place. Definitely, its heap. 

How garbage is collected in java?

Whenever there is any object that has no reference and is lying unreachable from the java program, it automatically qualifies for garbage collection.

When does garbage collector run?

Garbage collector is under the control of JVM. So it is upto JVM to decide when to run garbage collector. Whenever JVM gets the feeling that it is running out of the memory, it starts garbage collection to claim the space occupied by objects residing in heap without having any reference.

*Note : free() is used in C and delete() in C++ to collect garbage while java collects it automatically

Disadvantage of Java's Garbage collection process
  • The only downside of Garbage collector is that it can't be controlled completely by programmer. You may give instruction to run garbage collection process but its up to the JVM to start the process at its own whim. 

Advantages of Java's Garbage collection process

  • Java provides better memory management due to automatic garbage collection technique.
  • It frees the programmer from taking pain to write the logic to collect garbage (but programmers can give instruction to JVM to run garbage collector, if they want).
Q. Which method is called before the garbage collection occurs?

Tuesday 12 April 2016

Difference between final, finally and finalize() in java


1) final is a keyword in java.
2) final in java can be used with :

  • variable - If you mark a variable as final then once you initialize value to that variable, it can never be changed.
  • method - If you mark a method as final in your class then that method cannot be overridden by the sub-classes method.
  • class - If you mark a class as final in java then that class cannot be extended (or sub-classsed)


1) finally is a block in java
2) finally block is used with try block in exception handling. This block will surely get executed irrespective of whether exception is handled or not. 

click to know more in detail about finally block


1) finalize() is a method in java.
2) finalize() method is called at least once, before the object is garbage collected, to perform any cleanup activity like releasing any system resources if held or closing the open connection.

This is the main difference between final, finally and finalize().
Here we have talked about just difference but there is more to know about each one of them. To know in depth about working of each of them follow the given link above.

Sunday 10 April 2016

Why would you ever mark a class final?

You should mark a class final only if you need an absolute guarantee that none of the methods in that class will ever be overridden. If you're deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation out from under you.

You'll find number of classes in the Java core libraries marked as final. For example, the String class cannot be sub-classed.

Thus use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods.

Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer.

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

You may also like to read:

Wednesday 6 April 2016

Class in java

Think of java without a class...
It's not possible.
Java begins with a class.

Class is generally considered as the blueprint/template that describes the state/behavior that object of its type support.
This is definition which one can find in any book or tutorial. But what does it actually mean?

Why a class can be considered as a blueprint/template?

Lets try to find out taking real life example.
If we look on the road, we can see different type of cars, buses running here and there.Each of these can be
considered as an instance of a class Vehicle. And these instances are born from the same set of blueprints and thus consists of same components.
Lets take a look :

public class Vehicle {
       int maxSpeed;
       String model;
       int seats;
       int price_per_seat;
       public int fareCollection(int seat, int price_per_seat){
              int totalFare = seat*price_per_seat;
              return totalFare;
       public void acceleration(){
              //create logic to calculate acceleration which
              //instance of vehicle will use


public class VehicleType {

       public static void main(String[] args) {
              Vehicle car = new Vehicle();     //creating car from vehicle blueprint
              car.model = "car1190";
              car.seats = 6;
              car.maxSpeed = 150;
              car.price_per_seat = 50;
              int total_car_fare = car.fareCollection(car.seats, car.price_per_seat);
              System.out.println("Total collection of car model "+ car.model +" per trip : "+ total_car_fare);
              Vehicle bus = new Vehicle();     //creating bus from vehicle blueprint
              bus.model = "bus123";
              bus.seats = 45;
              bus.maxSpeed = 60;
              bus.price_per_seat = 10;
              int total_bus_fare = bus.fareCollection(bus.seats, bus.price_per_seat);
              System.out.println("Total collection of bus model "+ bus.model +" per trip : "+ total_bus_fare);



You can see here, how the two different instance use same template Vehicle but yet have different state and behavior.
The fields maxSpeed, model, 
seats, price_per_seat represents object state and methods  fareCollection() and acceleration()  define behavior and the way individual object interacts with outside world.

*Depending on the state of each instance the behavior changes.

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.