Friday, February 24, 2012


Java platform: API + JVM
API Java application programming interfaces  libraries of compiled code that you can use in your programs
JVM Java Virtual Machine. Interpreter for the Java programs
JRE: Java Runtime Environment
JDK: Java Development Kit
SDK: software development kit
ASCII: American Standard Code for Information Interchange.
Object: variable
Class: type
Inheritance: to derive subclasses from superclasses
Interface: blueprint for a class
Package: namespace to bundle classes
.java: source code file extension for java
.class: compiled file
.jar: (Java Archive) ZIP for Java  files.
.war: ( Web application ARchive) JAR file for Web application.
- public: visible everywhere
- no modifier: visible only within its own package
- protected: visible within its own package and subclass in another package
- private: visible only in  its own class
package is a grouping of related types providing access protection and name space management.
To create a package, you choose a name for the package  and put a package statement with that name at the top of every source file that contains the type that you want to include in the package.
The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
If you put multiple types in a single source file, only one can be public, and it must have the same name as the source file.
Naming Conventions
Package names are in all lower case.
Companies use their reversed Internet domain name to begin their package names
ex com.example.mypackage
To use a public package member from outside its package:
- Refer to the member by its fully qualified name.
Ex graphics.Rectangle
- Import the package member
Ex import graphics.Rectangle;
- Import the member's entire package
import graphics.*;
put an import statement at the beginning of the file before any type definitions but after the package statement
static import statement so that you don't need to prefix the class name.

import static java.lang.Math.PI;
import static java.lang.Math.*;
Setting the CLASSPATH System Variable

Windows: C:\> set CLASSPATH
Unix: % echo $CLASSPATH

Windows: C:\> set CLASSPATH=
Unix: % unset CLASSPATH; export CLASSPATH

