Monday, April 30, 2012

GIST NOTES 3 - Java Assignments

GIST NOTES 3 - Java Assignments

[DISCLAIMER: This is solely for non-commercial use. I don't claim ownership of this content. This is a crux of all my readings studies and analysis. Some of them are excerpts from famous books on  the subject. Some of them are my contemplations upon experiments with direct hand coded code samples using IDE or notepad.


I've created this mainly to reduce an entire book into few pages of critical content that we should never forget. Even after years, you don't need to read the entire book again to get back its philosophy. I hope these notes will help you to replay the entire book in your mind once again.]


[JDK 7]

-instance variables and objects live on the heap memory
-local variables live on the stack memory

int e=5;//this e doesn't conflict with the e in the next line
float fVal = 10e+3f;
System.out.println(fVal);//prints "10000.0"

e.g. int num = 08; //compiler error, why? (octal numbers start with 0, and symbol 8 is not available in octal base, hence 08 is invalid.

-in java prefixing numbers with 0 carelessly is dangerous (0 prefix should be used only when you intend to use octal form)
-long values are indicated by suffix L or l (mandatory); decimal, octal and hexadecial values can use long format
-float values are indicated by suffix F or f (mandatory)
-double values are indicated by suffix D or d (not mandatory); that is literal numbers are double by default

The following are legal hexadecial numbers:-

int x = 0X0001;
int y = 0x7ffff;
int z = 0xDeadCafe;
int p = 0XFEED; //65261 in decimal

