Pages

Java

Introduction

Java is a programming language licensed by Oracle

Java Keywords are always lower-case letters.
Java is a case sensitive language

Java Keywords
  1. abstract
  2. assert
  3. boolean
  4. break
  5. byte
  6. case
  7. catch
  8. class
  9. const
  10.  continue
  11. default
  12. do
  13. double
  14. else
  15. enum
  16. extends
  17. final
  18. finally
  19.  float
  20. for
  21. goto
  22. if
  23. implements
  24. imports
  25. instance of
  26. int
  27. interface
  28. long
  29. native
  30. new
  31. package
  32. private
  33. protected
  34. public
  35. return
  36. short
  37. static
  38. strict
  39. super
  40. void
  41. volatile
  42. while
  43. this
  44. transient
  45. try
  46. switch
  47. synchronized
  48. throws
  49. throw
 Java Main Method

1.
public static void main(String [] args)
{
}

2.
public static void main(String args[])
{
}
3.
public static void main(String..args)
{
}

Primitive types
Primitive types are types that are built in to the Java language. Variables of the
primitive types store numerical values that are integers or fl oating-point values,
Boolean values, or Unicode characters.

Identifiers
Identifiers is the name of a variable. This is User defined.

The basic difference between an identifier and a keyword is Identifier is user defined while Keyword is Predefined.

Access Modifiers
Class Package SubClass World
Public Y Y Y Y
Protected Y Y Y N
noModifier Y Y N N
Private Y N N N

Protected Access Modifier variables are available to subclass if it is of another package.

We can't import classes from default package

Class/Object Structure in Java

Consider a simple Java statement
System.out.println("");
Here
  1. System is the base class which contains object "out".
  2. Out is a static variable in class system
  3. println() is a method in object out
Overview of JDK 1.7.0

JDK 1.7.0 has the following folder structure
  1. bin - Compiler,Interpreter + other executables
  2. demo - Subdirectories containing Demo
  3. include - header files for native code
  4. sample
  5. JRE
    1. Bin - Executables for runtime
    2. Lib - Class Libraries
  6. Lib - Files used by executables
java.lang Package

A package that contains classes that support the basic language feature and the handling of arrays  and string. Classes in this package are always available in your programs by default because this package is automatically loaded with program.

Various Packages in Java
  1. java.io - Input/Output operations
  2. java.nio.file - classes for file input and output
  3. java.util -
    1. Utility classes for various winds
    2. includes classes for managing data
  4. javax.swing - easy to use and flexible components for building gui's
  5. java.awt - classes and packages that provide GUI components
  6. java.awt.geom - 2D geometric shapes
  7. java.awt.event -handle events in windowed application
Integer Data type

The integer types are byte, short, int, and long, and variables of these types
occupy 1, 2, 4, and 8 bytes, respectively.

Negative Numbers are stored as 2's complement form.
Hexadecimal Literals 0X1234
Binary Litrals 0B1100101
Octal Literals 0777,07772

Integer expressions are evaluated using 64-bit operations for variables of type long
and using 32-bit operations for all other integer types. You must, therefore, add a cast
for all assignment operations storing a result of type byte, type short, or type char.

Example 1
(Basic Example)
public class Fruit {
    public static void main(String[] args) {
        int numOranges=5;
        int numApples=10;
        int numFruits;
       
        numFruits=numApples+numOranges;
        // No need to include java.io
        System.out.println("My Fruits Total");
        System.out.println("Total Fruits are : "+numFruits);
    }
} 

Example 2
(Example with import)
import java.io.IOException;

public class Fruit {

    public static void main(String[] args) {
        // TODO code application logic here
        int numOranges=5;
        int numApples=10;
        int numFruits;
       
        numFruits=numApples+numOranges;
        System.out.println("My Fruits Total");
        System.out.println("Total Fruits are : "+numFruits);
        System.out.println("Press Enter to Exit");
        try
        {
            System.in.read();
        }
        catch(IOException e) //Imported Package
        {
            return;
        }
    }
}

