Data Types

Data and Variables
  1. Variable is a named piece in memory that we use to store information in Java program.
  2. Data can only be stored of only type.
  3. If you have defined a variable to store Date object then it will only store Date object.
  4. Helps the compiler to verify that each variable we define in our program is not used in a manner or a context that is inappropriate to its type.
  5. Explicit data values that appear in our program are called as literals.Each literal has a particular type for example 25 is an integer type.
  6. Before we can use a variable we must specify its name and type in the declaration.
  7. Name chosen for a variable is called as an Identifier.An identifier can be of any length,but must start with a letter,_ or a $ sign.Rest of the identifier can use characters except those used as operators in Java.
  8. Java is case sensitive so name "subject" & "Subject" are not same.No blanks or Tabs should be included in middle of name.
  9. You can't use keywords in Java as names.
  10. A name can't be anything that could be interpreted as a constant value.
Variable Names and Unicode
  1. All source code is converted to unicode characters before it is compiled.
  2. Identifiers in our code can use any national level character set that is defined within unicode character set.
Variable Types
  1. Each variable can store a specific type of data or object.
  2. We can define using 
    1. int numberOfWheels;
    2. Above datatype is int and variable name is number of wheels.
  3. Variables will be referenced objects or 8 basic datatypes.These fundamental types are called as primitive types
    1. Numerical values either floating or integer type
    2. Variables that store code for single Unicode Character.
    3. Logical variables that can assume their values as true or false.
  4. All primitive types are keywords in Java.
Numeric Data Types
  1. There are 4 types of variables that can store numeric data.
  2. All these are signed or unsigned i.e. they can have positive or negative values.
  3. The only difference is range of Values.
  4. The various Numeric types are
    1. Byte
      1. Variables of this type can have values from -128 to +127 and occupy 1 byte in memory.
      2. Used for memory saving
    2. Short
      1. Variables of this type can have values from -32768 to 32767 and occupy 2 bytes in memory.
      2. Used for memory saving
    3. int
      1. Variables of this type can have values from -2147483648 to 2147483647 and occupy 4 bytes in memory.
    4. long
      1. Variables can have values from -9223372036854775808 to 922337203685477 and occupy 8 bytes in memory.
      2. Used for longer range than int.
  5. Some Examples are 
    1. byte smallerValue;
    2. short pageCount;
    3. int wordCount;
    4. long bigValue;
  6. In Binary representation left most bit is signbit. When the bit is 0 number is positive and when bit is 1 number is -ve. 
    1. Binary -ve number's are represented in 2's compliment form.
Java Primitive Wrappers
  1.  These are wrapper classes provided over Java primitive types tom perform operation on them for example 'Byte' class is wrapper class over "Byte" primitive type which defines constants like. SIZE,BYTES,MAXVALUE,MINVALUE.
  2. To get size of Byte we will use
    1. System.out.println("Size of Byte "+(Byte.SIZE)+" bytes")); OR Byte.Bytes
    2. To get min and max values we use Byte.Max_Value and Byte.Min_Value.
Lets have a look at different types of Numeric Wrappers and their sizes in a program.
 public class size {  
   public static void main(String args[])  
   {  
     System.out.println("Size of byte: "+(Byte.SIZE/8)+" bytes.");  
     System.out.println("Size of Short: "+(Short.SIZE/8)+" bytes.");  
     System.out.println("Size of int: " + (Integer.SIZE/8) + " bytes.");  
     System.out.println("Size of long: " + (Long.SIZE/8) + " bytes.");  
     System.out.println("Size of byte: "+(Byte.BYTES)+" bytes.");  
     System.out.println("Size of Short: "+(Short.BYTES)+" bytes.");  
     System.out.println("Size of int: " + (Integer.BYTES) + " bytes.");  
     System.out.println("Size of long: " + (Long.BYTES) + " bytes.");  
     System.out.println("Minimum size of byte: "+Byte.MIN_VALUE);  
     System.out.println("Maximum size of byte: "+Byte.MAX_VALUE);  
     System.out.println("Minimum size of Short: "+Short.MIN_VALUE);  
     System.out.println("Maximum size of Short: "+Short.MAX_VALUE);  
     System.out.println("Minimum size of Integer: "+Integer.MIN_VALUE);  
     System.out.println("Maximum size of Integer: "+Integer.MAX_VALUE);  
     System.out.println("Minimum size of Long: "+Long.MIN_VALUE);  
     System.out.println("Maximum size of Long: "+Long.MAX_VALUE);  
   }  
 }  

















