Sunday, August 24, 2014

Classes.

Classes.
CLASS declarations define new reference types and describe how they are implemented. A top level class is a class that is not a nested class.

A nested class is any class whose declaration occurs within the body of another class or interface.

A named class may be declared abstract and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. . A class may be declared final in which case it cannot have subclasses.

If a class is declared public, then it can be referred to from other packages.

Each class except Object is an extension of (subclass) a single existing class and may implement interfaces. Classes may be generic, that is, they may declare type variables whose bindings may differ among different instances of the class.

Class declaration:
A class declaration defines new named reference.

There are two kinds of class declarations: normal class declarations and enum declarations.

Class modifier.
The access modifier public pertains only to top level classes and member classes, not to local classes or anonymous classes.

The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration.The modifier static pertains only to member classes, not to top level or local or anonymous classes.

Abstract classes.
  An abstract class is a class that is incomplete, or to be considered incomplete. It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression

final Classes
  A class can be declared final if its definition is complete and no subclasses are
desired or required.

strictfp Classes
  The effect of the strictfp modifier is to make all float or double expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) be explicitly FP-strict. This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp.


Generic classes and type parameter.
  A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. The type parameter section follows the class name and is delimited by angle brackets.

Mutually Recursive Type Variable Bounds.

interface ConvertibleTo<T> {
  T convert();
}

class ReprChange<T extends ConvertibleTo<S>, S extends ConvertibleTo<T>> {
  T t;
  void set(S s) {
    t = s.convert();
  }

  S get() {
    return t.convert();
  }
}

Nested Generic Classes.

class Seq<T> {
  T head;
  Seq<T> tail;

  Seq() {
    this(null, null);
  }

  Seq(T head, Seq<T> tail) {
    this.head = head;
    this.tail = tail;
  }

  boolean isEmpty() {
    return tail == null;
  }   
  class Zipper<S> {
    Seq<Pair<T,S>> zip(Seq<S> that) {
    
      if (isEmpty() || that.isEmpty()) { 
        return new Seq<Pair<T,S>>(); 
      }   
      else { 
        Seq<T>.Zipper<S> tailZipper = tail.new Zipper<S>(); 
        return new Seq<Pair<T,S>>( new Pair<T,S>(head, that.head), tailZipper.zip(that.tail));
      }   
    }   
  }
}
class Pair<T, S> {
  T fst; S snd;
  Pair(T f, S s) {
    fst = f; snd = s;
  }
}

class Test {
  public static void main(String[] args) {
    Seq<String> strs = new Seq<String>("a",new Seq<String>("b", new Seq<String>()));
    System.out.println(strs.toString());
    Seq<Number> nums = new Seq<Number>(new Integer(1), new Seq<Number>(new Double(1.5), new Seq<Number>()));
    Seq<String>.Zipper<Number> zipper = strs.new Zipper<Number>();
    Seq<Pair<String,Number>> combined = zipper.zip(nums);
  }
}

Inner class and enclosing instances.
class HasStatic { 
  static int j = 100; 
}

class Outer { 
  class Inner extends HasStatic { 
    static final int x = 3; // OK: constant variable 
    //static int y = 4; // Compile-time error: an inner class 
  }

  static class NestedButNotInner{
    static int z = 5; // OK: not an inner class
  }

  interface NeverInner {} // Interfaces are never inner 
}

Deeply nested class.
class WithDeepNesting { 
  boolean toBe;
  
  WithDeepNesting(boolean b) {
    toBe = b;
  }
  class Nested { 
    boolean theQuestion;
    class DeeplyNested {
      DeeplyNested(){
        theQuestion = toBe || !toBe; 
      }   
    }   
  }
}

Super class and subclasses.

Direct superclassesclass Point { int x, y; } 
final class ColoredPoint extends Point { int color; } 
class Colored3DPoint extends ColoredPoint { int z; } // error and subclasses.

Superclasses and subclasses.
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
final class Colored3dPoint extends ColoredPoint { int z; }

Superinterfaces.
Illegal Superinterfaces
class Redundant implements java.lang.Cloneable, Cloneable { 
 int x; 
}

-------------- ------------------------ -------------
interface Colorable {
  void setColor(int color);
  int getColor();
}

enum Finish { MATTE, GLOSSY }

interface Paintable extends Colorable { 
  void setFinish(Finish finish); 
  Finish getFinish(); 
}

class Point {
  int x, y;
}

class ColoredPoint extends Point implements Colorable { 
  int color; 
  