The Main Method
Public : Specifies that method is accessible from outside fruit class
Static : Specifies that method is a class method that is made to be executable even though no class objects have been created
void : specifies that method does not return a value

Operators
  1. Increment and Decrement Operators
  2. Assignment Operators
  3. Arithmetic Operator
Explicit Casting
short numOranges=5;
short numApples=10;
short numFruit=0;

numFruit=numOranges+numApples; // This returns an error since sum returns an integer
numFruit=(short)(numOranges+numApples); // Explicit casting

Automatic type Conversions Order(From higher to lower)
  1. Double
  2. Float
  3. Long
  4. Int
  5. Short
  6. Byte
Characters occupy 2 bytes
Error Types
  1. Integer Arithmetic Error
    1. Division By Zero
  2. Floating Point Arithmetic Error
    1. Out of Range
    2. Divide by Zero
Example 3
Floating Magic

public class Fruits {
    public static void main(String args[])
    {
        int numOranges=5;
        int numApples=10;
        double averageFruit=0.0;
        double fruitTypes=0.0;
        averageFruit=(numOranges+numApples)/fruitTypes;
        System.out.println("Average fruit is "+averageFruit);
    }
}
Output : Average fruit is Infinity

Infinity means a positive but effectively infinite result that is greater than the largest number that can be stored in double

Character Types
Variables of type char occupy 2 bytes and can store a single Unicode character code.

Example 4
Character Arithmetic

public class CharCodes {
    public static void main(String args[])
    {
        char letter1='A';
        char letter2=(char)(letter1+1); //Typecasting is needed else result will be numeric
        char letter3=letter2;
        System.out.println("Here's a sequance of letters :"+letter1+letter2+(++letter3));
        System.out.println("Here are the decimal codes for letters \n"+letter1+" : "+(int)letter1+" "+letter2+" : "+(int)letter2+" "+letter3+" : "+(int)letter3);
    }
}

Output :
Here's a sequance of letters :ABC
Here are the decimal codes for letters
A : 65 B : 66 C : 67

Bitwise & and |
  1. (And-off)bitwise & - switch off specific bits in a word
  2. (Or-On)bitwise | - forces a bit to be On(1) in a variable when the corresponding mask bit is 1.
Example 5
Bitwise And and Or Example
import static java.lang.Integer.toBinaryString;

public class BitwiseOps {
 public static void main(String args[])
 {
     //Bitwise And
     int indicators=0b1111_1111_0000_0111;
     int selectBit3=0b0000_0000_0000_0100;
     System.out.println("indicators= "+toBinaryString(indicators));
     System.out.println("selectBit3= "+toBinaryString(selectBit3));
     indicators &= selectBit3;
     System.out.println("indicators & select Bit 3="+toBinaryString(indicators));
    
     //Bitwise Or
     indicators=0b1111_1111_0000_1001;
     System.out.println("\nindicators="+toBinaryString(indicators));
     System.out.println("selectBit3="+toBinaryString(selectBit3));
     indicators |=selectBit3;
     System.out.println("indicators|selectBit3="+toBinaryString(indicators));
    
     //Now switch thirdbit off again
     indicators &= ~selectBit3;
     System.out.println("\n The third bit in the previous value of indicators" + "has been switched off");
     System.out.println("indicators &~ selectBit3="+toBinaryString(indicators));
 }
}
Output :
indicators= 1111111100000111
selectBit3= 100
indicators & select Bit 3=100

indicators=1111111100001001
selectBit3=100
indicators|selectBit3=1111111100001101

 The third bit in the previous value of indicators has been switched off
indicators &~ selectBit3=1111111100001001

Shift Operations

<>> shift right,propogating the sign bit from left
>>>shift right,filling with zeros from left

