Friday, April 6, 2012

Basics of Java

Dear Reader,
I have written few programs on basics, it may help you to explore new things. By the way it is just
for my reference. Topics: 
 1. Infinite Loop
 2. Mixed basics (Including signed unsigned bit operations)
 3. Logical Operators
 4. finally
 5. String concatenation
 6. Count of iterations
 7. Inheritance
 8. Modulus

Infinite Loop:
------
public class InfiniteLoop {
    public static void main(String[] args) {
        System.out.println("The below line of code is an infinite loop:");
        for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i+=1)
            System.out.println(i+", ");
    }
}
/*
It's an infinite loop, because every int value is less than or equal to Integer.MAX_VALUE. 
Once the loop gets to Integer.MAX_VALUE, it wraps to next value which is negative and starts over again.
*/
---------------


Mixed basics:
------
public class JoyOfHex {
    public static void main(String[] args) {        
        System.out.println(Long.toHexString(0x100000000L + 0xcafebabe)); 
        
        double x = 2.0;
        double y = 1.1;
        System.out.println( x - y );   //Why not 0.9
        
        int x1 = 10 + 010;
        System.out.println(x1);        //Why not 20 or if binary then 12 (10+2).
        
        double x2 = 1.0 / 2L;
        System.out.println(x2);        //You have to tell.
        
        int x3 = 11 % 2*5;
        System.out.println(x3);        //You have to tell.
        
        System.out.println(  ((int)(char)(byte) -1) );  //You have to tell.
    }
}
//Output:
cafebabe   //Why not 0x1cafebabe
0.8999999999999999  //1.1 gets represented as the nearest double then we subtract. The answer is rounded 
                    //to the nearest double, which happens to be the ugly thing you’ve just seen.
18  //If you put 0 before a number, JVM assumes that number as Octal.
0.5 //No magic here.
5
65535  //00000000000000001111111111111111

NOTE:  Signed (-1) 11111111111111111111111111111111
      (byte)Signed (-1): 11111111
      (char)Unsigned (65535) 1111111111111111
      (int)Signed (65535) 00000000000000001111111111111111
Rule: Sign extension is performed if the original value is signed. Otherwise zero extension.
    Java doesn't provide unsigned types. Java is Big-Endian which is network order.
    The term Endian or Endianness refers to the ordering of bits for a representation of a larger data item as 
    stored in external memory (or, sometimes, as sent on a serial network connection).

    Big-Endian: 01234.. (Left to Right bit ordering).
    |------------>>>>>

    Little-Endian: ..43210 (Right to Left bit ordering).
    <<<<<------------|

=================


Logical Operators:
------
public class LogicalOperator {
    public static void main(String[] args) {
        int j=0;
        int i = (j++) + (j++);
        System.out.println(i+" "+j);
        
        //What will be value of k in below program
        int k=0;
        for (int m=0; m<100; m++){
            k=k++;
        }
        System.out.println(k);  //You have to tell.
    }
}
//Output:
1 2
0
---------------


finally:
------
public class TryHarder {
    public static void main(String[] args) {
        TryHarder t=new TryHarder();
        System.out.println(t.returnInt());
        t.noReturn();
    }
    public int returnInt(){
        try{
            return 5;
        }
        catch(Exception e){
            return 15;
        }
        finally {
            return 10;
        }
        //return 20;  //Unreachable code
    }
    public void noReturn(){
        try{
            System.out.println("Inside try");
            return;
        }
        catch(Exception e){
            System.out.println("Inside catch");
            return;
        }
        finally {
            System.out.println("Inside finally");
        }
    }
}
//Output:
10
Inside try
Inside finally
NOTE: finally may not execute only when System.exit() call is made. Or a Thread is interrupted or
      a dead lock has come in multithreaded env.
---------------


String Concatenation:
------
public class StringOut {
    public static void main(String[] args) {
        System.out.println("R"+"2");
        System.out.println('D'+'2');  
    }
}
//Output:
R2
118
//Ascii: 68 + 50, Ascii table link: http://www.asciitable.com/
---------------


Count of Iterations:
------
//How may iterations you think the following loop does
public class LoopHole {
    public static void main(String[] args) {
        double d = 0.0;
        long count=0L;
        while ( d != 1.0 ) {
            d += 1.0 / 13;        //1.0 / 13 = 0.07692307692307693
            count++;
            System.out.println(d);
        }
        System.out.println("Count is: "+count); //Code is keep on counting, an infinite loop.
    }
}
//Output:
Infinite loop. Always handle addition properly.

See below code: 
long y = 1000000*5000;  //Overflows as right side calculation is on Integers. Specify "L" for long.
long y = 1000000L*5000; //Correct, made one as Long.
---------------

Inheritance:
------
class PolyPain {
    public String name = "Parent";
    public void Print() { 
        System.out.println("Parent");
    }
    public static void Print2() { 
        System.out.println("Parent"); 
    }
}

public class PolyPainChild extends PolyPain {
    public String name = "Child";
    public void Print() { 
        System.out.println("Child"); 
    }
    public static void Print2() { 
        System.out.println("Child"); 
    }
    public static void main(String[] args) {
        PolyPainChild c = new PolyPainChild();
        PolyPain p = (PolyPain)c;
        p.Print();  //Child
        p.Print2(); //Parent
        System.out.println(p.name); //Parent
    }
}
//Output:
Child
Parent
Parent

NOTE: Overridden methods exhibit dynamic polymorphism. Overridden static methods do not.
Overridden (“shadowed”) fields also do not exhibit dynamic polymorphism. 
---------------

Modulus:
------
public static boolean isOdd (int x) {
return (x % 2 == 1);
}
NOTE: Works for positive x only.

Java defines % as: (a / b) * b + (a % b) = a
So if a<0, b>0 then (a % b) < 0.
i.e. (-7 % 2) = -1 and not 1.

Fixes:
    public static boolean isOdd (int x) {
        return (x % 2 != 0);
    }
    public static boolean isOdd (int x) {
        return (x & 1 != 0); //bit wise operator.
    }
------------------------------END------------------------------

1 comment:

  1. Check "Programming Katta" for java basics dude...!!!
    You doing a good work men..!!!

    ReplyDelete