  public void setColor(int color) {
    this.color = color;
  }
  public int getColor() {
    return color;
  }   
}

class PaintedPoint extends ColoredPoint implements Paintable {
  Finish finish;
  
  public void setFinish(Finish finish) { 
    this.finish = finish; 
  }
  
  public Finish getFinish() {
    return finish;
  }
}

Class member.

class Point { 
  int x, y;

  /*private Point() { 
    reset();
  }*/
  
  Point() {
    reset();
  }

  Point(int x, int y) {
    this.x = x; this.y = y;
  }

  private void reset() {
    this.x = 0; this.y = 0;
  }
}

class ColoredPoint extends Point { 
  int color; 
  void clear() {
    //reset();
  } // error
  ColoredPoint() {
    super();
  }
  ColoredPoint(int x, int y) {
    super(x, y); 
  }
}

class Test { 
  public static void main(String[] args) {
    ColoredPoint c = new ColoredPoint(5, 0); // error 
    //c.reset(); // error
    System.out.println(c.x);
 }
}


ENUM

import java.util.List;
import java.util.ArrayList;

class Card implements Comparable<Card>, java.io.Serializable {
 
  public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,JACK, QUEEN, KING, ACE }
  public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
 
  private final Rank rank;
  private final Suit suit;
 
  public Rank rank() {
    return rank;
  }  
 
  public Suit suit() {
    return suit;
  }

  private Card(Rank rank, Suit suit) {
    if (rank == null || suit == null)
      throw new NullPointerException(rank + ", " + suit);
    this.rank = rank;
    this.suit = suit;
  }  

  public String toString() {
    return rank + " of " + suit;
  }

 // Primary sort on suit, secondary sort on rank
  public int compareTo(Card c) {
    int suitCompare = suit.compareTo(c.suit);
    return (suitCompare != 0 ? suitCompare : rank.compareTo(c.rank));
  }

  private static final List<Card> prototypeDeck = new ArrayList<Card>(52);
  static {
    for (Suit suit : Suit.values()) {
      System.out.println(suit);
      for (Rank rank : Rank.values())
        prototypeDeck.add(new Card(rank, suit));
    }
  }

 // Returns a new deck 
  public static List<Card> newDeck() {
    return new ArrayList<Card>(prototypeDeck);
  }

  public static void main(String[] args) {
    System.out.println(prototypeDeck);
  }
}

------------- ------------------- ----------------------- ---------------------

import java.util.List; 
import java.util.ArrayList; 
import java.util.Collections;

class Deal {
  public static void main(String args[]) {
    int numHands = Integer.parseInt(args[0]);
    int cardsPerHand = Integer.parseInt(args[1]); 
    
    List<Card> deck = Card.newDeck(); 
    System.out.println(deck);
    Collections.shuffle(deck);
    System.out.println(deck);
    
    for (int i=0; i < numHands; i++) 
      System.out.println(dealHand(deck, cardsPerHand)); 
  }
  
  public static <E extends Comparable<E>> 
  
  ArrayList<E> dealHand(List<E> deck, int n) { 
    int deckSize = deck.size(); 
    List<E> handView = deck.subList(deckSize - n, deckSize); 
    ArrayList<E> hand = new ArrayList<E>(handView); 
    handView.clear(); 
    Collections.sort(hand); 
    return hand; 
  }
}

Output:
CLUBS
DIAMONDS
HEARTS
SPADES

[DEUCE of CLUBS, THREE of CLUBS, FOUR of CLUBS, FIVE of CLUBS, SIX of CLUBS, SEVEN of CLUBS, EIGHT of CLUBS, NINE of CLUBS, TEN of CLUBS, JACK of CLUBS, QUEEN of CLUBS, KING of CLUBS, ACE of CLUBS, DEUCE of DIAMONDS, THREE of DIAMONDS, FOUR of DIAMONDS, FIVE of DIAMONDS, SIX of DIAMONDS, SEVEN of DIAMONDS, EIGHT of DIAMONDS, NINE of DIAMONDS, TEN of DIAMONDS, JACK of DIAMONDS, QUEEN of DIAMONDS, KING of DIAMONDS, ACE of DIAMONDS, DEUCE of HEARTS, THREE of HEARTS, FOUR of HEARTS, FIVE of HEARTS, SIX of HEARTS, SEVEN of HEARTS, EIGHT of HEARTS, NINE of HEARTS, TEN of HEARTS, JACK of HEARTS, QUEEN of HEARTS, KING of HEARTS, ACE of HEARTS, DEUCE of SPADES, THREE of SPADES, FOUR of SPADES, FIVE of SPADES, SIX of SPADES, SEVEN of SPADES, EIGHT of SPADES, NINE of SPADES, TEN of SPADES, JACK of SPADES, QUEEN of SPADES, KING of SPADES, ACE of SPADES]

