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.

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]

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'.



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


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

-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

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

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


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.


No comments:

Post a Comment