Windows:C:\> set CLASSPATH = C:\users\george\java\classes
Unix: % CLASSPATH = /home/george/java/classes; export CLASSPATH
curly braces {}
class ExampleProgram {
public static void main(String[] args)
{System.out.println("I'm a Simple Program");}

Compile: javac
Execute: java ExampleProgram

// Double slashes
/* These are C-style comments*/
/** This class displays a text string at
*  the console. Javadoc comments

class LessonTwoA {
static String text = "I'm a Simple Program";
public static void main(String[] args)
{ System.out.println(text); }}
class Bicycle { int c = 0;
void changeCadence( int newValue ) { c = newValue; }
void printStates() { System.out.println("cadence:" + c);  } }
class BicycleDemo {
public static void main(String[] args) {
Bicycle b1 = new Bicycle(); Bicycle b2 = new Bicycle();
b1.changeCadence(50); b1.printStates();
b2.changeCadence(50); b2.printStates();
} }
class MountainBike extends Bicycle {
// new fields and methods defining a mountain bike would go here

Bicycle is superclass
MountainBike is a subclass
interface Bicycle {
 void changeCadence(int newValue);
 void changeGear(int newValue);
 void speedUp(int increment);
 void applyBrakes(int decrement);

class ACMEBicycle implements Bicycle {
//remainder of this class implemented as before
final class: cannot be subclassed.
final method: cannot be overridden by subclasses
abstract class: cannot be instantiated, must be subclassed.

abstract method is declared without an implementation:
abstract void moveTo(double deltaX, double deltaY);
override: to create an instance method in a subclass with same signature of an instance method of a superclass.
hide: to create a static method in a subclass with same signature of an static method of a superclass.
overload: to create a method with the same name but different signatures.
signature: the method's name and the parameter types.
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000
int decVal = 26; // The number 26, in decimal
int octVal = 032; // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal
int binVal = 0b11010; // The number 26, in binary
types:  primitive | reference
primitive: boolean |  numeric
numeric: byte | short | int | long | char | float | double.
reference: class | interface | array
null type
byte: 8-bit signed two's complement integer. From -128 to 127.
short: 16-bit signed two's complement integer. From -32,768 to 32,767.
int: 32-bit signed two's complement integer, From -2^31 to (2^31)-1.
long: 64-bit two's complement integer. From -2^63 to (2^63)-1.
float: single-precision 32-bit IEEE 754 floating point.
double: double-precision 64-bit IEEE 754 floating point.
boolean: true or false.
char: 16-bit Unicode character. From '\u0000' (or 0) to '\uffff' (or 65,535).

F or f: float
D or d or nothing: double
E or e: float or double (scientific notation)
double d1 = 123.4;
double d2 = 1.234e2;
float f1  = 123.4f;
Default Value (for fields)
byte, short, int, long, float, double: 0
char: '\u0000'
String (or any object): null
boolean: false
Local variables: must be explicitly given a value before it is used, by either initialization or assignment.
class ArrayDemo {
public static void main(String[] args) {
int[] a1;
a1 = new int[2];
a1[0] = 100;
a1[1] = 200;
System.out.println( "Element at index 0:" + a1[0]);
System.out.println( "Element at index 1:" + a1[1]);
class Test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
  System.out.print(i == 0 ? args[i] : " " + args[i]);


java Test Hello, world.
Expression: construct made up of variables, operators, and method invocations that evaluates to a single value.
Statement: a complete unit of execution.  It terminates with a semicolon (;).
Block: group of zero or more statements between balanced braces used anywhere a single statement is allowed.
if (conditon) statement;
if (conditon) statement; else statement2;

int m = 8; String s;
switch (m) {
case 1:  s = "January"; break;
case 2:  s = "February"; break;

while (condition) { statement; }
do { statements;} while (conditon);

for( int i=1; i<11; i++ ) { System.out.println("Count is: " + i); }

int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) { System.out.println("Count is: " + item);}

for (i = 0; i < arrayOfInts.length; i++) {
  if (condition1) continue; //go back to the start of the  loop
  if (condition2) break; //get out of the loop
class MyClass extends MySuperClass implements Interface1, Interface2 {
    // field, constructor, and
    // method declarations
By convention the class name's initial letter is capitalized.
By convention the first word in a method name should be a verb in lowercase.
Constructor is a method that use the name of the class and have no return type and is invoked by the new operator.
Bicycle myBike = new Bicycle(30, 0, 8);
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
 Instance Variables (Non-Static Fields): variable declared inside a class but outside the methods without the static keyword. Each instance of a class has its own copy.
 Class Variables (Static Fields): variable declared inside a class but outside the methods with the static keyword. Each instance of a class shares the same copy.
 Local Variables: variable declared inside a method.
 Parameter: variable declared in a method declaration.
 Arguments: the actual values that are passed in when the method is invoked
 tokens: identifiers , keywords , literals , separators , and operators.
 Identifier: an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling  as a keyword , boolean literal , or the null literal. Letters and digits may be drawn from the entire Unicode character set.
 Keyword: reserved words that cannot be used as identifiers.
 Literal: is the source code representation of a value of a primitive type , the String type , or the null type.
Literals of types char and String may contain any Unicode (UTF-16) characters.
Examples of char literals:

\b (backspace)
\t (tab)
\n (line feed)
\f (form feed)
\r (carriage return)
\" (double quote)
\' (single quote)
\\ (backslash).
package other;
public class Other { static String hello = "Hello"; }

package testPackage;
class Other { static String hello = "Hello"; }
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " "); //true
System.out.print((Other.hello == hello) + " "); //true
System.out.print((other.Other.hello == hello) + " "); // true
System.out.print((hello == ("Hel" + "lo")) + " "); //true
System.out.print((hello == ("Hel" + lo)) + " "); //false
System.out.println(hello==("Hel" + lo).intern()); // true
If the variable name consists of only one word, spell it all in lowercase. (int current)
If it consists of more than one word, capitalize the first letter of each subsequent word (int overCurrent)
If it is a constant value, capitalize every letter and separating subsequent words with the underscore character. (static final int NUM_GEARS = 6)
nested class is any class whose declaration occurs within the body of another class or interface.
Inner classes may be static, in which case they have no access to the instance variables of the surrounding class;
A final method may cannot be hidden or overridden.
Operator     Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

Operator     Description
+  Unary plus operator; indicates positive value (numbers are positive without this, however)
-  Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
!   Logical complement operator; inverts the value of a boolean

== equal to
!= not equal to
>   greater than
>=  greater than or equal to
<    less than
<=   less than or equal to

the second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR

ternary operator
result = someCondition ? value1 : value2;
if (someCondition) result =value1; else result =value2;
class Parent {}
interface MyInterface {}
class Child extends Parent implements MyInterface {}

Parent obj1 = new Parent();
Parent obj2 = new Child();
boolean result;
result = obj1 instanceof Parent; // true
result = obj1 instanceof Child; // false
result = obj1 instanceof MyInterface; //false
result = obj2 instanceof Parent; //true
result = obj2 instanceof Child; //true
result = obj2 instanceof MyInterface; //true
~  Unary bitwise complement
<<   Signed left shift
>>   Signed right shift
>>>   Unsigned right shift
&   Bitwise AND
^    Bitwise exclusive OR
|     Bitwise inclusive OR
enum type is a type whose fields consist of a fixed set of constants.
All enums implicitly extend java.lang.Enum.


public class EnumTest {
Day day;
public EnumTest(Day day) { = day;}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:System.out.println("Mondays are bad.");break;
case FRIDAY:System.out.println("Fridays are better.");break;
case SUNDAY:System.out.println("Weekends are best.");break;
default:System.out.println("Midweek days are so-so.");break;
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);

for (Planet p : Planet.values()) {
 System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass));}

public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS   (4.869e+24, 6.0518e6),
EARTH   (5.976e+24, 6.37814e6),
MARS    (6.421e+23, 3.3972e6),
JUPITER (1.9e+27,   7.1492e7),
SATURN  (5.688e+26, 6.0268e7),
URANUS  (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
private final double mass;
private final double radius;
Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
private double mass() { return mass; }
private double radius() { return radius; }
public static final double G = 6.67300E-11;
double surfaceGravity() { return G * mass / (radius * radius); }
double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); }

public static void main(String[] args) {
if (args.length != 1) {
 System.err.println("Usage: java Planet <earth_weight>");
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
 System.out.printf("Your weight on %s is %f%n",
  p, p.surfaceWeight(mass));  
public class Box<T> {
 private T t; // T stands for "Type"
 public void add(T t) {this.t = t;}
 public T get() {return t;}}

Box<Integer> integerBox = new Box<Integer>();

public class BoxDemo3 {
public static void main(String[] args) {
 Box<Integer> i1 =  new Box<Integer>();
 i1.add(new Integer(10));
 Integer s1 = i1.get();
public class Box<T> {

private T t;        
public void add(T t) { this.t = t; }
public T get() { return t; }

public <U> void inspect(U u){
 System.out.println("T:" + t.getClass().getName());
 System.out.println("U:" + u.getClass().getName());}

public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.add(new Integer(10));
integerBox.inspect("some text");}

public interface Collection<E>
extends Iterable<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);

boolean add(E element);//optional

// optional
boolean remove(Object element);
Iterator<E> iterator();

// Bulk operations
boolean containsAll(Collection<?> c);

boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);// optional
boolean retainAll(Collection<?> c);// optional
void clear();// optional

// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
for (Object o : collection) System.out.println(o);
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
static void filter(Collection<?> c){
for (Iterator<?> it = c.iterator();
 it.hasNext(); )
if (!cond(;}
//remove all instances of a specified element e, from a Collection c.
public static <T> Set<T> singleton(T o)
Returns an immutable set containing only the specified object.
//remove all of the null elements from a Collection.
//dumps the contents of c into a newly allocated array of Object
Object[] a = c.toArray();
//dumps the contents of c into a newly allocated array of String
String[] a = c.toArray(new String[0]);
//create another Collection containing the same elements but with all duplicates eliminated
Collection<Type> noDups = new HashSet<Type>(c);
//preserves the order of the original collection while removing duplicate element.
Collection<Type> noDups =
 new LinkedHashSet<Type>(c);
//returns a Set of the same generic type as the one passed
public static <E> Set<E>
removeDups(Collection<E> c)
{ return new LinkedHashSet<E>(c); }
//prints out any duplicate words, the number of distinct words, and a list of the words with duplicates eliminated.
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);

(s.size() + " distinct words: " + s);}}
Set<Type> union = new HashSet<Type>(s1);

Set<Type> intersection = new HashSet<Type>(s1);

Set<Type> difference = new HashSet<Type>(s1);
import java.util.*;
public class FindDups2 {
public static void main(String[] args) {
Set<String> uniques = new HashSet<String>();
Set<String> dups    = new HashSet<String>();

for (String a : args)
  if (!uniques.add(a)) dups.add(a);

// Destructive set-difference

System.out.println("Unique words:" + uniques);
System.out.println("Duplicate words:" + dups);}}
//calculates the symmetric set difference of two sets nondestructively
Set<Type> symmetricDiff = new HashSet<Type>(s1);
Set<Type> tmp = new HashSet<Type>(s1);

No comments:

Post a Comment