[QUEEN of CLUBS, SEVEN of CLUBS, NINE of HEARTS, TEN of DIAMONDS, QUEEN of SPADES, KING of DIAMONDS, FOUR of HEARTS, SIX of DIAMONDS, FOUR of DIAMONDS, SIX of SPADES, JACK of DIAMONDS, TEN of HEARTS, JACK of HEARTS, EIGHT of SPADES, SEVEN of SPADES, KING of SPADES, ACE of DIAMONDS, NINE of CLUBS, FIVE of SPADES, THREE of CLUBS, ACE of SPADES, THREE of DIAMONDS, NINE of SPADES, SIX of HEARTS, DEUCE of HEARTS, DEUCE of DIAMONDS, FIVE of CLUBS, FOUR of SPADES, QUEEN of HEARTS, ACE of HEARTS, FIVE of HEARTS, EIGHT of HEARTS, FIVE of DIAMONDS, ACE of CLUBS, SIX of CLUBS, DEUCE of SPADES, DEUCE of CLUBS, JACK of CLUBS, JACK of SPADES, KING of HEARTS, NINE of DIAMONDS, QUEEN of DIAMONDS, KING of CLUBS, EIGHT of CLUBS, TEN of CLUBS, SEVEN of HEARTS, THREE of HEARTS, EIGHT of DIAMONDS, SEVEN of DIAMONDS, THREE of SPADES, TEN of SPADES, FOUR of CLUBS]

[FOUR of CLUBS, SEVEN of DIAMONDS, EIGHT of DIAMONDS, THREE of SPADES, TEN of SPADES]
[EIGHT of CLUBS, TEN of CLUBS, KING of CLUBS, THREE of HEARTS, SEVEN of HEARTS]
[JACK of CLUBS, NINE of DIAMONDS, QUEEN of DIAMONDS, KING of HEARTS, JACK of SPADES]

*****************  ************************   ******************  *************

Friday, August 22, 2014

Packages.

Programs are organized as sets of packages. Each package has its own set of names for types, which helps to prevent name conflicts. A top level type is accessible outside the package that declares it only if the type is declared public.

The naming structure for packages is hierarchical. The members of a package are class and interface types, which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.

A package can be stored in a file system or in a database. Packages that are stored in a file system may have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily.

Package members:
  • The package java has subpackages awt, applet, io, lang, net, and util, but no
compilation units.
  • The package java.awt has a subpackage named image, as well as a number of
compilation units containing declarations of class and interface types.

Host support for packages:
Each host system  deter mains how packages and compilation units are created and stored.
Each host system also determines which compilation units are observable in a particular. The observability of compilation units in turn determines which packages are observable, and which packages are in scope.

Compilation units:
java.lang are always observable.
import allow types from other packages and members of type to be refered using their simple name.

Package declaration.
A package declaratoin appears within a compilation unit to indicate the package to which the compilation unit belongs.

Observability of backage:
A compilation unit containing a declaration of the package is observable. subpackage of the package is observable

One can conclude this from the rule above and from the rules of observable compilation units, as follows. The predefined package java.lang declares the class Object, so the compilation unit for Object is always observable. Hence, the java.lang package is observable, and the java package also. Furthermore, since Object is observable, the array type Object[] implicitly exists. Its superinterface java.io.Serializable also exists, hence the java.io package is observable

package test;
import java.util.Vector;
class Point {
 int x, y;
}
interface Point { // compile-time error #1
 int getR();
 int getTheta();
}
class Vector { Point[] pts; } // compile-time error #2
----------------------- -------------------------- --------------------
class Point {
  int x, y; // coordinates
  PointColor color; // color of this point
  Point next; // next point with this color
  static int nPoints;
}

class PointColor {
  Point first; // first point with this color
  PointColor(int color) { this.color = color; }
  private int color; // color components
}

Apache Cassandra.

Apache Cassandra.
  Cassandra is NoSQL persistence solustion.  NoSQL persistence.

* Distributed data
* Linear scalability
* Tunable consistency level.

Developed by facebook - open sourced in 2008
Influenced by Bigtable(link) and Dynamo white(link).

Netflix, ebay, twitter, reddit.


