Wednesday, 20 May 2015

Program: Write a program to reverse a number.

Below program shows how to reverse a number using numeric operations.

package in.blogspot.java2bigdata;
 
public class NumberReverse {
 
    public int reverseNumber(int number){
         
        int reverse = 0;
        while(number != 0){
            reverse = (reverse*10)+(number%10);
            number = number/10;
        }
        return reverse;
    }
     
    public static void main(String a[]){
        NumberReverse reverseNum = new NumberReverse();
        System.out.println("Result: "+reverseNum .reverseNumber(212015));
    }
}


// Output:
//Result:510212

Prgram:Factorial of a number.
Program:The leap year rule.

Instance Control Flow In a Class

In my previous article I discussed about static control flow in a class and static control flow in parent and child relationship. let see what will happen at the time of creating class object .

At the time of creating an object the following sequence of events will be performed automatically by JVM.

1. Identification of instance members from top to bottom.
2. Execution of instance variable assignments and instance blocks from top to bottom.
3. Execution of constructor.


Output:

0
First instance block
Second instance block
InstaceFlow constructor
main() method......

I know the above program is bit confusing, I will try to elaborate more

At the time of creating an object the following sequence of events will be performed automatically[2].

At first all instance members of the class are identified (just identified , no assignment of variables and execution of instance blocks is done), observe [3] to [8] .

After identification variable assignment and execution of instace blocks starts from top to bottom so value 5 is assigned to int firstNumber[9] , the next instance block is executed here firstMethod() method is called ,  observe  firstMethod() is trying to print secondNumber which is not yet initialized so the default value “0” is printed,

now control flows back to instace block and the next statement  “First instance Block”[12] is displayed on console. After it the second instance block is executed and “Second instace Block” is printed[13], now the secondNumber is initialized[14]. Finally constructor is being executed [15]. (Generally object initialization done in constructors). then main () method next statement will be executed[16].

Note: Instance control flow is not one time activity for every object creation it will be executed but
static control flow is one time activity and it will be executed at the time of class loading.

I will be discussing more about constructors in my up coming post.