Shift Operators

  1. << shift left
    1. a=1110011011
    2. a<<3 br="">
    3. a=0011011000(bits in bold are lost)
  2. >>> shift right filling with zeros from left
    1. a=1110011011
    2. a>>>3
    3. a=0001110011(bits in bold are lost)
  3. >> shift right propogating sign bit from left
    1. a=1110011011
    2. a>>3
    3. a=1111110011(bits in bold are lost)
Example 6
Shift And Or Operations 
  public class PackingCharacters {
    public static void main(String args[])
    {
        char letterA='A';
        char letterB='B';
        char letterC='C';
        char letterD='D';
        long packed=0L;
        packed = letterD;
        packed=(packed<<16 br="" letterc="">        packed=(packed<<16 br="" letterb="">        packed=(packed<<16 br="" lettera="">        System.out.println("Packed Now contains 0x"+ Long.toHexString(packed));
        //Now Unpack the letters and Output them
        long mask=0XFFFF;//Rightmost 16 bits as 1
        char letter=(char)(packed & mask);// Extract the right most Letter
        System.out.println("From right to left the letters i packed are");
        System.out.println(" "+letter+" 0x"+Long.toHexString(letter));
        packed>>=16;//shift out the rigt most letter
        letter=(char)(packed&mask);
        System.out.println(" "+letter+" 0x"+Long.toHexString(letter));
        packed>>=16;//shift out the rigt most letter
        letter=(char)(packed&mask);
        System.out.println(" "+letter+" 0x"+Long.toHexString(letter));
        packed>>=16;//shift out the rigt most letter
        letter=(char)(packed&mask);
        System.out.println(" "+letter+" 0x"+Long.toHexString(letter));
    }
}
Output :
Packed Now contains 0x44004300420041
From right to left the letters i packed are
 A 0x41
 B 0x42
 C 0x43
 D 0x44

Bitwise operations Methods
  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);
Example 7
Bit Methods
import static java.lang.Long.*;

public class TryBitMethods {
    public static void main(String[] args)
    {
        long number=0xF000_0000_0000_000FL;
        System.out.println("number:\n"+ toBinaryString(number));
        long result=rotateLeft(number,2);
        System.out.println("Number rotated Left 2 bits:\n"+toBinaryString(result));
        result=rotateRight(number,3);
        System.out.println("Number rotated Right 3 bits:\n"+toBinaryString(result));
        result=reverse(result);
        System.out.println("Previous result reversed:\n"+toBinaryString(result));
        System.out.println("Bit Count in number : "+ bitCount(number));
    }
}
Output :
1111000000000000000000000000000000000000000000000000000000001111
Number rotated Left 2 bits:
1100000000000000000000000000000000000000000000000000000000111111
Number rotated Right 3 bits:
1111111000000000000000000000000000000000000000000000000000000001
Previous result reversed:
1000000000000000000000000000000000000000000000000000000001111111
Bit Count in number : 8

Enum Variables
Used for variables which have a specific set of values
eg : enum Day {Mon,Tue,Wed,Thurs,Fri,Sat,Sun}

Example 8
Enumeration Example

public class TryEnumeration {
    enum Day{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday};
 
    public static void main(String args[])
    {
        Day yesterday=Day.Thursday;
        Day today=Day.Friday;
        Day tomorrow=Day.Saturday;
     
        System.out.println("Today is "+today);
        System.out.println("Tomrrow will be "+tomorrow);
        System.out.println("Yesterday was "+yesterday);
    }

}
Output :
Today is Friday
Tomrrow will be Saturday
Yesterday was Thursday

Boolean Variables
These variables can have values either true or false

Operator Association and Precedence in Java
Operator Precedence Group Association
Operator precedence Group
(),[],postfix++,postfix--
left
Unary+,Unary-,prefix++,prefix--,~ right
(type),new left
*,/% left
+,- left
<<,>>,>>>>left
<,<=,>,>=,instance of left
==,!= left
& left
^ left
| left
&& left
|| left
? left
=,+=,-=,*=,/=,%=,<<=,>>=,>>>=,&=,\=,^= right

Example 8
Operator Precedence Example

public class OperatorPrecedence {
    public static void main(String args[])
    {
        int a=1,b=1,c=1,d=1;
        int result = a+=b=c+=d=10;
        System.out.println(result);
    }

}

Program Comments
//-used to comment lines of code
Documentation Comments
/**
* - used for documentation in program
*/
Can include HTML tags as well as special tags beginning with @

Tag Keywords
  1. @author
  2. @depreciated
  3. @exception
  4. @link
  5. @param
  6. @return
  7. @see
  8. @throws
  9. @version
Loops and Logics
  1. > left greater than right
  2. >= left greator than equal to right
  3. == both left and right are equal
  4. !=  not equal to
  5. <= less than equal to
  6. < less than
The if statement
if(expression)
execute statement1
else
execute statement 2

Example 9 
Nested If Example

public class LetterCheck {
    public static void main(String[] args)
    {
        char symbol='A';
        symbol=(char)(128.0*Math.random());
        if(symbol>='A')
        {
            if(symbol<='Z')
            {
                System.out.println("You have the capital letter "+symbol);
            }
            else
            {
                if(symbol>='a')
                {
                    if(symbol<='z')
                    {
                        System.out.println("You have a small letter "+symbol);
                    }
                    else
                    {
                        System.out.println("The code is greater than a but not a letter");
                    }
                }
                else
                {
                    System.out.println("The code is less than a and it's not a letter");
                }
            }
        }
        else
        {
            System.out.println("The code is less than A so it is not a letter");
        }
    }
}

Above example can be simplified using logical operators as follows

public class LetterCheck2
{
    public static void main(String[] args)
    {
        char symbol = 'A';
        symbol = (char)(128.0*Math.random());
        // Generate a random character
        if(symbol >= 'A' && symbol <= 'Z')
        {
            // Is it a capital letter
            System.out.println("You have the capital letter " + symbol);
        }
        else
        {
            if(symbol >= 'a' && symbol <= 'z')
            {
                // or is it a small letter?
                System.out.println("You have the small letter " + symbol);
            }   
            else
            {
                // It is not less than z
                System.out.println("The code is not a letter");
            }
        }
    }
}

Comparing Enum Values

enum Season {spring,summer,fall,winter}
Season seson=Season.summer;
if(season.equals(Season.spring))
{
   System.out.println("Spring is here");
}

Season best=Season.winter;
if(season.equals(best))
{
 System.out.println("season is "+best)
}

Logical And Operation
&& Vs &

&& does not evaluate the right hand operand if left hand operand is false.
& executes both the operands and is useful when we have an operation such as increment on the right hand side
For example

int number=50;
if(number<40 amp="" number-27="">100)
{
   System.out.println("number = "+number);
}
The effect is different

Logical OR operations

Returns true when either one or both are true.
The logical OR works in a similar way to && operator it omits evaluation  of right hand operator if left hand operand is true.

Boolean Not operations
Results in the inverse of the operand value. i.e. if state is true returns false if state is false returns true.

if(!(age>=16 && age <65 p="">{
  ticketprice*=0.9;
}


Example 10
Character Testing using standard Library Methods
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;

public class LetterCheck3 {
 
    public static void main(String args[])
    {
        char symbol='A';
        symbol=(char)(127.8*Math.random());
        if(isUpperCase(symbol))
        {
            System.out.println("You have a capital Letter "+symbol);          
        }
        else
        {
            if(isLowerCase(symbol))
            {
                System.out.println("You have a small letter "+ symbol);
            }
            else
            {
                System.out.println("The code is not a letter");
            }
        }
    }
}

Other Methods for testing Characters
  1. isDigit()
  2. isLetter()
  3. isLetterOrDigit()
  4. isWhiteSpace()
Conditional Operator

older=yourage>myage?yourage:myage;

if(yourAge>myAge)
{
  older=yourAge;
}
else
{
  older=myAge;
}

The switch statement

switch(wash)
{
    case 1:
      System.out.println("Cotton");
      break; 
   case 2:
      System.out.println("Cotton");
      break;
default:
      System.out.println("error");
      break;
}

Example 11
Switch Controlled by Integer Type and Enumeration Type

public class TrySwitch
{
    enum WashChoice {cotton, linen, wool, synthetic} // Define enumeration type
    public static void main(String[] args)
    {
        // Variable to define the choice of wash
        WashChoice wash = WashChoice.cotton;
        // The clothes variable specifi es the clothes to be washed by an integer
        // 1:shirts 2:sweaters 3:socks 4:sheets 5:pants
        int clothes = 3;
        switch(clothes)
        {
            case 1:
                System.out.println("Washing shirts.");
                wash = WashChoice.cotton;
                break;
            case 2:
                System.out.println("Washing sweaters.");
                wash = WashChoice.wool;
                break;
           case 3:
                System.out.println("Washing socks.");
                wash = WashChoice.wool;
                break;
           case 4:
                System.out.println("Washing sheets.");
                wash = WashChoice.linen;
                break;
           case 5:
                System.out.println("Washing pants.");
                wash = WashChoice.synthetic;
                break;
          default:
                System.out.println("Unknown washing - default synthetic.");
                wash = WashChoice.synthetic;
                break;
        }

        System.out.println("Wash is "+ wash);
        // Now select the wash temperature
        switch(wash)
        {
            case wool:
                    System.out.println("Temperature is 120.");
                    break;
            case cotton:
                    System.out.println("Temperature is 170.");
                    break;
            case synthetic:
                    System.out.println("Temperature is 130.");
                    break;
            case linen:
                    System.out.println("Temperature is 180.");
                    break;
        }
    }
}

Loops
  1. The Numerical for Loop
    1. for (initialization_expression ; loop_condition ; increment_expression) {
    2. // statements
    3. }
  2. The Collection-Based For Loop
    1. for (type identifier : iterable_expression) {
    2. // statements
    3. }
  3. The While Loop
    1. while (expression) {
    2. // statements
    3. }
  4. The Do-While Loop
    1. do {
    2. // statements
    3. } while (expression);
Example 12 : Collection For Loop

public class CollectionForLoop {
    enum Season { spring, summer, fall, winter }
    // Enumeration type defi nition
    public static void main(String[] args) {
    for(Season season : Season.values()) {
    // Vary over all values
    System.out.println(" The season is now " + season);
        }
    }
}

Continue Statement
Used to skip a part of an iteration based on a condition

for(int i = 1; i <= limit; ++i) {
if(i % 3 == 0) {
continue;
}
sum += i;
}


The Labelled Continue Statement
Breaks the inner loop on a condition but continues to the outer loop.Below Example omits the calculation of factorials of odd numbers greater than
10.


Example 13 : Labelled Continue Statement

public class Factorial {
    public static void main(String[] args)
    {
        long limit = 20L;
        // to calculate factorial of integers up to this value
        long factorial = 1L; // factorial will be calculated in this variable
        // Loop from 1 to the value of limit
        OuterLoop:
        for(long i = 1L; i <= limit; ++i)
        {
            factorial = 1;
            // Initialize factorial
            for(long j = 2L; j <= i; ++j)
            {
                if(i > 10L && i % 2L == 1L)
                {
                    continue OuterLoop;
                    // Transfer to the outer loop
                }
                factorial *= j;
            }
            System.out.println(i + "! is " + factorial);
        }
    }
}

Break Statement

This is used to Breaks a loop

Example 14: Break Statement
public class Prime {
    public static void main(String[] args)
    {
        int nValues = 50;
        // The maximum value to be checked
        boolean isPrime = true; // Is true if we fi nd a prime
        // Check all values from 2 to nValues
        for(int i = 2; i <= nValues; ++i)
        {
            isPrime=true;
            // Assume the current i is prime
            // Try dividing by all integers from 2 to i-1
            for(int j = 2; j < i; ++j)
            {
                if(i % j == 0)
                {
                    // This is true if j divides exactly
                    isPrime = false;
                    // If we got here, it was an exact division
                    break;
                    // so exit the loop
                }
            }
            // We can get here through the break, or through completing the loop
            if(isPrime)
            // So is it prime?
            System.out.println(i);
            // Yes, so output the value
        }
    }
}

Labelled Break Statement
Just like Labelled Continue statement the labeled break enables you to break out to the statement following an enclosing block or loop that has
an identifying label, regardless of how many levels of nested blocks there are.

Assertions
Used for statements that should be true always.They could be executed in theory,in practice they are never executed

Used in circumstances where if the statements the statements were to executed it would mean that something is wrong with program or envirnoment.

assert logical_expression

If logical expression returns true it means program executes normally else program halts with error message.

java.lang.assertion.error

Complex Assertions
assert logical expression : string_expression
If logical expression is false then the program terminates with an error message including the string that results from string_expression

assert false:"days in month has the value "+daysInMonth

Example 15 Assertions
public class TryAssertions {
    public static void main(String args[]) {
        int daysInMonth = 32;
        if(daysInMonth == 30) {
            System.out.println("Month is April, June, September, or November");
            }
        else if(daysInMonth == 31) {
            System.out.println("Month is January, March, May, July, August, October, or December.");
        }
        else if(daysInMonth == 28 || daysInMonth == 29)
        {
            System.out.println("Month is February.");
        }
        else
        {
            assert false;
        }
    }
}

After compile
Execute as follows
java -enableassertions TryAssertions

Arrays

An array is an object that is a named set of variables of the same type.Each variable in array is called an array element.
You can refer to the length of an array using "length",a data member of the array object.
Arrays can be initialized via utility methods for example

Arrays.fill(data,1.0); for this import java.util.Arrays

We can also have a static import for Java.util.Arrays.fill(since fill is static method);

long[] even ={2L,4L,6L,8L,10L};
long[] values=even;
values[2]=even[2] // same memory location

double[] inputArray=new double[100];
double[] outputArray=new double[100];
double[] temp;

temp=inputArray;
inputArray=outputArray;
outputArray=temp;

No elements are moved here just the addresses are swapped.This is a fast process.

Using Collection based for loop with Arrays

double sum = 0.0;
for(double value : samples) {
sum += value;
}

Example 16: Primes Extended
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;

public class MorePrimes {
    public static void main (String args[])
    {
        long[] primes= new long[20];
        primes[0]=2L;
        primes[1]=3L;
        int count=2;
        long number=5L;
       
        outer:
        for( ; count < primes.length; number += 2L) {
           
            long limit=(long)ceil(sqrt((double)number));
            for(int i = 1; i < count && primes[i] <= limit; ++i)
            {
               if(number%primes[i] == 0L)
               {
                   continue outer;
               }
            }
            primes[count++] = number;
        }
        for(long n : primes)
        {
            System.out.println(n);
        }
    }
}
 
Here we divide the number at max by its square root because of following reason.
For every factor a number has that is greater than the square
root of the number, the result of division by this factor is another factor that is less than the square root. You
perhaps can see this more easily with a specifi c example. The number 24 has a square root that is a bit less than 5.
You can factorize it as 2 * 12, 3 * 8, 4 * 6; then you come to cases where the fi rst factor is greater than the square
root so the second is less, 6 * 4, 8 * 3, and so on, and so you are repeating the pairs of factors you already have.
The only even prime number we can think of is 2 hence we increment by 2 after 3 for odd numbers.


No comments:

Post a Comment