Structure.
The data stored and replicated across nodes. node - server having cassandra instance. virtual node(one server will contain many cassandra instance). The node are distributed around a token ring. hash of the key will determines where on the token data stored.

replication strategies combined with snitch -  where data to replicated. it improves availability.

Data structure.

A keyspace is the namespace under which column families are defined.The replication strategies and factors defined at keyspace level.

A column family contains a number of rows, indexed by a row key, Each row containing a collection of columns. Each column contains a column name value and time stamp.

The ordering of columns in a row is important. The datatype for column value is specified by the validator.

Column automatically expire by setting time to live. ttl has passed then column will automatically be deleted.

Conversion and Contexts.

CONVERSION AND CONTEXT.

Every expression written in java either has no result or has type that can be deduced.

class Test {
  public static void main(String[] args) {
  // Casting conversion (5.4) of a float literal to
  // type int. Without the cast operator, this would
  // be a compile-time error, because this is a
  // narrowing conversion (5.1.3):
  int i = (int)12.9999f;
  // String conversion (5.4) of i's int value:
  System.out.println("(int)12.5f==" + i);
  // Assignment conversion (5.2) of i's value to type
  // float. This is a widening conversion (5.1.2):
  float f = i;
  // String conversion of f's float value:
  System.out.println("after float widening: " + f);
  // Numeric promotion (5.6) of i's value to type
  // float. This is a binary numeric promotion.
  // After promotion, the operation is float*float:
  System.out.print(f);
  f = f * i;
  // Two string conversions of i and f:
  System.out.println("*" + i + "==" + f);
  // Invocation conversion (5.3) of f's value
  // to type double, needed because the method Math.sin
  // accepts only a double argument:
  double d = Math.sin(f);
  // Two string conversions of f and d:
  System.out.println("Math.sin(" + f + ")==" + d);
  }
}


Output:
(int)12.5f==12
after float widening: 12.0
12.0*12==144.0
Math.sin(144.0)==-0.49102159389846933


Identity conversion:
Conversion from a type to the same type is acceptable.

Widening primitive conversion.
byte to short, int, long, float, double
short to int, long, float, double
char to int, long, float,  double
int to long, float, double
long to float, double
float to double

class Test { 

  public static void main(String[] args) { 
  int big = 1234567890; 
  float approx = big;
  int wide = (int)approx;
  System.out.println("big = " + big + " "+ "approx = " + approx +" "+ "wide = " + wide); 
  System.out.println(big - (int)approx);
 }
}

big = 1234567890 approx = 1.23456794E9 wide = 1234567936
-46

Narrowing primitive conversion:
  short to byte or char
  char to byte or short
  int to byte, short, or char
  long to byte, short, char, or int
  float to byte, short, char, int, or long
  double to byte, short, char, int, long, or float

class Test { 
  public static void main(String[] args) { 
    float fmin = Float.NEGATIVE_INFINITY;
    float fmax = Float.POSITIVE_INFINITY;
    System.out.println("long: " + (long)fmin + ".." + (long)fmax);
    System.out.println("int: " + (int)fmin + ".." + (int)fmax);
    System.out.println("short: " + (short)fmin + ".." + (short)fmax);
    System.out.println("char: " + (int)(char)fmin + ".." + (int)(char)fmax);
    System.out.println("byte: " + (byte)fmin + ".." + (byte)fmax);
 } 
}

Narrow primitive conversion that losses information.
class Test { 

 public static void main(String[] args) { 
 // A narrowing of int to short loses high bits: 
 System.out.println("(short)0x12345678==0x" + Integer.toHexString((short)0x12345678)); 
// An int value too big for byte changes sign and magnitude: 
 System.out.println("(byte)255==" + (byte)255); // A float value too big to fit gives largest int value: 
 System.out.println("(int)1e20f==" + (int)1e20f); // A NaN converted to int yields zero: 
 System.out.println("(int)NaN==" + (int)Float.NaN); 
 // A double value too large for float yields infinity: 
 System.out.println("(float)-1e100==" + (float)-1e100); 
 // A double value too small for float underflows to zero: 
 System.out.println("(float)1e-50==" + (float)1e-50); 
 } 
}


Value set conversion
Assignment conversion.


Assignment context:

primitive assignment conversion.

class Test {
  public static void main(String[] args) { 
    short s = 12; // narrow 12 to short
    float f = s; // widen short to float
    System.out.println("f= " + f); 
    char c = '\u0123';
    long l = c; // widen char to long
    System.out.println("l=0x" + Long.toString(l,16));
    f = 1.23f;
    double d = f; // widen float to double
    System.out.println("d=" + d); 
 }
}