Numeric Literals
  1. By default a literal specified as a sequence of decimal digits is of type int.If you want to define an integer literal of type long we need to append an L to the value.
  2. So values 1L,-9999L,123456789L are all of type long.
  3. Byte and Short numeric literals are automatically interpreted by the compiler.
  4. We can specify numeric literals to the base 16 i.e. hexadecimal numbers.These numbers in Java have 0X in front of them and follow usual convention of using letters A to F to represent values with digits 10 to 15.Example
    1. 0X100 - 256 (decimal)
    2. 0X1234 - 4660 (decimal)
    3. 0XDEAF - 57007 (decimal)
    4. 0XCAB - 3243(decimal)
  5. For a long hexadecimal number we use 0X0FL which equals 15.
  6. Octal numbers are defined with a leading 0 for example 035,067 etc.Each octal digit defines 3 bits.
  7. Its good to initialize a variable to default value as soon as we declare them Example
    1. long bigOne=299999999L;
  8. Multiple variables can be declared as 
    1. long bigOne=9999999L,largeOne=000000L;
  9. Its always good to add a one line comment to variables so that they can be distinguished
    1. int xCoord=0,yCoord=0; //pointCoordinates
Floating Point Data Types
  1. Numeric values that are not absolute are stored in as floating point numbers.
  2. A floating point number has a fixed number of digits of accuracy but with a very wide range of values. Example 0.0005,500.01 and 5000.0 etc
  3. There are 2 primitive floating types in Java float and double.
    1. Float
      1. from -3.4E38 ( -3.4*10 power 38) to (3.4*10 power 38)
      2. Occupies 4 bytes in memory
      3. supports up to 7 decimal digits
      4. Used to Save memory
      5. Don't use for precise values like currency
    2.  Double
      1. from -1.7E308(-1.7 * 10 pow 308) to +1.7E308(+1.7 * 10 pow 308)
      2. Occupies 8 bytes in memory
      3. Supports up to 17 decimal digits
      4. Don't use for precise values like currency
Floating point literals
  1. Floating point literals are of type double by default so 1.0 and 345.678 are both of type double. 
  2. To specify a value of type float append a 'F' to the value so 1.0F and 1.0f are both of type float.
  3. For very large floating type literals we write them as an exponent for example 149600000 kms can be written as 1.496E8 or 1.496 * 10 pow 8
Declaring floating point variables
Examples of floating point variables
  1. double sunDistance = 1.496E8;
  2. float electronMass=9E.28F;
  3. float hisWeight=185.2F, herWeight=108.5F
Fixing value of Variable

Sometimes we need to fix value to variable.Such variables need to be prevented from being changed accidentally.We use final keyword while declaring these for example.
  1. Final int FEET_PER_YARD=3;
  2. Final float PIE =3.14f;
Final keyword specifies that value of variable is final and cannot be changed.Its good to define constants in uppercase.