-comma is not allowed in numerical values
-from java 7.0 onwards underscore char is allowed between any two digits; any number of underscores are allowed
-in java numbers cannot be used in places of boolean
-to type unicode value of a character "\u" prefix is used as in [char a = '\u004E';//letter N]
-number literals can be assigned to char variables, when the value is out of range (more than 16bits), an explicit cast to char is required for such assigements

char d = (char) -98; //Ridiculous, but legal

char a = -29; //compile error: possible loss of precision, needs a cast
char f = 70000; //compile error: possible loss of precision, needs a cast

char c = '\"'; //escape code for double quote char
char r = '\n'; //escape code for new line

-string literals are source code representation of a value of a String object
-strings are not primitives but still they have literal form
-arrays are not primitives but still they have literal form
-only strings and arrays are the non-primitive types that have literal form

Variables
----------
-variables are holders or containers containing binary bits
-primitive variables contain the value itself in bits
-object variables contain a pointer(in bits) to the object it is referring, not the object itself
-an object variable explicitly assigned to null contains the value null itself (in bits)

"So variable is just a little box of bits"

Weird int
---------
> integer literals such as 3 are implicitly int type
> so integer literals can be easily assigned to int or long variables

int a = 30;//no problem
long al = 30;//no problem

> what about assigning integer literals to short, char or byte?

short s = 40;//no problem
char c = 40;//no problem
byte b = 40;//no problem

//because compiler automatically casts these literals to appropriate short, char or byte

> int type is 32 bit; byte, char and short are smaller than int
> any integer literal is int type; also, the result of an expression involving anything int-size or smaller is always int
> addition of two bytes gives int (though those bytes are very small and the result is still byte-sized, the end result is always int)
> multiplication of int and short is int
> division of short by byte is an int

byte a = 2;
byte b = 2;
byte c = a + b; //compilation error because the result is an int but it is not literal in this line;
//it is a result from an expression (a + b)

(it makes sense actully; when biggest possible byte added itself gives to a value that is no longer byte-sized)

> the above code needs explicit cast in the third line
> implicit cast(automatic) for primitives happens when smaller value is assigned to bigger container (widening)
> explicit cast for primitives is required when bigger values are assigned to smaller containers (narrowing)

long g = 130L;
byte b = (byte) g; //byte can store only upto 127

//printing b displays -126
//this is because when 130 is narrowed, the bits leftmost to 8th bit are discarded and if the 8th bit(on left side)
//is 1, the number becomes negative

Floating Point Numbers
----------------------
> every floating point literal is implicitly double (e.g. 1.1), not float
> float is 32bit, double is 64bit
> float f = 1.1; //gives compile error; either cast or f/F suffix is required here
> byte a = 128; //gives compile error; 128 is too large to hold

byte a = (byte) 128;//compile
//printing 'a' displays -128. why?
//what happens during narrowing of 128?
//after chopping off the unwanted bits from 32bit(because 128 is int type) representation of 128,
//the last 8 bits that remain are "10000000"
//since leftmost bit is 1, it is negative number
//for negative numbers, 2's complement is used to compute the value of the negative number

2's Complement:-

[Flip all bits (01111111); then add 1 (10000000 back again); we got 128; so final value is -128]

> so when you use explicit cast to narrow down a value, be wary of the unpredicted result you would get

> compound assignment operators lets us skip explicit casts

byte b = 3;
b += 7; //compiles
b = (byte)(b + 7); //doesn't compile without the explicit cast

> assigning one primitive variable to another causes the contents of one variable just copied to another; they don't share the same value; they have separate copies of the same value

Variable Scope
--------------
>static variable scope, instance variable scope, local variable scope(method level) and block variable scope are the four scopes
>method local variables are available as long as the method is on the stack
>sometimes method variables are available on stack but not accessible; this happens when method within a method is being executed, the caller method variables are still on stack but are inaccessible(out of scope) to called method
>variables declared in switch, try-catch, for, do and while loops are not available outside their block

Uninitialized variables
-----------------------
>attempt to use uninitialized variable gives different behavior based on the variable type as well as variable scope
>attempt to use uninitialized method variable gives compile error
>instance variables are given default values if not initialized

Default values:
Object - null
byte/short/int/long - 0
float/double - 0.0
boolean - false
char - '\u0000'


>string variables are object type; so they are initialized with null by default not with empty string ""
>an instance variable will be initialized with null
>an empty array's(initialized array with new operator) elements will be initialized with default values according to their individual type as though they were an instance variable
>even if the array itself is a local variable(not instance variable), its elements get default values as though they were instance variables
>array elements always get initialized regardless of where they are declared
>but a local array variable never gets initialized and you will get compiler error if you attempt to use (it gets null only when it is instance variable)
>local or stack variables sometimes called automatic variables; but there is nothing automatic about them; it is just a name
>attempt to use uninitialized local variable gives compile error
>if the initialization code of the local variable is not visible(is put in a code block like if loop), again any attempt to use that variable in areas where visibility is not there will cause compilation error
>assigning object reference variable to each other does nothing but copy the bit patterns of one variable to another just like the primitive variable values are copied
>so in java assignment means, copy copy copy and copy the contents of the container, that is all
>modifying an object through two copies of its reference affects the same object in the heap (except for String object)
>string objects are immutable and they are given special treatment; whenever you modify a string, java makes up a new string object for result and the original objects involved in the compuatation are left unchanged; this is due to the use of String Constant Literal Pool maintained by JVM; so two copies of reference to a same string object doesn't always operate on the same object forever
>so any operation on a string object creates a new object leaving the originals untouched; copy copy and copy here too; string operations work with copies only

Passing Variables into a Method
-------------------------------
>when you pass an object reference to a method, mind it you are only passing a copy of the reference, not the object itself(like a copy of the address to the original object in the heap)
>although java passes copies of the reference to objects, java is NOT pass-by-reference sematics; it is INDEED pass-by-value (value of the reference to be precise)
>java is pass-by-value for all variables running within a single VM
>pass-by-variable-value or pass-by-copy-of-the-variable
>either a copy of the primitive value or a copy of the reference of the object
>called method cannot change the variables of the caller, but can change the objects referred by those variables
>in case of primitives essentially the same thing, that is the called method can't change the value of the variables of the caller, because it only received a copy of the primitive value
>one can shadow an instance variable by declaring the same again in a method; modifying the shadowing variable doesn't affect the instance variable with the same name (to really get to the instance variable use this operator) - this is for primitives
>while shadowing an object variable, modifying the shadowing variable can still affect the instance variable because it might receive the reference to the instance variable object reference

Array Declaration, Construction and Initialization
--------------------------------------------------
>there is no such thing as primitive array; every array is an object in the heap; either it holds primitives or objects doesn't matter

int key []; //space between key and square bracket is legal

int[] key; //recommended format

String[][] records; //multi dimensional array
String[] records[]; //same multidimensional array and legal

>size of the array should be specified when you create the array object not when you declare it

int[] scores = new int[5]; //creates an array in the heap with 5 int elements initialized to value 0

Thread[] workers = new Thread[5]; //creates an array object in the heap with 5 Thread elements initialized to null
//still no Thread objects created yet

How many objects got created by the previous code line? Just one. The array object. It has 5 reference variables of Thread type. No Thread objects created yet.

>without size, any attempt to create an array object gives compile error

>multi dimensional arrays (not all sizes need to be mentioned)

int[][] scores = new int[5][]; //legal - each element of scores is again array object whose size not mentioned
//each array within this array can be of different size
int[][][] scores = new int[5][][7];//illegal, dimension after empty dimension is not allowed

>initializing an array means putting things into it
>array of primitive type holds primitive values in them
>array of objects doesn't hold objects, but rather a set of references to some objects
>object arrays can be sources of NullPointerException and ArrayIndexOutOfBoundsException (runtime)
>using negative index also causes runtime exception (look, these are not caught by compiler)
>"length" is the only, single, public variable available is array objects(not mean object arrays)

>shorthand syntax to create arrays (without new operator, in this way you can create objects!)

int x = 9;
int[] dots = {1,x,3}; //declaring, constructing and initializing in one line
int[][][] scores = {{1,2,3,4},{1,2,3},{1,2}};//this creates a total of 4 objects of different size in the heap

Anonymous Array Creation(another shortcut to create arrays)
-----------------------------------------------------------

display(new int[] {1,2,3});//display method takes int[]

//no need to specify size for anonymous array; it is even NOT LEGAL to specify

display( new Object[3] {new ArrayList(), new Vector(), new Hashtable()} ); //compilation error here

>array of int can hold byte, char and short values as well
>an object array can hold subtype objects as well
>arrays can hold anything that passes IS-A test

References to arrays themselves
-------------------------------
>you can't assign one type of array reference to another type of array reference (strictly prohibited)

int[] ints = new int[2];
char[] chars = new char[2];
ints = chars; //illegal - though char is compatible with int (what an irony, only children can mingle it seems)

//but for object arrays, even PARENTS can mingle

List[] lists;
ArrayList[] aLists = new ArrayList[5];
lists = aLists; //legal because ArrayList is of List type
Thread[] threads = aLists; //illegal, because ArrayList is not Thread type

>arrays with different dimensions can't be assigned to one another even if they are same type or compatible

>in a multidimensional array of primitives, only the last dimension can accept primitives; others can only accept array objects of that primitive type

Initialization blocks
---------------------
>apart from constructors and methods, initialization blocks also can run codes
>static initialization block - runs when class is loaded
>instance initialization block - runs when an instance is created

class Blocks {

static
{
int a; //static init block
}

{
int b; //instance init block
}

}

>instance initialization blocks run right after the call to super() in the constructor
>one can have many initialization blocks in a class
>the order in which init blocks appear in a class matters; they are run in sequence from top to bottom
>all instance init blocks are run before the control reaches the 2nd line of each contructor of the current class

>The following is the order of execution when we run child class (which attempts to create its own instance)

1. Static init blocks of Parent class
2. Static init blocks of the current(Child) class
3. Instance init blocks of Parent class
4. 2nd line of Parent constructor
5. Instance init blocks of Child class
6. 2nd line of Child constructor

(pretty clear, huh?)

> From the above, it is clear that though we ran Child class, first Parent class is loaded into JVM (hence its static init blocks are run first)

> static init blocks are run once only; but instance init blocks are run everytime an instance is created

> instance init blocks are often used as a place to put code that should be shared by all constructors

> any exception in static init blocks produces java.lang.ExceptionInInitializerError
> any exception in instance init blocks are just treated as regular exceptions and reported as usual in the course of program execution

Wrapper Classes
---------------

>every primitive in java has a wrapper class (Boolean, Byte, Character, Double, Float, Integer, Long, Short)
>wrapper classes are immutable; once an object got created, its value cannot be changed after
>all wrapper classes provide two constructors(except for Character class) of which one takes primitive value, and the other takes string representation of the value

Integer val = new Integer(23);
Integer valval = new Integer("23");

>Character class provides only one constructor which takes char type argument

> Boolean bool = new Boolean("TrUe"); //case doesn't matter in strin rep. for boolean values

> only due to autoboxing/unboxing (from java 5.0 onwards), a boolean object can be directly used for boolean test

valueOf() methods
------------------
>another way to create wrapper objects is to use valueOf() methods
>there are two versions; first version takes string form of primitive value; second version takes string form of primitive value plus base/radix if it is a number type (base: binary, octal, decimal and hexadecial --> 2, 8, 10 and 16)

>byteValue(), shortValue(), doubleValue() and such methods are provided by wrapper classes for conversion purpose; bit truncation is done whenever necessary

>parseBlaBla() and valueOf() methods are similar; both take string form of primitives; both can use bases(radix) for number types; both throw NumberFormatException when the string form is not proper; but parseBlaBla() methods return primitive values while valueOf() methods return wrapper objects of the concerned type

>wrapper classes are marked final

>toString() method is inherited by all classes in java from Object class; this method is not static
>however, wrapper classes support static toString() version in addition to Object class toString(); this static method takes primitive value as argument and returns a string form ofit;
>in addition to that, Long and Integer classes provide a third toString() version which is static;
>this static method takes primitive value as the first argument and radix as the second argument; this is useful to print numbers in different bases
>Integer and Long also have toHexString(10), toOctalString(10), toBinaryString(10) static methods

>Boolean and Character classes do not provide most of the above mentioned methods; Character provides only the simple version of toString() method; Boolean is same as Character but it provides one more method which is a simple valueOf() without radix support

>Double and Float classes do not provide any methods relating to radixes; but essentially they are same in all other respects to Integer/Long/Short/Byte classes

blablaValue() - wrapper to primitive (blabla = int/double/float/short/byte)
parseBlabla(String) - String to primitive
valueOf(String) - String to wrapper

(Happy?)

equals(==) operator and equals() method
----------------------------------------

== operator compares the values or object references are same
equals() method compares the contents of the object

== operator generally considers two objects to be not equal even if they have same content

but, in the world of autoboxing/unboxing, equals(==) operator behaves a little differently (to some extent) when it comes to wrapper objects

Even == operator treats two different wrapper objects to be equal sometimes if their content is same.

when is that sometime? and why?

when?

when the following wrapper objects are created through autoboxing:- 1. Boolean, 2. Byte, 3. Character from \u0000 to \u007f (0 to 127), 4. Short and Integer objects having values between -128 to 127

why?

to save memory :-)

[This is because the autoboxing code is replaced by the compiler with Integer.valueOf() method call. This method caches the above said values for fast performance and to save memory. So, wrapper objects obtained through autoboxing are same objects throughout the application if their value is within the above specified ranges]

{
Integer a = 1;
Integer b = 1;
System.out.println(a == b); //prints true
}

when a primitive and a wrapper is mingled in == operation, the comparison is done in primitive only(wrapper is unboxed).