Output
f=12.0
l=0x123
d=1.2300000190734863

Assignment conversion for reference type.

class Point {
  int x, y;
}

class Point3D extends Point {
  int z;
}

interface Colorable {
  void setColor(int color);
}

class ColoredPoint extends Point implements Colorable {
  int color; 
  public void setColor(int color) {
    this.color = color;
  }
}

class Test {
  public static void main(String[] args) {
  // Assignments to variables of class type:
  Point p = new Point();
  p = new Point3D(); // OK because Point3D is a subclass of Point
  //Point3D p3d = p;
  // Error: will require a cast because a Point
  // might not be a Point3D (even though it is,
  // dynamically, in this example.)
  // Assignments to variables of type Object:
  Object o = p; // OK: any object to Object
  int[] a = new int[3];
  Object o2 = a; // OK: an array to Object
  // Assignments to variables of interface type:
  ColoredPoint cp = new ColoredPoint();
  Colorable c = cp;  // OK: ColoredPoint implements Colorable 
  // Assignments to variables of array type: 
  byte[] b = new byte[4]; 
  //a = b; 
  // Error: these are not arrays of the same primitive type 
  Point3D[] p3da = new Point3D[3]; 
  Point[] pa = p3da; // OK: since we can assign a Point3D to a Point 
  //p3da = pa; // Error: (cast needed) since a Point 
  // can't be assigned to a Point3D 
 }
}
----------------------------------------          --------------------------------------          ------------------------------------
class Point {
  int x, y;
}

interface Colorable {
  void setColor(int color);
}

class ColoredPoint extends Point implements Colorable {
  int color;
  public void setColor(int color) {
    this.color = color;
  }
}

class Test {

public static void main(String[] args) { 
  Point p = new Point(); 
  ColoredPoint cp = new ColoredPoint();  // Okay because ColoredPoint is a subclass of Point: 
  p = cp; 
  Colorable c = cp;  // Okay because ColoredPoint implements Colorable:
  // The following cause compile-time errors because 
  // we cannot be sure they will succeed, depending on 
  // the run-time type of p; a run-time check will be 
  // necessary for the needed narrowing conversion and 
  // must be indicated by including a cast: 
  //cp = p; // p might be neither a ColoredPoint 
  // nor a subclass of ColoredPoint 
  //c = p; // p might not implement Colorable 
 } 
}


Assignment conversion for array type.

Casting conversion of reference type.

class Point {
  int x, y;
}

interface Colorable {
  void setColor(int color);
}

class ColoredPoint extends Point implements Colorable {
  int color;
  public void setColor(int color) {
    this.color = color;
  }
}

final class EndPoint extends Point { } 

class Test {
  public static void main(String[] args) { 
  Point p = new Point(); 
  ColoredPoint cp = new ColoredPoint(); 
  Colorable c;  
  // The following may cause errors at run time because 
  // we cannot be sure they will succeed; this possibility 
  // is suggested by the casts: 
  //cp = (ColoredPoint)p; // p might not reference an 
  // object which is a ColoredPoint 
  // or a subclass of ColoredPoint 
  //c = (Colorable)p; // p might not be Colorable 
  // The following are incorrect at compile time because 
  // they can never succeed as explained in the text: 
  //Long l = (Long)p; // compile-time error #1 
  EndPoint e = new EndPoint(); 
  //c = (Colorable)e; // compile-time error #2 
 } 
}

Casting conversion on array type.
class Point {
  int x, y;
  
  Point(int x, int y) {
    this.x = x; this.y = y;
  }
  
  public String toString() {
    return "("+x+","+y+")";
  }
}

interface Colorable {
  void setColor(int color);
}

class ColoredPoint extends Point implements Colorable {
  int color;
  
  ColoredPoint(int x, int y, int color) {
    super(x, y); 
    setColor(color);
  }

  public void setColor(int color) {
    this.color = color;
  }

  public String toString() {
    return super.toString() + "@" + color;
  }
}

class Test { 
  public static void main(String[] args) { 
  Point[] pa = new ColoredPoint[4];
  pa[0] = new ColoredPoint(2, 2, 12);
  pa[1] = new ColoredPoint(4, 5, 24);
  ColoredPoint[] cpa = (ColoredPoint[])pa;
  
  System.out.print("cpa: {");

  for (int i = 0; i < cpa.length; i++)
    System.out.print((i == 0 ? " " : ", ") + cpa[i]);
  System.out.println(" }");
  }
}