Arithmetic Calculations
  1. Assignment statement is used to store the result of a calculation in variable.
  2. It consist of 3 parts
  3.                                numFruit                   =               numApples + numOranges
                                   (Variable where  (Assignment    (Expression)
                                    result is stored)   operator)
    1. Expression on right is executed and result is stored in variable on left.
    2. Increment a variable is done by 
      1. numApples = numApples+1;
    3. Multiple assignments can be written in a single statement.
      1. a=b=c=777;
    4. Initializing is different from assignment.When we initialize we provide an initial value to variable.
    5. When we assign we copy data from one place in memory to another.
    6. In the statement a=b=c=777; 
      1. C is initialized to 777 which is copied to b and b is copied to a.
    7. The constant is stored as the type of variable on left.For example
      1. short value =0;
      2. value=10
      3. Here value is declared as 0 initially.The assignment will store 10 as integer literal of type short occupying 2 bytes.
    Integer calculations
    1. Integer calculations are performed by Binary operators +,-,* and /,these have the usual meaning i.e. add,subtract,multiply and divide respectively.
    2. An operand is just a term for a value to which operator is applied.
    3. Execution is based on BODMAS basis i.e. Bracket Open Division Multiplication Addition Subtraction
    4. The unary versions of + and - operator apply to a single operand to the right of  the operator eg -345.
    Integer Division and Remainders
    1. In integer division remainder is discarded and result is a integer rounded off.
    2. It's the amount left over after dividing the right operand called "divisor" and left operand called as "dividend" a whole number of times.
    3. As in arithmetic when we divide 2 negative numbers result is positive when we divide a negative by a positive number result is -ve.
      1. There is an exception to this when dividend is a -ve integer that has largest magnitude and divisor is -1 the result is same as dividend.
      2. So if we divide -2147483648/-1=2147483648 but int can hold only uptil 2147483647 hence result is original dividend -2147483648.
    4. Dividing by zero causes arithmetic exception.
    5. Modulus operator "%" generates the remainder after a division.
    6. Modulus operator has same precedence as the multiplication and division and therefore executes before addition and subtraction.
    Increment and Decrement operators
    1. Increment operator is written as "++" 
    2. Decrement operator is written as "--" 
    3. If int Count=10; ++count will produce 11 and --count will produce 9
    4. These operators are useful during looping through objects.
    5. These operators behave differently when we use them in front or back of a variable.
      1. When in front i.e. prefix it will increment/decrement first and then return value
        1. int count=10; int incr=++count will give value 11 to incr and count will also be 11
      2. When in back i.e. postfix it will return the value and then increment/decrement i.e.
        1. int count=10; int incr=count++ will give value 10 to incr and count will be 11;
    Computation with shorter Integer Types
    1. All binary integer operations work with operands of type int or long in java.So for arithmetic operations using short type integers convert these first to int type and then execute.
    2. Short c1=5,c2=10; short sum=c1+c2;
      1. Will not compile since (c1+c2) is a 32 bit expression while sum is a 16 bit variable.To do this we need to typecast the operation to short as "short sum=(short)(c1+c2);.
      2. This is called as explicit type cast.The effect of this cast is that only right most least significant bits are kept.Since the bits in a binary number in Java increase from right to left.The most significant bits are discarded. 
    3. Similarly for byte the least significant 8 bits are kept.So if result requires more than 16bits/8bits to be represented then result will be wrong.But we will get no indication from compiler regarding this.
    4. Implicit type casting is when compiler internally converts from one type to another for example.
      1. int x='a'; System.out.println(x); will return 97 which is the ASCII value of  'a'.
      2. long result=0; long factor=10L; int number =5; result= factor*number;
      3. Because factor is "long", to execute last statement the multiplication is carried out using long values.So "number" will be converted to long before execution.
    Errors in Integer Arithmetic
    1. Exception is thrown when you divide a number by zero;
    2. Exception is thrown when we modulus with right hand operand which is zero.
    Floating point calculators
    1. All arithmetic operators can be used for floating point numbers.
    2. Like in int , we can use increment and decrement for floating point variable.
    3. We can apply modulus operator to find out remainder.
    Error conditions in floating point variables
    1. Occurs when a calculation produces a value that is outside a range that can be represented by the floating type we are using.
    2. Other arises when result is mathematically indeterminate.
    Mixed Arithmetic Expressions
    1. If either operand is of type double then other is converted to double.
    2. If either operand is of type float then the other is converted to float.
    3. If either operand is of type long then other is converted to long.
    The op= operators
    1. Used as lhs op= rhs  where op is any arithmetic operator
    2. The right hand side is worked first before it is combined with LHS
    3. Example count+=5 (same as count=count+5;)
    4. If variable is of different type the result is automatically typecasted to the type of the variable.
    5. op= operators are
      1. +=
      2. -=
      3. *=
      4. /=
      5. %=
      6. <<=
      7. >>=
      8. >>>=
      9. &=
      10. /=
      11. ^=
    Mathematical Functions and Constants
    1. Java provides a variety of math functions such as sqrt in package java.lang.These are available to program directly.
    2. These functions are implemented in Math class as static methods.So to find square root of a number you will find as 
      1. Math.sqrt(aNumber);
    3. There are a wide range of trigonometric functions,hyperbolic functions,numerical functions,mathematical functions.
    4. Sometimes we need to use certain methods of this class.Sometimes we may require only one,Sometimes we may require many.
      1. Depending on our requirement only we should import either selected methods or all methods.
        1. import static java .lang.Math.*; // imports all methods
        2. import static java.lang.Math.floor; // imports floor
        3. import static java.lang.Math.sqrt; // imports sqrt
        4. import static java.lang.Math.PI; // imports PI
      2. Here we can use the methods directly example sqrt(5);
      3. This makes code look more cleaner.
    5. The only difference here is when we don't import we have to use methods with class name example Math.sqrt(5).
    Let's now look at a program that calculates area of shape depending of number of sides passed
     import java.util.Arrays;
     public class Area {  
       final float PIE=3.14f;  
       private float CircleArea(int diameter)  
       {  
         float radius=diameter/2;  
         float area=this.PIE*radius*radius;  
         return area;  
       }  
       public static void main(String args[])  
       {  
         Area a=new Area();  
         int count=args.length;  
         if(count==1)  
         {  
           System.out.println("I believe this is diameter of circle");  
           float area = a.CircleArea(Integer.parseInt(args[0]));  
           System.out.println("Area is :"+area);  
         }  
         else if(count==2)  
         {  
           System.out.println("I could not build a figure with 2 sides");  
         }  
         else if(count==3)  
         {  
           System.out.println("Assuming that's a right Triangle");  
           Arrays.sort(args);  
           float area=(Integer.parseInt(args[0])*Integer.parseInt(args[1]))/2;  
           System.out.println("Area is :"+area);  
         }  
         else if(count==4)  
         {  
           Arrays.sort(args);    
           if((Integer.parseInt(args[0])==Integer.parseInt(args[1])) &&(Integer.parseInt(args[0])==Integer.parseInt(args[3])))  
           {  
             System.out.println("That's a Square");  
             float area=Integer.parseInt(args[0])*Integer.parseInt(args[1]);  
             System.out.println("Area is :"+area);  
           }  
           else if((Integer.parseInt(args[0])==Integer.parseInt(args[1])) &&(Integer.parseInt(args[2])==Integer.parseInt(args[3])))  
           {  
             System.out.println("That's a Rectngle");   
             float area=Integer.parseInt(args[0])*Integer.parseInt(args[2]);  
             System.out.println("Area is :"+area);  
           }  
           else  
           {  
             System.out.println("That's a Trapzoid(currently not supported)");  
           }  
         }  
         else if(count==5)  
         {  
           if((Integer.parseInt(args[0])==Integer.parseInt(args[1])) && (Integer.parseInt(args[0])==Integer.parseInt(args[3])))  
           {  
             if (Integer.parseInt(args[3])==Integer.parseInt(args[4])) {  
               System.out.println("That's a Pentagon");  
               double area = (Integer.parseInt(args[0])*Integer.parseInt(args[1]))*(Math.sqrt(5*(5+(2*Math.sqrt(5)))))/4;  
               System.out.println("Area is :"+area);  
             }  
           }  
         }  
         else if(count==6)  
         {  
           if((Integer.parseInt(args[0])==Integer.parseInt(args[1])) && (Integer.parseInt(args[0])==Integer.parseInt(args[3])))  
           {  
             if ((Integer.parseInt(args[3])==Integer.parseInt(args[4])) && (Integer.parseInt(args[4])==Integer.parseInt(args[5])))   
             {  
               System.out.println("That's a Hexagon");  
               double area = (Integer.parseInt(args[0])*Integer.parseInt(args[1]))*(3*Math.sqrt(3))/2;  
               System.out.println("Area is :"+area);  
             }  
           }  
         }  
         else if(count==7)  
         {  
           System.out.println("That's a Heptagon");  
         }  
         else if(count==8)  
         {  
           System.out.println("That's a Octagon");  
         }  
         else if(count==9)  
         {  
           System.out.println("That's a Nonagon");  
         }  
         else if(count==10)  
         {  
           System.out.println("That's a Decagon");  
         }  
       }  
     }  
    

    1. So here in main we are first checking the number of sides as Strings passed from console.That is why we take the main parameter as an array of Strings.
    2. Next we are counting the sides and calculating area using some Math functions.
    3. Since the parameters were received by us as Strings we typecasted them to integers.
    4. As we see here we have used sorting function from Array class in java.util package to sort array and imported the same since java.util package is not available by default.
    5. Then using some Math functions we have calculated the area of shapes accordingly.You can expand it further to support more shapes.
    Storing Characters

    1. Variables of type char, store a single character code.They each occupy 16 bits or 2 bytes in memory.
    2. To declare and initialize a character variable mycharacter you can use statement.
      1. char mychar = 'X'; because all characters are stored as unicode.
    3. You cannot delimit a character with double quotes as they are used to delimit a character String.
      1. char a="x"; //wrong
      2. char a='x'; //right
      3. String a="xyz"; //right
      4. String a='xyz'; //wrong
    Character Escape Sequences
    1. Sometimes we need to define a unicode character for characters not available on our keyboard.
    2. These are represented using hexadecimal representation of character codes in an escape sequence.
    3. An escape sequence starts off with a "\".Most common character is "\n"(newline).
    4. To create an escape sequence of a Unicode character we proceed the four hexadecimal digits of a character by "\u" for example
      1. char mycharacter="\u0058";
    5. To use "\" as char in string we use "\\".
    6. Also for characters quote('') & doublequotes("") we need to use \' and \" because string and chars are enclosed in " and ' respectively.
      1. Example System.out.println("\" Smell the coffee before its too late \",said the manager"); 
    7. Other Escape sequences are
      1. "\b" Backspace
      2. "\f" Formfeed
      3. "\n" Newline
      4. "\r" Carriage return
      5. "\t" Tab
    Character Arithmetic
    1. Like integers we can increment or decrement characters.
      1. char mychar = 'x';
      2. mycharacter+1;
      3. ++mycharacter;
    2. Since character is specified as unicode so their values is converted to int to carry out operations.
      1. char letter1='A';
      2. char letter2=(char)(letter1 + 1);
      3. char letter3=letter2;
    3. Since (letter1+1) is a 32 bit operation we need to typecast the same back to 16 bit char.
    4. On the other hand an increment operation automatically typecasts to char so if
      1. char letter1='A' then
      2. ++letter1='B' and so on.
    5. To see hexadecimal code of a character you may use.
      1. Integer.toHexstring(letter);
    6. To see Decimal value of letters use (int)letter1.
    Bitwise Operators
    1. & And
    2. |   Or
    3. ^  Exclusive Or
    4. ~ Complement
    5. Bitwise And Truth Table
      1. 1&0=0
      2. 0&1=1
      3. 0&0=0
      4. 1&1=1
    6. Bitwise Or Truth Table
      1. 1|0=1
      2. 0|1=1
      3. 1|1=1
      4. 0|0=0
    7. Bitwise Exor Truth Table
      1. 1^0=1
      2. 0^1=1
      3. 1^1=1
      4. 0^0=0
    8. Complement Truth Table
      1. ~1=0
      2. ~0=1
    Using And,Or operators
    1. And and Or operators can be used for masking operations.If we look closely the & operator turns off the bits where the value of our mask is 0 and leaves the others.
    2. Or operator on the other hand forces the bit to be 1 where mask is 1 and a mask bit of 0 leaves the bit unchanged.
      1. 1011 & 0011=0011
      2. 1001 | 0011=1011
      3. Here 0011 is Mask bit in both the cases
    Using Exclusive OR operator
    1. The ^ operator can interchange 2 values without moving either value somewhere else.Its a simple program.
      1. a^=b
      2. b^=a
      3. a^=b
    Let us look at an calculator example which shows type of operations discussed till now.
     public class calc {  
       private final int digit1;  
       private final int digit2;  
       public calc(int digit1,int digit2)  
       {  
         this.digit1=digit1;  
         this.digit2=digit2;  
       }  
       public int add()  
       {  
         return digit1+digit2;  
       }  
       public int subtrct()  
       {  
         return digit1-digit2;  
       }  
       public int divide()  
       {  
         return digit1/digit2;  
       }  
       public int multiply()  
       {  
         return digit1*digit2;  
       }  
       public int remainder()  
       {  
         return digit1%digit2;  
       }  
       public void swap()  
       {  
         int d1=this.digit1;  
         int d2=this.digit2;  
         System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
         System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
         d1^=d2;  
         System.out.println("After d1^=d2");  
         System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
         System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
         d2^=d1;  
         System.out.println("After d2^=d1");  
         System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
         System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
         d1^=d2;  
         System.out.println("After d1^=d2");  
         System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
         System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
       }  
       public void increment()  
       {  
         System.out.println("Digit 1 is :"+this.digit1);  
         int d1=this.digit1;  
         System.out.println("Digit 1++ is :" + (d1++));  
         System.out.println("Now Digit 1 is :" + d1);  
         d1=this.digit1;  
         System.out.println("++Digit 1 is :" + (++d1));  
         System.out.println("Now Digit 1 is :" + d1);  
       }  
       public void decrement()  
       {  
         System.out.println("Digit 1 is :"+this.digit1);  
         int d1=this.digit1;  
         System.out.println("Digit 1-- is :" + (d1--));  
         System.out.println("Now Digit 1 is :" + d1);  
         d1=this.digit1;  
         System.out.println("--Digit 1 is :" + (--d1));  
         System.out.println("Now Digit 1 is :" + d1);  
       }  
       public void shortsum()  
       {  
         short c1=5;  
         short c2=10;  
         short sum=(short)(c1+c2);  
         c1++;  
         System.out.println("C1 after increment "+c1);  
         System.out.println("Short Sum : "+sum);  
         int c3='a';  
         System.out.println(c3);  
       }  
       public static void main(String[] args)  
       {  
         //Division of -ve largest magnitude integer  
         calc c1=new calc(-2147483648,-1);  
         System.out.println(c1.divide());  
         //Division by zero  
         calc c5=new calc(25,0);  
         System.out.println(c5.divide());  
         //Increment and Decrement  
         calc c2 = new calc(11,14);  
         c2.increment();  
         c2.decrement();  
         //Short Sum  
         calc c3 = new calc(11,14);  
         c3.shortsum();  
         //Xor Swap  
         calc c4 = new calc(25,30);  
         c4.swap();  
       }  
     }  
    

    As we see when we divide largest magnitude negative integer by -1 we get the same number then we have an exception for division by zero.
    Next I have commented that code and recompiled and again executed we can see postfix and prefix outputs.
    Next we have summed 2 short integers.Also we have an output for swapping 2 integers by Exclusive OR operation along with their binary

    Shift Operations

    1. You can shift the bits of an integer to either right or left.Shifting binary value to left multiplies the value by 2.
    2. Shifting to right one bit divides by 2.
    3. Java has 3 shift operators
      1. <<shifting left filling zeros from right
      2. >>shifting right, propagating the sign bit from left
      3. >>>shifting right,filling with zeros from left.
    Methods for Bit wise operations

    1. The methods for bitwise operations are also predefined in Integer and Long wrapper classes in Java.lang package.
    2. The methods are for int and long datatypes respectively.
      1. bitcount(arg)
      2. highestOneBit(arg)
      3. lowestOneBit(arg)
      4. numberOfLeadingZeros(arg)
      5. numberOfTrailingZeros(arg)
      6. reverse(arg)
      7. rotateLeft(arg,distance)
      8. rotateRight(arg,distance)
    Now let us look at another example where we will play with letters apply binary operations on them.Use them for shift operator examples and check their hexadecimal values incrementing them each.
    1:  public class alphabets   
    2:  {  
    3:    public void binaryOperations()  
    4:    {  
    5:      char c1='A';  
    6:      char c2='Z';  
    7:      System.out.println("Char\tBinary");  
    8:      System.out.println(c1+"\t"+Integer.toBinaryString(c1));  
    9:      System.out.println(c2+"\t"+Integer.toBinaryString(c2));  
    10:      int c3=(int)c1&(int)c2;  
    11:      System.out.println(c1+"&"+c2+"="+(char)c3+"\tBinary:"+Integer.toBinaryString(c3));  
    12:      int c4=(int)c1|(int)c2;  
    13:      System.out.println(c1+"|"+c2+"="+(char)c4+"\tBinary:"+Integer.toBinaryString(c4));  
    14:      int c5=(int)c1^(int)c2;  
    15:      System.out.println(c1+"^"+c2+"="+(char)c5+"\tBinary:"+Integer.toBinaryString(c5));  
    16:      int c6=~c1;  
    17:      System.out.println("~"+c1+"="+(char)c6+"\tBinary:"+Integer.toBinaryString(c6));  
    18:    }  
    19:    public long packLetters()  
    20:    {  
    21:      char c1='A';  
    22:      char c2='B';  
    23:      char c3='C';  
    24:      char c4='D';  
    25:      long packed=0L;  
    26:      packed=c4;  
    27:      packed=(packed << 16)|c3;  
    28:      packed=(packed << 16)|c2;  
    29:      packed=(packed << 16)|c1;  
    30:      return packed;  
    31:    }  
    32:    public void unpackLatters(long pack)  
    33:    {  
    34:      System.out.println("Packed now contains Hex 0X"+Long.toHexString(pack));  
    35:      System.out.println("Packed now contains Binary "+Long.toBinaryString(pack));  
    36:      long mask=0XFFFF; //Left 16 Bits as 1111111111111111  
    37:      char letter=(char)(pack&mask);  
    38:      System.out.println("From right to left the letters in packed are:");  
    39:      System.out.println("Charcter :"+letter+" Hex: 0X"+Long.toHexString(letter));  
    40:      pack>>=16;  
    41:      System.out.println("Packed now contains Binary "+Long.toBinaryString(pack));  
    42:      letter=(char)(pack&mask);  
    43:      System.out.println("Charcter :"+letter+" Hex: 0X"+Long.toHexString(letter));  
    44:      pack>>=16;  
    45:      System.out.println("Packed now contains Binary "+Long.toBinaryString(pack));  
    46:      letter=(char)(pack&mask);  
    47:      System.out.println("Charcter :"+letter+" Hex: 0X"+Long.toHexString(letter));  
    48:      pack>>=16;  
    49:      System.out.println("Packed now contains Binary "+Long.toBinaryString(pack));  
    50:      letter=(char)(pack&mask);  
    51:      System.out.println("Charcter :"+letter+" Hex: 0X"+Long.toHexString(letter));  
    52:    }  
    53:    public void showAllAlphabets()  
    54:    {  
    55:      char c1;  
    56:      System.out.println("Char\tDec\tHex\tBinary");  
    57:      for(c1='A';c1<='z';c1++)  
    58:      {  
    59:        System.out.println(c1+"\t"+(int)c1+"\t"+Integer.toHexString(c1)+"\t"+Integer.toBinaryString(c1));  
    60:      }  
    61:    }  
    62:    public static void main(String args[])  
    63:    {  
    64:      alphabets a1=new alphabets();  
    65:      a1.showAllAlphabets();  
    66:      a1.binaryOperations();  
    67:      long pack=a1.packLetters();  
    68:      a1.unpackLatters(pack);  
    69:    }  
    70:  }  
    

    So we have incremented characters here starting from A till z and shown their Decimal,Hex and Binary value.
    Next we have selected 2 alphabets A and Z and performed some binary operations on them.Note that since Binary operators perform 32 bit operations so when we negate "A" the left least significant 16 bits also negate and hence we get a 32 bit result here.
    Next we have packed certain characters using shift operations in a string and then unpacked them.


    Variables with a Fixed Set of Integer Values
    1. Such custom variables are called as enumeration variables or enum for example a variable weekday should have only fixed set of values corresponding to days.
      1. enum Day {Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}
      2. This defines a new type Day for variables that can store only one of the above values specified in braces.
      3. These values are called as enumeration constants.
      4. There is no semicolon at the end of the statement.You can define a new variable as Day weekday=Day.Tuesday.
      5. Each value of enumeration variable belongs to an Integer value location 0,1 but it is not of type Integer.
    Lets look at an enumeration example.We have two files here one to define enumeration type and other to use the same
    File : operation.java
    1:  public enum operation{  
    2:      PLUS(-2147483648,-1),  
    3:      MINUS(-2147483648,-1),  
    4:      TIMES(-2147483648,-1),  
    5:      DIVIDE(-2147483648,-1);  
    6:      private final int num1;  
    7:      private final int num2;  
    8:      operation(int num1,int num2)  
    9:      {  
    10:        this.num1=num1;  
    11:        this.num2=num2;  
    12:      }  
    13:      int calculate()   
    14:      {  
    15:        switch(this)   
    16:        {  
    17:          case PLUS:  
    18:            return this.num1 + this.num2;  
    19:          case MINUS:  
    20:            return this.num1 - this.num2;  
    21:          case TIMES:  
    22:            return this.num1 * this.num2;  
    23:          case DIVIDE:  
    24:            return this.num1 / this.num2;  
    25:          default:  
    26:            throw new AssertionError("Unknown operations " + this);  
    27:        }  
    28:      }  
    29:    }  
    
    File : enumeration.java
    1:  public class enumeration   
    2:  {  
    3:    public static void main(String args[])  
    4:    {  
    5:      int result = operation.DIVIDE.calculate();  
    6:      System.out.println(result);  
    7:      result = operation.PLUS.calculate();  
    8:      System.out.println(result);  
    9:    }  
    10:  }  
    

    Here we have an enumeration type taking from previous example of division highest -ve number in operation.java.
    We have defined our variables to perform operations and set the constructor accordingly.
    Then we have defined a function which depending upon variable name performs an operation.
    Since our class is in global package it is accessible to another class in same package  enumeration.java.

    Boolean Variables
    1. These variables can only have one of the 2 types TRUE or FALSE.
    2. The values true and false are boolean literals.
    3. boolean state=true;state=false;
    4. operators that work on boolean values are called as boolean operators example
      1. boolean AND
      2. boolean OR
      3. boolean negation
    Operator Precedence
    1. (),[],postfix++,postfix--(Associativity : Left)
    2. Unary+,Unary-,prefix++,prefix--,~(Associativity : right)
    3. (type),new(Associativity : Left)
    4. *,/,%(Associativity : Left)
    5. +,-(Associativity : Left)
    6. <<,>>,>>>(Associativity : Left)
    7. <,<=,>,>=,instanceOf(Associativity : Left)
    8. ==,!=(Associativity : Left)
    9. &(Associativity : Left)
    10. ^(Associativity : Left)
    11. |(Associativity : Left)
    12. &&(Associativity : Left)
    13. ||(Associativity : Left)
    14. ?:(Associativity : Left)
    15. =,+=,-=,*=,/=,%=,<<=,>>=,>>>=,&=,\=,^=(Associativity : right)
    All operators execute according to their precedence.Operators in same line execute according to their associativity for example

    int noOfAnimals=Horses+++Elephants; will execute as (horses++) + elephants;

    Comments
    1. There are 2 types of comments
      1. single line comment //
      2. multiple line comments /**/
    2. Documentation Comments
      1. These are processed by javadoc
        1. @author
        2. @depriciated
        3. @exception
        4. @link
        5. @param
        6. @return
        7. @see
        8. @throws
        9. @version
    Description of these comments is easily recognizable from their names itself.

    No comments:

    Post a Comment