Autoboxing/Unboxing - is a compiler gimmicks (java language didn't change w.r.to wrapper objects; only the compiler changed)

That is compiler automatically puts code for unboxing and autoboxing wherever required. Saves us some effort.

Autoboxing can obscure NullPointerException occuring due to uninitialized wrapper references. You will be in pinch at runtime though your code might look like using only primitive operations in the code.(duh?)

Overloading
-----------
which overloaded method to use based on the type of the input we pass (especially when primitives/wrappers are involved)?

[we are assuming that all overloaded methods only differ by the type of one input argument in the same position in the argument list; even return type is same across all overloaded methods; the situation turns grave when we have to decide which overloaded method we have to use based on that one input arg's type]

>passing byte and short automatically chooses overloaded method which takes int if there are not methods that take byte or short
>as long as the passed input is accommodatable the overloaded method with int arg is chosen over the method with long arg(widening in play)
>smallest possible YET accommodating argument is given preference over other accommodating ones (int over long and float over double)

>Firstly, when a choice is given between "widening" and "autoboxing" for choosing an overloaded method, "widening" gets the first preference. Lazy compiler doesn't want to put all those autoboxing code; so it simply uses widening; e.g value "5" to be passed as "Integer" object or "long" value - it chooses "long" option

>this preference comes from the decision of Java 5's designers to let the preexisting code to function the way it used to (hence widening comes first than autoboxing)

>Secondly, given a choice between "widening" and "var-args", widening is given first preference to choose appropriate overloaded method; e.g. (short, short) will be passed as (int, int) rather than (short...)

[again old style is preferred first]

>Thirdly, between Autoboxing and Var-args, Autoboxing wins

>"Widening" is the KING; "Var-args" is the LOSER;

>"Var-args" is used as a last resort; when nothing else works, we come to var-args

>It is legal to widen the primitives; so is for object references if polymorphic relationship is there, widening works well; e.g. ArrayList passed as List;
>But wrapper classes donot have any polymorphic relationships with one another; they are all peers; For example Short object cannot be passed as Integer; same goes for all wrapper classes

>Compiler will not do two adjustments; e.g. first widening, then boxing is not permissible (byte value 5 to be passed as Long object is not allowed)

>first boxing and then widening is allowed; like 5 to Byte(5) to Object; but not 5 to Byte(5) to Long(5); (remember we said object widening needs polymorphic relationship)

[Combining widening or boxing with vararg]

>widen + vararg is possible (first widens, then uses vararg to choose the correct method)
>boxing + vararg is possible (first boxes, then uses vararg to choose the correct method)

Garbage Collection
------------------
>Java garbage collector provides automatic solution to memory management; no memory management logic is necessary in your application code
>the downside of this automatic solution is you can't control when it runs and when doesn't
>Java memory areas: stack, heap, constant pools, method areas
>Heap is where java objects live
>Heap is the only place where garbage collection happens
>Heap is only one; only one heap

>when no live threads can reach/access an object, it becomes eligible for garbage collection
>where there are no references to an object it is eligible for garbage collection
>by setting all existing references to null we can force the object to become orphan and so it is eligible for garbage collection
>method local objects become eligible for garbage collection once the method is over, if no references were returned back to the calling method and saved there

Islands of Isolation: It is nothing but an island of object cutoff from the rest of the JVM world. The objects in that island may still be holding references to each other, but the island as a whole is not accessible to any live threads. Hence the whole island becomes eligible for garbage collection

>One can request for garbage collection using System.gc() call; but no guarantees that JVM will actually run gc
>In Java 6 and later, using System.gc() is almost useless because gc has advanced so much that JVM itself is capable of taking care of gc without your intervention
>Even after running gc, there is no guarantee that all inaccessible object would be garbage collected
>gc related routines/methods are part of Runtime class. Runtime is a singleton class for each main program
>Runtime object provides mechanism to directly communicate with the VM
>Runtime.getRuntime() returns the singleton object
>Sytem.gc() uses Runtime object internally
>Guaranteed:: GC will be run for sure before it throws OutOfMemoryError
>finalize() method is inherited from Object class by all objects in JVM; GC will call finalize() before it deletes an object; one can use this method to cleanup or free resources before it gets deleted
>however, since GC itself is not guaranteed to be run at the time you expect, the chance of the finalize() method running is also not guaranteed
>GC calls the finalize() method on an object only once; in case you saved this object from getting deleted using finalize() method, it won't work second time, because GC will not call finalize() again on the same object
>it is recommended not to override finalize() method because that method ever running is unpredictable
>You can't know GC algorithm for sure

>outer class can access the private members of the static inner class (verified) [non-static inner class private members also are accessible]


Reference: Kathy Sierra's SCJP Book

Wednesday, April 25, 2012

GIST NOTES 2 - Java Object Orientation



GIST NOTES 2 - Java Object Orientation

[DISCLAIMER: This is solely for non-commercial use. I don't claim ownership of this content. This is a crux of all my readings studies and analysis. Some of them are excerpts from famous books on  the subject. Some of them are my contemplations upon experiments with direct hand coded code samples using IDE or notepad.


I've created this mainly to reduce an entire book into few pages of critical content that we should never forget. Even after years, you don't need to read the entire book again to get back its philosophy. I hope these notes will help you to replay the entire book in your mind once again.]


[JDK 7]

-Getters and Setters are called Accessors and Mutators
-Two most common reasons to use inheritance are: To promote code reuse; To use polymorphism
-any object which can pass more than one IS-A test is considered polymorphic
-All java class objects except for Object objects, pass at least two IS-A test and hence they are all polymorphic
-a reference variables type determines the methods that can be invoked on the object referenced
-java doesn't support multiple inheritance

Deadly Diamond of Death: Multiple inheritance class diagram in the shape of diamond depicting inheritance issue of not being able to decide whether the member is inherited from this class or that. Four classes having inheritance relationship where the class diagram looks like a diamond

-usually you can call only methods available in the type the reference variable is declared as. For example, if the reference variable is declared as Runnable then you can call methods from Runnable interface. You can't call methods from other implemented types say if the class also extends UnicastRemoteObject, you still can't invoke methods from UnicastRemoteObject.

-One exception to this strict decalred type the compiler enforces is "methods from Object class" can be called on any object regardless of its declared type(true, checked in the code!)

Method overriding
-----------------
-subclasses are not allowed to narrow down the visibility or access level of the method being overridden (leads to compilation error)

>> Contract of the super class: Overriding rules

1. argument list of the overridden method should match
2. return type should be same as the one it is declared in the super class or a subtype of it
3. access level should not be restricted
4. access level can be broadened though
5. can throw a new UNCHECKED exception
6. can NOT throw a new CHECKED exception or broaden(more generic) the already thrown checked exception, but can throw a subtype of parent's exception
7. overriding method can narrow(more specific exception) the parent exception
8. final methods cannot be overridden
9. static methods cannot be overriden(just like private methods)
10. a method that was not inherited, obviously CANNOT be overridden(private methods, duh!)
11. using super keyword one can access the parent version of the overridden method in the subclass
12. overriding method can choose not to throw any exception at all(eliminates the parent's exception)
13. calling the overridden method using supertype reference will only call the parent's version and will expect parent's exception be handled (unhandling that exception causes compilation error)

14. change in the return type without changes to argument list is neither 'overriding' nor 'overloading'. overloading requires different argument list than the original method. Such attempts causes compilation error because return type cannot be resolved even at runtime. (you think you are so clever, eh?)

Method overloading
------------------
-overloaded methods MUST change the argument list
-can change return type
-can change access modifier
-can declare newer and broader(more generic) checked exceptions
-overloading can happen in the same class or subclass
-overloading against the inherited method in the subclass still qualifies as proper OVERLOADING but across different classes(actually the inherited method sits in the subclass too)

-if method overloading is based on compatible types(subtype, say first method takes Animal and its overloaded version takes Horse a related type to Animal) when you pass a subtype object through supertype reference, then the method which will be called is the method that takes super type as argument, not the method that takes subtype, though the actual object passed at runtime is of subtype; it is decided during compile time

#That is the choice of which overloaded method to infer in a context is decided at compile time itself.

-polymorphism does not matter when a method is overloaded; it skips the polymorphic special treatment and all
-but polymorphism STILL matters when it comes to method overriding
-compiler is dumb; it doesn't have the patience to check for polymorphic relationships; so don't go invoking subtype methods on a subtype object that is held in supertype reference variable; compiler will recoil at you violently (it would say, "what are you?! you think I've got all day to do your biddings? the nerve!")

Compile time resolution - overloaded method calls
Run time resolution - overridden method calls

downcast(going specific) - casting down the inheritance tree (casting a supertype to a subtype), e.g. (Dog)Animal

-compiler is also dumb enough to not recognize wrong downcasts that are evident EVEN at compile time

e.g. Animal a = new Animal();
Dog d = (Dog) a; //compiler allows this when Dog is a subtype of Animal, though it is a compile time programming error

String name = (String) a; //compilation will fail here because EVEN compiler knows that String is not related to Animal type


upcast(going generic) - doesn't need explicit casting; you can directly assign the subtype(object) to a supertype(reference); super type can be an interface.

upcast   <--> broaden <--> generic
downcast <--> narrow  <--> specific

-a subclass can implement an interface which was already implemented by superclass; in this case, subclass can just declare that it implements the interface but can skip actual implementation of its methods because it was already implemented by the parent

Interface Implementation
------------------------
-a class implementing the interface can narrow(use subtypes) the return-type and declared exception of the methods in the interface
-it can also choose to eliminate the declared exception
-since interfaces can extend more than one interfaces, it is possible for a child interface to directly re-extend a distant ancester who is already in the inheritance tree

e.g.

interface GrandParent{}

interface Parent extends GrandParent{}

interface Child extends Parent{}

interface GrandChild extends Child, Parent, GrandParent{}


Return Type Declaration
-----------------------
-the declared return type of the overriding method should be same or subtype of the declared return type of the method which is being overridden
-subtype for return type is allowed from java 5.0. This is called co-variant returns. Co-variant return type gives compilation error in 1.4 or before

Return Type Values
------------------
-null can be returned for any return type(but not for primitive types)
-char can be returned for int
-int cannot be returned for char [Gives: possible loss of precision error]
-returning any value is not allowed for void return type
-dotted numbers cannot be assigned to float variable
-float can NOT be returned for int return type
-int CAN be returned for float return type
-dotted numbers cannot be assigned to int variable
-all dotted numbers are treated as double
-float values should have 'f' suffixed
-float value cannot be assigned to int variable
-int value can be assigned to a float variable
-dotted number(that is double value) cannot be returned for float return type
-int can be returned for double
-float can be returned for double
-char can be returned for double
-"return void" is illegal syntax
-subclass object can be returned in the place of super return type
-any object that passes IS-A test can be returned safely

Constructors
------------
-you can't make a new object without invoking the constructor
-in addition to that, you can't make a new object without invoking constructors of each of the superclasses in the inheritance hierarchy
-when you say 'new', constructors and initialization blocks are run
-every class(including abstract classes) has a constructor even if it is not explicitly coded
-constructors have no return type and have same name as the class
-if a class doesn't define any constructors, then no-arg constructor will be automatically enabled by the compiler
-if however a class defines at least one constructor with one or more arguments, the no-arg constructor will not be enabled by the compiler and any attempt to instantiate with no-arg constructor results in compilation error
-constructors can be overloaded
-constructors are used to initialize the object and states of its member variables

Constructor Chaining: when you call new operator on a class type, the following happens:-

1. Constructor of the current class is called
2. Then constructor of the immediate superclass is called (automatically using super() if you haven't explicitly called a superclass constructor inside your constructor.
3. Then, next superclass constructor
4. Then next superclass constructor and so on until it reaches Object which is the topmost in java system
5. Instance variables of Object class are initialized with the declared values(explicitly assigned values)
6. Object constructor completes
7. Members of next class below Object get initialized
8. Constructor of the class below Object class completes
9. One step below, next class member variables get initialized with explicit values, and its constructor completes
10. and so on till it reaches the bottom most class in the inheritance hierarchy.
11. Bottom most class member variables are initialized (with explicit values if any)
12. Bottom most class constructor completes

This recursive work is called "constructor chaining".

First: super class constructor runs
Second: current class members get their explicitly assigned values
Third: current class constructor finishes

Rules for constructors
----------------------

1.Constructors can use any access modifiers including private
2.It is legal to have a method with the same name as the class though it doesn't qualify as constructor for it has a return type!
3.Compiler generated default constructor is always no-arg constructor(only when no constructors are explicitly declared)
4.Every constructor as a first statement in it, it should call one of the super class constructor. If not, compiler inserts one(no-arg super constructor only) automatically
5.when the compiler is attempting to insert a call to the super class' default constructor, and if it is not availble, bang!, results in compilation error
6.you can't call intance methods or access instance variables until after the super constructor runs
7.during this() and super() calls, only static methods and static variables can be accessed
8.abstract classes have constructors, but called only when a concrete subclass is instantiated
9.interfaces don't have constructors
10.calling a constructor without new operator (like a method call) is allowed only inside another constructor and nowhere else, mind it
11. class Horse {
void Horse() {}
} //for this class, compiler will insert a default constructor. why? (take a closer look at the code)

12. Props of default constructor: >it has same access modifier as the class, >has no arguments, >includes a call to no-arg super constructor [super();]

13. class Parent {
Parent(String name){}
}

    class Child extends Parent {
//compilation fails here due to the unavailability of default no-arg constructor in the super class
}

14. CONSTRUCTORS ARE NEVER INHERITED; so they can't be overridden, but can be overloaded

15.a constructor instead of calling super constructor, it can call its own constructors this(); but eventully the constructor chaining reaches top level class through the other constructor

16. the first line in a constructor must be either super() or this() or any of their overloaded counterparts [this has to be done either by you or by the compiler; so no exceptions to this rule]

17. using both super() as well as this() in the same constructor gives compile error. because not both of them can be the first line in the constructor ;-)

18. when you explicitly put super() or this() calls, compiler will not insert the default calls to either super() or this(). This allows to write the following erraneous program which some compilers will NOT CATCH (latest compilers DO catch)

class A {

A()
{
this("Hi");
}

A(String greeting)
{
this();
}

}

//7.0 compiler error: recursive constructor invocation
//if compiler didn't catch then it leads to StackOverflowError at runtime

19. overloaded constructors give code-reuse and flexibility in object instantiation


Static Variables and Methods
----------------------------
static method - method that doesn't depend on object state(instance variables) and hence common to the whole class
static - is a scope outside of any object; a perfect place to monitor all objects of a particular class
static members - belong to the class not to any object
static variables - get same default values as the instance variables get

-referencing instance variables or methods from a static context(e.g main method) throws compile error
-static methods cannot be overridden, but can be redefined (what is the difference?); because in proper overriding, subclass can access superclass version of the method using super.method(); but when you redefine static method, the usage of super.method() is not possible because super and this are non-static; that's why this is called "method redefining" instead of calling "overriding"

Redefined static method ===>

1.parent version of the static method is used when parent class name is used for access (Parent.staticMethod())
2.child version is used when child class name is used for access(Child.staticMethod())
3.if an object reference is used to access the static method, then the version available in the declared variable type class is called, though the variable can be holding subclass object. so, reference variable type decides which version of the redefined static method will be called.

e.g. Parent p = new Child();
p.staticMethod(); //calls the static method in Parent class; for overridden non-static methods, Child class method would be called.

Cohesion and Coupling(are subjective concepts)
----------------------------------------------
-high cohesion and loose coupling are good OO designs
-the object for this is easy creation, maintenance and enhancement

coupling: knowledge of the two classes about each other; has to do with how classes interact with each other
loose coupling: two classes know only each others exposed public interfaces
tight coupling: result of poor encapsulation
cohesion: is about how a single class is designed; it is a degree to which a class has a single well focused purpose
high cohesion: class is highly focused on a single purpose; easier to maintain(extensible); more reusable;
low cohesion: has unrelated functionalities in the same class; inflexible to extend; less reusability;


-polymorphism applies to overriding, not to overloading
-object type(not reference variable type) determines which overridden method is used at runtime
-reference type determines which overloaded method will be used at compile time
-reference type determines which redefined static method(no overriding concept for static methods) will be used at compile time

- I think I have a low cohesion!

-a final method cannot be overridden; but if it is a private method, the subclass has no visibility to it; so subclass can put the exact same final method in its own class with different code body(it looks like overriding a final method, but it is not)

-a super class instance variable can be redefined in the subclass; but polymorphism doesn't apply for instance variables; hence, reference type decides which version of the variable will be used at compile time;

-if two overloaded methods one taking parent type argument and other taking child type argument, then always the method taking parent type will be called; the other method will never be used even one tries to call the method with child type object because child type object first is of parent type and it supersedes

-also overloaded var-arg methods are chosen last compared to normal argumented methods; autoboxing can come in to rescue to pick a method in overloaded context



Reference - Kathy Sierra SCJP book

Saturday, April 21, 2012

Slytherin welcome message

Courtesy: Pottermore

Congratulations! I’m Prefect Gemma Farley, and I’m delighted to welcome you to SLYTHERIN HOUSE. Our emblem is the serpent, the wisest of creatures; our house colours are emerald green and silver, and our common room lies behind a concealed entrance down in the dungeons. As you’ll see, its windows look out into the depths of the Hogwarts lake. We often see the giant squid swooshing by – and sometimes more interesting creatures. We like to feel that our hangout has the aura of a mysterious, underwater shipwreck.

Now, there are a few things you should know about Slytherin – and a few you should forget.

Firstly, let’s dispel a few myths. You might have heard rumours about Slytherin house – that we’re all into the Dark Arts, and will only talk to you if your great-grandfather was a famous wizard, and rubbish like that. Well, you don’t want to believe everything you hear from competing houses. I’m not denying that we’ve produced our share of Dark wizards, but so have the other three houses – they just don’t like admitting it. And yes, we have traditionally tended to take students who come from long lines of witches and wizards, but nowadays you’ll find plenty of people in Slytherin house who have at least one Muggle parent.

Here’s a little-known fact that the other three houses don’t bring up much: Merlin was a Slytherin. Yes, Merlin himself, the most famous wizard in history! He learned all he knew in this very house! Do you want to follow in the footsteps of Merlin? Or would you rather sit at the old desk of that illustrious ex-Hufflepuff, Eglantine Puffett, inventor of the Self-Soaping Dishcloth?

I didn’t think so.

But that’s enough about what we’re not. Let’s talk about what we are, which is the coolest and edgiest house in this school. We play to win, because we care about the honour and traditions of Slytherin.

We also get respect from our fellow students. Yes, some of that respect might be tinged with fear, because of our Dark reputation, but you know what? It can be fun, having a reputation for walking on the wild side. Chuck out a few hints that you’ve got access to a whole library of curses, and see whether anyone feels like nicking your pencil case.

But we’re not bad people. We’re like our emblem, the snake: sleek, powerful, and frequently misunderstood.

For instance, we Slytherins look after our own – which is more than you can say for Ravenclaw. Apart from being the biggest bunch of swots you ever met, Ravenclaws are famous for clambering over each other to get good marks, whereas we Slytherins are brothers. The corridors of Hogwarts can throw up surprises for the unwary, and you’ll be glad you’ve got the Serpents on your side as you move around the school. As far as we’re concerned, once you’ve become a snake, you’re one of ours – one of the elite.

Because you know what Salazar Slytherin looked for in his chosen students? The seeds of greatness. You’ve been chosen by this house because you’ve got the potential to be great, in the true sense of the word. All right, you might see a couple of people hanging around the common room whom you might not think are destined for anything special. Well, keep that to yourself. If the Sorting Hat put them in here, there’s something great about them, and don’t you forget it.

And talking of people who aren’t destined for greatness, I haven’t mentioned the Gryffindors. Now, a lot of people say that Slytherins and Gryffindors represent two sides of the same coin. Personally, I think Gryffindors are nothing more than wannabe Slytherins. Mind you, some people say that Salazar Slytherin and Godric Gryffindor prized the same kinds of students, so perhaps we are more similar than we like to think. But that doesn’t mean that we cosy up with Gryffindors. They like beating us only slightly less than we like beating them.

A few more things you might need to know: our house ghost is the Bloody Baron. If you get on the right side of him he’ll sometimes agree to frighten people for you. Just don’t ask him how he got bloodstained; he doesn’t like it.

The password to the common room changes every fortnight. Keep an eye on the noticeboard. Never bring anyone from another house into our common room or tell them our password. No outsider has entered it for more than seven centuries.

Well, I think that’s all for now. I’m sure you’ll like our dormitories. We sleep in ancient four-posters with green silk hangings, and bedspreads embroidered with silver thread. Medieval tapestries depicting the adventures of famous Slytherins cover the walls, and silver lanterns hang from the ceilings. You’ll sleep well; it’s very soothing, listening to the lake water lapping against the windows at night.

http://www.pottermore.com/en/book1/chapter7/moment3

Friday, April 20, 2012

GIST NOTES 1 - Basic Java


GIST NOTES 1 - Basic Java


[DISCLAIMER: This is solely for non-commercial use. I don't claim ownership of this content. This is a crux of all my readings studies and analysis. Some of them are excerpts from famous books on  the subject. Some of them are my contemplations upon experiments with direct hand coded code samples using IDE or notepad.


I've created this mainly to reduce an entire book into few pages of critical content that we should never forget. Even after years, you don't need to read the entire book again to get back its philosophy. I hope these notes will help you to replay the entire book in your mind once again.]



[JDK 7]

$ and _ are legal characters in an identifier.

$, $$, _ and __ are legal identifiers or variable names.

KEYWORDS OF JAVA
================
volatile - instructs threads not to keep a copy of the variable in stack
transient - instructs java not to persist/serialize the particular variable

assert was added in 1.4 - ?

enum was added in 1.5 - ?

const - ?

goto - ?

native - ?

strictfp - ?

Java Naming Convention
======================
Class names are nouns in camelCase format.
Interface names are adjectives in camelCase format.
method(verb+noun) and variable(noun) names should start in lowercase with camelCase format.

JavaBeans Standards
===================
Getter and Setter methods should reflect instance variable name. Both the methods should match in datatype.

For variable 'size' [public int getSize() and public void setSize(int s)] are the correct getter/setter methods.

All getter/setter methods should be declared 'public'.

For boolean values, 'is' or 'get' prefix should be used in the methods (e.g isStopped)

Setter method return type should be void.

Getter method input param should be nothing.

For event listeners register/unregister method names should be add_____Listener(), remove_____Listener() where blank represents a noun like 'Action'.

Source File Declaration Rules
=============================
Only one public class is allowed per source code file.
Public class name should match the file name.

Package statement(optional) should come first in the source file and nowhere else.

Import statements should come second in the source file and nowhere else is allowed.

Only one package statement is allowed per source file even if it contains multiple classes.

A file can have more than one nonpublic classes.

private and protected modifiers are not allowed for classes(gives compilation error). 
Only 'public' and default access modifiers are allowed for classes.

So, when we say nonpublic classes are allowed in a single file, we really mean that they are package level accessible (default access) classes. There can't be 'private' or 'protected' class mind it.

There can be classes called '$' and '_' since these two characters can come first in an identifier.

Files with no public classes can have a name that does not match with any of the class names in that file - while compiling you always compile with file name and not the nonpublic class names. You can't javac a nonpublic class in a file whose name doesn't match with the file name.

Nonpublic classes also can be executed using 'java' command from command line.

javac is always done on source file name not the class names.

Class Access(Class Visibility)
============
A class can access another class means,
-it can create an instance of that class
-extend that class
-or access methods and variables in that class depending upon the access control declared in that class

Default Access - A class with default access is not visible to other classes in other packages. Any attempt to use this class in other packages will result in compilation error.

Access Modifiers: public, protected, private,
Non-access Modifiers: strictfp, final, abstract

Non-access modifiers can be used along side (or added to) Access modifiers. They can work together. e.g. public final class A{}

Combination "abstract final" is not allowed. Compilation error.

Both [abstract public class A{}] and [public abstract class A{}] are valid declarations. Access modifier order doesn't matter here.

final - cannot be subclassed

abstract - must be subclassed

'abstract' can be used only for classes and methods. (not allowed for variables)
'final' can be used for classes, methods and variables(even for method arguments).
'strictfp' is only for class or method and never for a variable.

strictfp - means the method/class conforms to IEEE 754 floating point standards. Without this keyword, the floating points used in the code will behave in platform-dependent way. 'strictfp' could literally mean "strict floating point".

abstract and strictfp combination is not allowed(compilation error). So, strictfp is allowed only for classes, interfaces and non-abstract methods.

strictfp and final can be combined.

IEEE 754 specifies arithmetic formats(NaN, etc), interchange formats, rounding algorithms, operations, exception handling(division by zero, overflow, etc) for floating point arithmetic.

Combination "abstract private" is not allowed. "protected abstract" and " abstract" are allowed. [for methods]

INTERFACES
==========
private/protected interface - not allowed(compilation error). interface is allowed.
public interface cannot reside in the same file with a public class.
private/protected methods inside an interface are not allowed.(illegal)

When an interface and its methods are left with default access modifiers, the compiler automatically puts "public abstract" modifier prefix to methods, but leaves the interface as it is (in default access mode).[found through decompilation]

All interface methods are implicitly public abstract. All variables defined in the interface are 'public static final' that is only constants are allowed. 'public static final' is automatically added to constants during compilation.

Interface methods cannot be declared static(compilation error). Since they are abstract methods, they cannot be declared final, strictfp or native.

[public abstract interface A{}] is legal, since interface is inherently abstract, the use of 'abstract' modifier here is redundant. Even compiler does not add 'abstract' to interfaces.

Interface can have either public or default access.

final, static, private and protected are not allowed for interface methods.

Attempt to modify an interface constant in implementing class will give compilation error.

Member(Methods and Instance variables) Access
==================================
Two access issues:-
1. a class accessing member of another class
2. a subclass inheriting a member of its superclass

First comes, class level visibility. Then only comes member visibility.

Access across different packages is possible among superclass-subclasses. However default access allows only classes residing in the same package to access.

Private members are accessible only within the same class. They are not even available for subclasses to inherit. Having the same private member as the superclass private member, inside the subclass does not qualify as "overriding" or "inheriting". Rules of overriding do not apply to such members/methods. They just happen to have the same signature as a super class private member has.

Usually class instance variables are declared private and are given setter/getter methods for everyone(java beans) to properly modify them. This is called data protection (or encapsulation).

Private method CANNOT be overridden.

default access - available to all classes within the same package and NOT for other packages EVEN IF they are SUBCLASSES.
protected - available to all subclasses regardless of the package they reside in, and also available for other classes in the same package

default access --> package only (not for kids in other packages)
protected --> package + kids

PROTECTED: subclass-outside-the-package inherits the protected member from the super class. But it can never access the protected member using dot operator on superclass object. Still the subclass-outside-the-package is NOT ELIGIBLE to access protected members of the superclass directly. It CAN access such protected members through inheritance only.

[Looks like package level access is the king.] Within the package all class can access default members as well as protected members. A subclass-outside-the-package can inherit only protected members not default members. Both the protected as well as default members are not visible to the subclass-outside-the-package. Note that 'inheriting' is different from 'having visibility'.

PROTECTED = DEFAULT ACCESS + EXCEPTION FOR INHERITANCE

DEFAULT ACCESS == PACKAGE LEVEL

The inherited protected member in the subclass-outside-the-package will not be visible to the neighbors that sit in the same package as the subclass-outside-the-package.[one might argue the protected members are package visible and why not the inherited protected member in the subclass-outside-the-package is not visible in its package?!!]. Because once the subclass-outside-the-package inherits the protected member, it becomes private and not visible to anyone else except for further subclasses of the subclass-outside-the-package.

Access modifiers cannot be applied to local variables(except for final) - gives compilation error.

'protected' is biased towards package level access.

Modifiers for Methods
================
final method -> method cannot be overridden in subclasses

final method argument -> method arguments in the method signature that are declared as final cannot be modified inside the method. "modified" means reassigning new values to variables. That is the final argument should keep the same value that the parameter had when it was passed into the method.

abstract method -> method with no body; forcing subclasses to implement the method; a class with at least one abstract method should explicitly be declared as abstract class; however it is possible to have an abstract class with no abstract methods.

Combinations 'abstract final' and 'abstract private' are not allowed for methods. But 'private final' is allowed.

private methods are not visible to subclasses; so marking it as abstract calls for the impossible.

'abstract static' is illegal; 

synchronized -> only for methods; not variables, not classes. it indicates that the method can be accessed by one thread only, at a time. synchronized can be paired with all four access control levels.

native -> only for methods; not variables,  not classes. Indicates that the method is implemented in platform-dependent code(often in C). methods body is just a semicolon just like abstract methods(body omitted).

strictfp -> only for methods and classes; not variables. forces floating point operations to be uniform in all platforms. if the underlying platform is capable of supporting higher precision, strictfp method WON'T BE ABLE to take advantage of it.

Methods with variable argument lists(var-args)
===============================
From java 5.0

Little convention:

arguments - the things you specify between parentheses when you are invoking a method
parameters - the things in the method signature that indicate what the method must receive when it's invoked.

var-arg parameter should be the last parameter in the signature; only one var-arg param is allowed per method.

e.g. void doStuff(char c, int... x){} --> ellipsis is used for var-arg param; 0 to many int's can be passed.

e.g. void doStuff2(Object... in){} --> 0 to many Object's can be passed

FOLLOWING ARE ILLEGAL:

void display(int x...){}
void display(int... x, char... c){}
void display(String... s, Object obj){}

CONSTRUCTORS
==============
-do not have return type
-every class has a constructor, if not mentioned, compiler will create one.
-constructors are similar to methods regarding access modifiers
-they have same name as the class name
-they cannot be marked as static because they are involved in object creation after all
-constructors cannot be overridden and hence they cannot be marked as final or abstract
-they can take var-args
-they cannot have omitted body that is ending with semicolon is illegal
-there can be a method(with return type) with same name as the class that might look like a constructor; do not be fooled!

Variable Declaration
==============
primitive variables -> (8 types) char, boolean, byte, short, int, long, double or float.
reference variables -> used to refer to any object of the declared type or a compatible type(subtype)

class variables -> static member variables

e.g. int x, y, z; //is legal

Ranges:
-------
integer type -> the sequence from small to big: byte, short, int, long
float type -> the sequence from small to big: float, double
number type -> both integer and floating-point types are all signed

-All numbers are made up of 8-bit bytes.
-left most bit represents the sign; 1 means negative and 0 means positive
-the rest of the bits represent the value using two's complement notation

byte -> 8 bits(2^7 unsigned; from -128 to 0 to +127 = 256 values)
short -> 16 bits(2^15 unsigned; from -32768 to 0 to +32767 = 65536 values)

The positive range is one less than the negative range because number 0 is stored as positive binary number. 

Positive Range = +2^(n-1) - 1
Negative Range = -2^(n-1)

byte - 8 bits(1 byte)
short - 16 bits(2 bytes)
int - 32 bits(4 bytes)
long - 64 bits(8 bytes)
float - 32 bits(4 bytes - range not applicable)
double - 64 bits(8 bytes - range not applicable)

int = float (in bit size only)

long = double

bit depth of a boolean ---> "That's virtual machine dependent"

char --> a single 16 bit Unicode character; though ASCII(ISO Latin-1) needs only 8 bits; 16 bits are useful for languages other than English; these Unicode characters are unsigned 16 bit integers actually; char is really an integer type; so char can be assigned to any integer type larger than short; both char and short use 16 bits;

[short ~= char] ----> they are almost equal because, short loses one bit for sign and hence char can still have bigger positive numbers than short.

Instance Variables
=============
-defined outside methods but inside classes
-they are initialized only when the class is instantiated
-[field=instance variable=property=attribute] generally
-they can use four access levels
-CAN be marked final, transient, volatile
-CANNOT BE marked abstract, synchronized, strictfp, native, static(static members become class variables NOT instance variables?!?)

Modifiers allowed
-----------------
Local variables - final
Nonlocal variables - final, public, protected, private, static, transient, volatile
Methods - final, public, protected, private, static; abstract, synchronized, strictfp, native

Local/Automatic/Stack/Method Variables
--------------------------------------
-declared inside method; initialized inside method; destroyed inside method
-they are always on the stack not heap
-since they live within the method scope, when they are passed to other methods, only a value is passed; though that value can be stored in an instance variable later, the variable itself dies within the method.
-but all objects live in heap though they can be referred by a local variable; there is no such thing as 'local object' or 'stack object'; it is really a locally declared reference variable, that is all.
-local variables can't use public/private/protected, transient, volatile, abstract or static; but can be marked as final
-local variable must be initialized before attempting to use it; otherwise results in compilation error; but instance variables need not be initialized because they get default values automatically.
-it is possible to declare a local variable with the same name as an instance variable; it is called "shadowing"; the name collision is resolved using 'this' keyword

Array Declarations
------------------
-store multiple variables of same type or compatible type(subclasses)
-both primitive and object arrays are object in themselves and they are stored in the heap
-there is no such thing as primitive array but you can have array of primitives

e.g. int[] keys; 
int keys[]; //both are valid array declarations

-using square bracket immediately after type instead of after identifier is recommended; it easily says 'array of that type'

e.g. String[][][] names;
String[] data []; //both are valid multi-dimensional arrays or 'array of arrays'

-It is ILLEGAL to specify size of the array in the declaration

e.g. int[5] scores; //compilation error

-JVM doesn't allocate space until you actually instantiate the array object; that is when the size matters.

Final variables
---------------
-need to be explicitly initialized only once; default values don't count as initialization
-primitive final variables once initialized with a value cannot be altered ever again
-object reference final variables once initialized cannot be altered to point to another object; but the data within the object can be modified
-that is final reference still allows us to modify the state of the object
-there are no final objects, only final references

Transient variable
------------------
saving an object = serialization = flattening

transient keyword indicates to JVM to skip from serializing the variable.

Volatile variable
-----------------
-applicable only for instance variables
-volatile indicates that all threads should sync their private copy of this variable with the master copy in the memory
-thread safety can be achieved using synchronization instead of volatile

Static
------
what can be static?(the following)

1. Methods
2. Variables
3. A class nested within another class but not within a method
4. Initialization blocks

what can NOT be static?

1. Constructors
2. Classes (unless they are nested)
3. Interfaces
4. Method local inner classes
5. Inner class methods and instance variables
6. Local(stack) variables

Enum Declaration
----------------

As of 5.0, java lets you restrict a variable to having one of only a few pre-defined VALUES--in other words, one value from an enumerated list. The items in the enumerated list are called surprisingly, 'enums'.

-enum helps to avoid unwanted values for a variable that might cause the code to break

e.g. enum CoffeeSize {BIG, HUGE, OVERWHELMING};

CoffeeSize cs = CoffeeSize.BIG; //this is how you access the values

-enum constants need not be in all upper case, but it is Sun coding convention for constants right?
-enums can be declared as their own separate class
-can be declared as a class member
-they must not be declared within a method!
-enum can be declared outside a class(in the same file); but it cannot be private or protected; it can only be public or default access; however you cannot have a public enum outside a public class in the same file; since enum also is a class, as a rule we know that two public classes are not allowed in the same file; hence it gives compilation error
-when you compile the source code, there is a class file generated for every enum just like how it happens for inner classes
-enum declared inside a class is accessed as "enclosing_classname dot enum_name dot enum_value" from other classes; this is because compiler converts this enum into a static final inner class automatically, even when you don't declare the enum as static
-enum is a compiler GIMMICK
-semicolon after enum is optional (even inside a class)
-the order in which enum values are declared matters (they know their index)
-you can iterate through enum values by invoking values() method on any enum type

-inside enum one can add constructors, instance variables, methods and constant specific class body

e.g.

enum CoffeeSize{
BIG(8), HUGE(10), OVERWHELMING(16){ public int getOunces() {return 32;}/*this is called constant-specific-class-body */};
CoffeeSize(int ounces){
this.ounces = ounces;
}

private int ounces;
public int getOunces()
{
return ounces;
}
}

Here, one can invoke getOunces() method on any enum constant defined in the above class.

-every enum has a static method values() which returns the array of enum values in the order they are declared
-you can't invoke enum constructor directly
-you can have variety of enum constructors (overloaded, any no.of arguments, etc)
-as shown in the above example, the constant specific class body allows to override a method for selective constants in the above case for OVERWHELMING constant, getOunces() method is overridden.(shew overly flexy)

>> identifiers can be of any length
>> a legal nonabstract (interface) implementing class must not declare any new checked exceptions for an implementation method; it cannot broaden the checked exception declared in the interface method; but runtime exceptions can be newly declared; should maintain method signature(except for covariant return); 
>> final reference variables must be initialized before the constructor completes

>> An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.

REFERENCE - KATHY SIERRA SCJP BOOK

Tuesday, April 17, 2012

I am a Slytherin

Well, I entered Hogwarts. On first day, the sorting hat saw my true desires in my head. But then it couldn't possibly decide in which house I have to be put in.

Well then, it asked me. "What do you think you are? A Slytherin or a Ravenclaw?"

I was surprised. Why it didn't give me Gryffindor as an option at all? Because I'm not courageous?

But, then I thought, it is better to be Slytherin than a Ravenclaw. So, I said, I might be a Slytherin. Then the sorting hat happily sorted me into Slytherin house.

Despite the encouraging introduction to Slytherin house by J.K. Rowling, I still feel weird being a Slytherin. Especially when you have to hang around Malfoy all the time in the common room.

I think I might get used to.

But, then the sorting hat has truly done excellent job sorting. Because, Slytherins are always at the top in the house points! It truly shows how Slytherins desire the greatness.

If you want to experience Hogwarts, go here http://www.pottermore.com where J.K.Rowling has done an excellent job providing Harry Potter fans a real Hogwarts experience through this site.

I guess the number one Harry Potter fan is the author J.K.Rowling herself. She loves the magical world more than anyone.


Saturday, April 14, 2012

ஜப்பான் பாஷையில் டபாய்ப்பது எப்படி?

[some fun japanese to tamil/english translations]

அறிகாத்தோ - நன்றி
அறிகாத்தோ ஒஸை மாஸு - நன்றிங்க
ஓயாஜி - நைனா
நறுஹுதோ - அத்தானா சமாசாரம்?
ஒஸ்ஸான் - தாத்தா
பாகா - முட்டாப்பயலே
சுமிமாஸென் - மன்னிச்சிக்கோங்க
கோமின்னே ஸாய் - சாரி பா
ஓஹாயோ - வணக்கம்
தெம்மே - உன்ன!
அஹோ - கேனப்பயலே
வக்காடி மஸ்த்தா - புரிஞ்சிது பா
சென்ஸீ - தல
காஸான் - ஆத்தா
தோஸான் - நைனா
பாச்சான் - கெழவி
நானி? - இன்னா?
நந்தா? - இன்னாங்கறேன்?
நானி குரே? - இன்னா இது?
குர நானி? - இது இன்னா?
இத்தா நானி அத்திந்தா ஒமாயிரா? - இன்னா பண்ற நீ?
பாகாக்கா ஒமாயிரா? - முட்டாப்பயலா நீ?
ஒரேவா ஸைக்கோ தா! - நான் வல்லவன்டா
ஒரேவா ஹென்ஸாய் தா! - நான் அதி புத்திசாலி டா!
ஒரேவா ஹென்டாய் தா! - நான் பொருக்கி டா!
மொத்து - இன்னும்
மொத்து மொத்து - இன்னும் இன்னும்
சிக்காரா - சக்தி
கைஸோக்கு - கடற் கொள்ளையன்
ஒத்தேகோ - ஒருவன்
நிங்கேன் - மனிதன்
மிஸுக்கு - தண்ணி
மெஷி - சாப்பாடு
ஸுபெத்தே - எல்லாம்
ஓகன்னு கநிவு - தங்க மணி
மாஸாக்கா - அப்டி இருக்குமோ?
ஓ - ராஜா
வத்தாஷி - நான்
மத்தகு - ஒனக்கே ஓவரா தெரியல?
இத்ததாக்கி மாஸ் - சோறு போட்டதுக்கு தேங்க்ஸ் பா
நிகரோ - இங்கருந்து எஸ்கேப் ஆயிடு
சென்ச்சோ - கேப்டன்
மின்னா சாமா - தாய் மாறே தந்தை மாறே அண்ணன் மாறே!
தாருதா? - யார்ரா நீ?
யோகத்தா - நல்லதாப்போச்சு
சஸ்'ஷிபுரி - பாத்து ரொம்ப நாளாச்சி
கவாய் - அழகு
குவாய் - பயந்தாங்கொள்ளி
யாரோதமா - எல்லாரும் கெளம்புங்க!
தத்தரா - அப்பறம் என்ன? / அதுக்கு தான் சொல்றேன்
பாகேமோனமே - மிருகமே  / அரக்கனே
ஆக்குமா - சாத்தான்
கொமு - ரப்பர்
கொமு நிங்கேன் - ரப்பர் மனிதன்
மாதா மாதா - எங்க ஓடற இன்னும் வருது பாரு
ததகாய் - சண்டை
தவசு - கொன்னுடுவேன்
புத்தபஸ் - பின்னி பெடல் எடுத்துடுவேன்
அரஹித்தா - பசி பசி
ஒரே - நான் / என்னோட
ஹாயாக்கு - சீக்கிரம்
போக்கு - நான்
இய்யா - முடியாது
யுமே - கனவு
இச்சி பன் - நம்பர் ஒன்
கொஸோ - சின்ன பயலே
உர்ரே உர்ரே உர்ரே - வா வா வா இன்னா சண்ட போர்ர நீ
அனாத்தாவா - நீ/ஒன்னோட
தொனக்காய் - பனிச்சறுக்கு வண்டி இழுக்கும் கலை மான்(Courtesy: SearchKo)
சுபராஷி - அருமை அருமை
தஸ்கத்த குரே - காப்பாத்துங்க!
தனுஷ்கத்தா - ரொம்ப குஜால்ஸா இருந்துது பா
ஜோதாஞ்சனைவாயோ - காமெடி பண்ணாத / டபாய்க்காத
தோஸ்தா? - என்ன ஆச்சு?
ஆணிக்கி - அண்ணாத்த/எக்கோவ்
இஷா - டாக்டரு
ஷிம்பாய் - கவல
வக்காருக்கா? - பிரிஞ்சிதா?
வருக்கத்தா - சாரி பா
நக்காமா - தோஸ்து
யாமெத்தே - நிறுத்து
ஸுகே - சூப்பரு
மா....நா.... - யாருக்கு தெரியும்....
ஜெத்தாய் - செத்தாலும் உட மாட்டேன்

arigato - thanks
arigato osai maasu - thanks(more politely)
oyaaji - dad
naruhudho - i see
ossaan - old man
paagaa/baakkaa - stupid
sumimasen - i'm sorry(formal)
gomen ne sai - i'm sorry
ohaiyo - good morning
themmey - you!
aho! - idiot
vakkaadi mastaa - understood
sensei - teacher
kaasaan - mother
thosaan - father
baachaan - old lady
naani - what
nandhaa - what
naani kura - what is this?
kura naani - this is what?
iththaa naani asthindhaa omaiyaraa? - what are you doing?
paagaakkaa omaiyara? - are you stupid?
orevaa psycho dhaa! - i'm the best!
orevaa hensai dhaa! - i'm a genius!
orevaa hentai thaa! - i'm a pervert!
mothu - more
mothu mothu - more and more
chikaaraa - power
kaizoku - pirate
otheko - a guy
ningen - human
mizukku - water
meshi - food
subethe - everything
yume - dream
Ogannu kanivu - golden bell
masaakkaa - could that it be?!!
Ou - king
vathaashi - me
maththagu - honestly
ithadhakki maas! - thanks for the food
nigaroh! - run for it
sencho - captain
minnaa saamaa - ladies and gentlemen 
dharudhaa - who?
yogaththaa - thanks goodness
sas'shiburi - long time no see
kavaai - cute
kuvaai - coward
yaarodhamaa - everyone!
dhaththaraa - that's why/then what? get going!
paagemoname - monster
aakkumaa - devil
gomu - rubber
gomu ningen - rubber man
maadhaa maadhaa - not yet over
thathakai - fight
thavusu - kill you
buththabus - kick your ass
arahiththaa - hungry
ore - I
haayaakku - hurry up
boku - I
iyye - no
umey - dream
ichchi ban - no.1 
koso - brat
urreyurrrreyurrrrrey - egging and charging to fight
anaaththaavaa - you
thonakaai - reindeer
subaraashi - delightful
thaskaththekurey - help me
thanushkaththaa - had been fun
jodhaanjanaaivaayo - don't kid around
dhoasththaa - what happened?
aanikki - elder brother/sister
ishaa - doctor
shimpaai - worry
vakkaarukkaa - understood?
varukkaththaa - feeling sorry
nakamaa - friend and partner and companion
yaameththey - stop it
sugey - awesome
maa...naa... - I guess
zeththaai - hell sure not

some more,...



  1. oreva omaiva ayistheru/ஒரேவா ஒமாய்வா ஆய்ஸ்தேறு - i love you/நான் உன்னை காதலிக்கிறேன்
  2. urusae/உருஸே - shut the hell up/வாய மூடு
  3. bara bara/பர பர - separated/தனித் தனியா
  4. koi / கோய் - come/வா
  5. meethe/மீத்தே - see/பார்
  6. sonna/சொன்னா - oh no(can't believe)/என்ன?! அப்படியா?!
  7. dhekke/தேக்கே - big/பெரிய
  8. dhamedha/தாமேதா - useless/பிரயோஜனம் இல்லை
  9. mudhadha/முதாதா - totally useless/ஒன்னும் முடியாது
  10. noro noro/நொரோ நொரோ - slow slow/மெது மெது
  11. oumi /ஊமி- ocean/கடல்
  12. oreva naaru/ஒரேவா நாறு - i will become/நான் ஆவேன்
  13. shimaththaa/ஷிமத்தா - holy crap/கிழிஞ்சிது
  14. kono/கொனோ - here/this/இங்கே
  15. nakkamakka/நக்காமாக்கா - is friend?/தோஸ்தா?
  16. psythae/சைத்தே - worst/மோசமான
  17. genjitsu/கெஞ்சிட்சு - real/நிஜம்
  18. orenga irundha/ஒரேங்கா இருந்தா - i'm here (still)/நான் இருக்கேன் பயப்படாத
  19. anu othako/அணு ஒத்தகோ- that man/அந்த ஆள்
  20. nandhatho?/நந்தாத்தோ?- what did you say?/என்ன சொன்ன?!
  21. themmeva ithai nunnandha?/தெம்மே இத்தாய் நன்நந்தா? - what are you?!/நீ மனுஷனா இருக்க வாய்ப்பு இல்ல
  22. nikku/நிக்கு - meat/கறி
  23. mamuru/மமுறு - protect/பாதுகாப்பு
  24. kaami/காமி - god/கடவுள்
  25. mamuri kami/மமுறு காமி - god of protection/காவல் தெய்வம்
  26. minna/மின்னா - everyone/எல்லாரும்
  27. sodha/ஸோதா - i see/அப்பிடியா சங்கதி
  28. usu/உசு - lie/பொய்
  29. dhamaaru/தமாறு - shut up!/வாய மூடு
  30. sokkaa/சோக்கா - is it?(i see)/அப்பிடியா
  31. aathadimaiyo/ஆத்தாடிமையோ - absolutely!/கண்டிப்பா
  32. naai/நாய் - not/இல்ல
  33. varinnaa/வரின்னா - sorry/மன்னிக்கணும்
  34. yeppaadi/எப்பாடி - so that's true then/நான் பயந்த மாதிரியே ஆயிடுச்சே
  35. orengaa captain dha/ஒரேங்கா கேப்டன் தா - i'm the captain!/நான் தான் கேப்டன்
  36. iguzo/இகுசோ - lets go/போலாம்
  37. shimaththa/ஷிமத்தா - shit(in frustration)/ஐயோ போச்சி
  38. diajobu/தைஜோபு - are you alright?/ஒனக்கு ஒன்னும் காயம் படலியே?
  39. hanase/ஹனாஸே - let me go??/என்னை விடு
  40. kzo/க்ஸோ - shit(furious frustration)/ஐயோ
  41. shineh/ஷினே - die/சாவு
  42. thonikaakku/தோனிகாக்கு - anyhow/எப்படி இருந்தாலும்/என்னானாலும்
  43. shiranaai/ஷிரனாய் - don't know/never heard/unknown/தெரியாது
  44. oyaabun/ஓயாபுன் - boss/முதலாளி
  45. onnaa/ஒண்ணா - woman/பொம்பள
  46. kempai/கெம்பாய் - cheers/சியர்ஸ்(இது இங்க்லிஷ்)
  47. thakkaara/தக்காரா - treasure/புதையல்
  48. omaiye/ஒமாயே - you.../என்னப்பா நீ ரொம்ப நல்லவனா இருக்கியே