Output:
cpa: { (2,2)@12, (4,5)@24, null, null }

Wednesday, August 20, 2014

Types Values Variables

Java is Statically and Strongly typed language.

Statically - Every variable and every expression has a type that is known at compile time.

Strongly - because types
limit the values that a variable can hold or that an expression can produce,
limit the operations supported on those values.

Two types are there in java.
* Primitive types - boolean type, numeric type (byte, short, int, long, char, float and double)
* Reference types - class type, interface types, array type.

Primitive types and values.
  Primitive types are predefined by java and named by its reserved key word.

Integer types and values.
byte (-128 to 127)
short (-32768 to 32767)
int    (-2147483648 to 2147483647)
long (-9223372036854775808 to 9223372036854775807) 0 to 18446744073709551615
char ('\u0000' to '\uffff')  0 to 65535

Operations can be performed on Integer.
=
>
<
>=
<=
~
? : (condition)
==
!=
&&
||
++ (prefix and postfix)
--  (prefix and postfix)
+
-
*
/
&
|
^
%
( <<
  >>    
  >>>  singed and unsigned shifts ).
cast operator to any primitive types.
String concatenation operator.

Floating point types and values.
Float
Double
[ This part ready hard ]







Add caption






class Test {
 public static void main(String[] args) {
 // An example of overflow:
 double d = 1e308;
 System.out.print("overflow produces infinity: ");
 System.out.println(d + "*10==" + d*10);
 // An example of gradual underflow:
 d = 1e-305 * Math.PI;
 System.out.print("gradual underflow: " + d + "\n ");
 for (int i = 0; i < 4; i++)
 System.out.print(" " + (d /= 100000));
 System.out.println();
 // An example of NaN:
 System.out.print("0.0/0.0 is Not-a-Number: ");
 d = 0.0/0.0;
 System.out.println(d);
 // An example of inexact results and rounding:
 System.out.print("inexact results with float:");
 for (int i = 0; i < 100; i++) {
 float z = 1.0f / i;
 if (z * i != 1.0f)
 System.out.print(" " + i);
 }
 System.out.println();
 // Another example of inexact results and rounding:
 System.out.print("inexact results with double:");
 for (int i = 0; i < 100; i++) {
 double z = 1.0 / i;
 if (z * i != 1.0)
 System.out.print(" " + i);
 }
 System.out.println();
 // An example of cast to integer rounding:
 System.out.print("cast to int rounds toward 0: ");
 d = 12345.6;
 System.out.println((int)d + " " + (int)(-d));
 }
}


Boolean type values and operations.

true or false.
==
!=
&
^
|
&&
||
? :
string concatenation +
it controls flow in several statements.
if
while
do
for


Reference Type and values.
Four Reference types.
Class type
Interface type
Type variable
Array type.

Object:
An Object is class instance or Array Instance.
The reference values are just pointer to this object. null reference points no object.
instance creation can take place where string concatenation performed new string object will created.

A new array object is implicitly created when an array initializer expression is evaluated
class or interface is initialized
new instance of a class is created
local variable declaration statement is executed
New objects of the types Boolean, Byte, Short, Character, Integer, Long, Float, and Double may be implicitly created by boxing conversion.

class Point {
 
  int x, y;
 
  Point() { System.out.println("default"); }
  Point(int x, int y) { this.x = x; this.y = y; }  
  static Point origin = new Point(5, 5);                        /* A Point instance is explicitly created at  class initialization time: */
  public String toString() { return "(" + x + "," + y + ")"; } /* A String can be implicitly created by a + operator: */
}

class Test {
  public static void main(String[] args) {
   
    Point p = null;  
   
    System.out.println("p: " + p);                               /* Strings are implicitly created by + operators: */
    try {
      p = (Point)Class.forName("Point").newInstance();         /* A Point object is explicitly created using newInstance: */
    }  
    catch (Exception e) {
      System.out.println(e);
    }  

    System.out.println("p: " + p);                               /* Strings are implicitly created by + operators: */
    Point a[] = { new Point(0,0), new Point(1,1) };              /* An array is implicitly created  by an array constructor: */
    System.out.println("a: { " + a[0] + ", " + a[1] + " }");     /* An array is explicitly created by an array creation expression: */
    System.out.println(Point.origin);
  }  
}

Output:
p: null
default
p: (0,0)
a: { (0,0), (1,1) }
(5,5)


Primitive and reference identity.

class Value {
  int val;
}

class Test {

  public static void main(String[] args) {
    int i1 = 3;
    int i2 = i1;
    i2 = 4;
   
    System.out.print("i1==" + i1);
    System.out.println(" but i2==" + i2);
   
    Value v1 = new Value();
    v1.val = 5;
    Value v2 = v1;                                             //The Reference v1 assigned to v2
    v2.val = 6;
   
    System.out.print("v1.val==" + v1.val);
    System.out.println(" and v2.val==" + v2.val);
  }  
}

Output
i1==3 but i2==4
v1.val==6 and v2.val==6

The class Object.
The class Object is super class to all other classes. so all classes inherit the Objects methods.

clone is used to make a duplicate of an object.

equals defines a notion of object equality, which is based on value, not reference, comparison.

finalize is run just before an object is destroyed.

getClass returns the Class object that represents the class of the object.

hashCode is very useful, together with the method equals, in hashtables such as java.util.Hashmap.

wait, notify, and notifyAll are used in concurrent programming using threads

toString returns a String representation of the object.


Type Variables.

A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies.
A type variable is introduced by the declaration of a type parameter of a generic class,generic interface, generic method, or generic constructor.


class C { 
  public void mCPublic() {}  
  
  protected void mCProtected() {}  
  
  void mCPackage() {}  
  
  private void mCPrivate() {}  
}

interface I { 
  void mI();

class CT extends C implements I { 
  public void mI() {}  

class Test {
  <T extends C & I>     // T is type variable
  void test(T t) {
    t.mI(); // OK 
    t.mCPublic(); // OK 
    t.mCProtected(); // OK 
    t.mCPackage(); // OK 
    //t.mCPrivate(); // Compile-time error 
  }   
}

Here T is same as CT


Parameterized type:

A parameterized type C<T1,...,Tn> is well-formed if all of the following are true:
  C is the name of a generic type.
  The number of type arguments is the same as the number of type parameters in the generic declaration of C.
  When subjected to capture conversion (§5.1.10) resulting in the type C<X1,...,Xn>, each type argument Xi is a subtype of S[F1:=X1,...,Fn:=Xn] for each bound type S in Bi (Fi:=Xi)


Type arguments of parameterized types.

Type arguments may be either reference types or wildcards. Wildcards are useful in situations where only partial knowledge about the type parameter .

Unbounded wildcards.

import java.util.Collection; 
import java.util.ArrayList; 
 
class Test { 
 static void printCollection(Collection<?> c) { 
 // a wildcard collection 
 for (Object o : c) { 
 System.out.println(o); 
 } 
 } 
 
 public static void main(String[] args) { 
 Collection<String> cs = new ArrayList<String>(); 
 cs.add("hello"); 
 cs.add("world"); 
 printCollection(cs); 
 } 
}

Type erasure.

erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|.
erasure of a nested type T.C is |T|.C.
erasure of an array type T[] is |T|[].
erasure of a type variable (§4.4) is the erasure of its leftmost bound.
erasure of every other type is the type itself.

Raw Type:

class Cell<E> { 
  
  E value;
  
  Cell(E v) {
  value = v;
  }   
  
  E get() {
  return value;
  }   
  
  void set(E v) {
  value = v;
  }   
  
  public static void main(String[] args) { 
    Cell x = new Cell<String>("abc"); 
    System.out.println(x.value); // OK, has type Object 
    System.out.println(x.get()); // OK, has type Object 
    //x.set("def");
 } 
}

Raw Type Inheritance.

import java.util.*; 
class NonGeneric { 
 Collection<Number> myNumbers() { return null; } 
 
abstract class RawMembers<T> extends NonGeneric 
 implements Collection<String> { 
 static Collection<NonGeneric> cng = 
 new ArrayList<NonGeneric>(); 
 
 public static void main(String[] args) { 
 RawMembers rw = null; 
 Collection<Number> cn = rw.myNumbers(); 
 // OK 
 Iterator<String> is = rw.iterator(); 
 // Unchecked warning 
 Collection<NonGeneric> cnn = rw.cng; 
 // OK, static member 
 } 
}

Interface and class.

interface Colorable { 
  void setColor(byte r, byte g, byte b); 
}

class Point { int x, y; } 

class ColoredPoint extends Point implements Colorable { 
  byte r, g, b;  
  
  public void setColor(byte rv, byte gv, byte bv) { 
  r = rv; g = gv; b = bv; 
  }   
}

class Test { 
 
  public static void main(String[] args) { 
    Point p = new Point(); 
    ColoredPoint cp = new ColoredPoint(); 
    cp.setColor((byte)1, (byte)2, (byte)3);
    p = cp; 
    System.out.println("Point p : " + p.x); 
    Colorable c = cp; 
    System.out.println("Colorable c :" + c); 
    ColoredPoint c1 = cp; 
    System.out.println("Colorable c :" + c1.r); 
  }   
}


Tuesday, August 19, 2014

Lexical Structure of Java.

Lexical structure :

Unicode :
Programs are written using the Unicode character set.

Comments :

In java single line comment is //
In java multiline command is /*   */

Identifier:
An identifier is an unlimited-length sequence of Java letters and Java digits, the
first of which must be a Java letter

Key words :
  50 character sequences, formed from ASCII letters, are reserved for use as
keywords and cannot be used as identifiers.

abstract
assert
boolean
break
byte
continue
case
catch
char
class
const
default
do
double
else
enum
extends
final
finally
float
for
goto
if
import
implements
instanceof
int
interface
long
native
package
private
protected
public
return
synchronized
switch
short
static
strictfp
super
this
throw
throws
transient
try
void
volatile
while

Literals:
Literal is source code representation of primitive value.

  Integer Literal:
    Integer literal may be expressed in decimal, hexadecimal, binary, octal.
An integer literal is of type long if it is suffixed with an ASCII letter L or l, Otherwise it is type of int.

In a hexadecimal or binary literal, the integer is only denoted by the digits after
the 0x or 0b.

Examples of int literals:
0
2
0372
0xDada_Cafe
1996
0x00_FF__00_FF

Examples of long literals:
0l
0777L
0x100000000L
2_147_483_648L
0xC0B0L

  Floating point literals:
The largest positive finite literal of type float is 3.4028235e38f.
The smallest positive finite non-zero literal of type float is 1.40e-45f.
The largest positive finite literal of type double is 1.7976931348623157e308.
The smallest positive finite non-zero literal of type double is 4.9e-324.

Examples of float literals:
1e1f
2.f
.3f
0f
3.14f
6.022137e+23f

Examples of double literals:
1e1
2.
.3
0.0
3.14
1e-9d 1e137

Boolean literals:
true or false

Character literals can only represent UTF-16 code units, they are limited
to values from \u0000 to \uffff.

'a'
'%'
'\t'
'\\'
'\''
'\u03a9'
'\uFFFF'
'\177'
'™'

String literals;

class Test {
 public static void main(String[] args) {
 String hello = "Hello", lo = "lo";
 System.out.print((hello == "Hello") + " ");
 System.out.print((Other.hello == hello) + " ");
// System.out.print((Other.Other.hello == hello) + " ");
 System.out.print((hello == ("Hel"+"lo")) + " ");
 System.out.print((hello == ("Hel"+lo)) + " ");
 System.out.println(hello == ("Hel"+lo).intern());
 }
}
class Other { static String hello = "Hello"; }

output:
true true true false true

Null literal.
null.

Separators:
Twelve tokens, formed from ASCII characters, are the separators.

(
)
{
}
[
]
;
,
.
...
@
::

Operators:
38 tokens, formed from ASCII characters, are the operators.
=
>
<
!
~
?
:
->
==
>=
<=
!=
&&
||
++
--
+
-
*
/
&
|
^
%
<<
>>
>>>
+=
-=
*=
/=
&=
|=
^=
%=
<<=
>>=
>>>=



Monday, August 18, 2014

INTRODUCTION.

Important point in introduction.
  Java is a general purpose, concurrent, class-based, object oriented language.

What is general purpose language?

General purpose language opposite to Domain specific language.
Domain specific is designed to work with a specific domain. But general purpose can used to any kind of software development.(general purpose language)

Concurrent (wiki) Concurrent and parallel are not same. (stackoverflow)

Class-based (wiki) class-based is opposed to object based.

Object oriented language Object oriented programming is a paradigm that represent the objects that contains the fields and the associated methods.

Java is a production language  not  research language and so.

Java is a strongly statically typed language.Un-tick the date under
Here strong/week and static/dynamic are important to have a look at. (stackoverflow)

This specification clearly distinguishes between the compile-time errors that can and must be detected
at compile time, and those that occur at run time. Compile time normally consists of translating programs into a machine-independent byte code representation.
Run-time activities include loading and linking of the classes needed to execute
a program, optional machine code generation and dynamic optimization of the
program, and actual program execution.

Compile time - finding error and reporting, translating machine independent byte code.
Run time - Linking of classes, Program execution.

Java is relatively high level language. Machine representation are not available through language. It will manages storage stuff.