Java Basics

  

These are my personal notes that I use as a quick help in my work.
You are welcome to read them.

Contents of current page Top-level home page
 
Index  Java Internet Oracle Notes
Linux Basics Web Basics SQL Notes
Informatica Servlets Apache BkpRstore SQL*Plus
Teradata   LDAP Storage PL/SQL
Windows     Tables OEM
UML   Net8 Portal
SQL Server Python perl Performance OLAP
Vmware Visual Basic PHP/MySQL User Mgmt  
Git        
More technical pages here

Contents

 


Introduction

  

Three types of java programs: applets, applications, and servlets/JSP pages.

Programming environment

Sample application:

class HelloWorldApp {
  public static void main(String[] args){
    System.out.println("Hello World!");
    }
}

Compile: javac -verbose HelloWorldApp.java
Run: java HelloWorldApp
The method "main" is the starting point.
To terminate (e.g. in windowClosing): dispose(); System.exit(0);

Memory allocation (default is 256MB):
java -Xmx1024MB HelloWorldApp

Sample windows bat file to compile
javac needs jdk
SET JAVA_HOME="C:\Program Files (x86)\Java\jdk1.8.0_141"
SET PATH=%PATH%;"%JAVA_HOME%\bin"
javac -verbose HelloWorldApp.java

Sample windows bat file to run
java can use jre if the .class file is present. You can use the jdk as well to run.
SET JAVA_HOME="C:\Program Files (x86)\Java\jre1.8.0_141"
SET PATH=%PATH%;"%JAVA_HOME%\bin"
java HelloWorldApp

Sample applet:

import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet {
  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
    }
  }

Compile: javac -verbose HelloWorld.java

Page to display applet (size is in pixels):

<HTML> <BODY>
<TITLE>Hello World!</TITLE>
<APPLET CODE=HelloWorld WIDTH=150 HEIGHT=40> </APPLET>
</BODY> </HTML>

Open the HTML page or run appletviewer the-html-page.html

Execution of an applet  
Constructor  
public void init() {...} When applet is first loaded
public void start () {...} When applet starts;
when browser is deiconized;
when browser returns to page (back from another URL).
public void paint(Graphics g ){...}  
public void stop() {...} When browser is iconized;
when browser enters another link.

 

 


Basics and Variables

An identifier contains characters (Unicode UTF-16, not only a-z and A-Z), digits (but not at beginning), '_' (underscore) and '$'.
Names are case sensitive. Starting with "$", and "_" is allowed but not good practice.
Variables start with lowercase and each word starts in upper case (nameWordWord). Constants are all uppercase with underscores seperating the words (CONSTANT_WORD_WORD). It is possible (since Java 7) to place underscores in between digits in a numerical litteral.

// comments
/* comments */
/** comments picked up by javadoc */

Visibility:

Specifier visible in class visible in package visible in subclass full access
private (members)
X
 
 
 
default access
(without "public", "private" or "protected")
for members and classes
X
X
 
 
protected (members)
X
X
X
 
public (members and classes)
X
X
X
X
private protected
no longer used (java 1.0)
-
-
-
-

Note that objects of the same type can see each others private members. The "privacy" is not at the object level but at the class level.
Generally, fields (variables) should be private: use methods to give or modify field values.
Restrict visibility of methods.

 

Static variables become class variables as opposed to instance variables. If the static variable is public, it can be accessed without any instance of the class. For clarity, access the static variables with the name of the class as opposed to the name of an instance. The static variables are stored in one place in memory independently of instances. Use static methods to handle static variables. An example could be the count of instances created, with a counter increment in the constructor.
Final variables are constants (name in upper case by convention).
Transient variables cannot be serialized (for serialization).
Volitile variables cannot be optimized; this is rarely used.
Variables of primitive data types (byte, short, int, long, float, double, boolean, and char) are not intialized.

 

Types

boolean truth = true; True or false

char c, cc;

'\t' tab           '\u????' unicode character
'\n' newline       '\'' single quote
'\r' return        '\"' double quote
'\r\n' CR-LF       '\\' backslash
'\f' form feed     '\b' backspace

1 character, 0..216-1, unicode
String a_string1;
String a_string2 = "Hello World!"
StringBuffer sb = new StringBuffer(10);

Use double quotes!
Note capital S in String
StringBuffer is for string manipulations

Integral types:
byte i = 1; //  8 bits, i.e. -128..127
short       // 16 bits, i.e. -32'768..32'767
int         // 32 bits
long        // 64 bits
Literals are generally int, long if followed by L
two's complement
0nnn octal
0xnnn hexadecimal

Floating point:
float       // 32 bits
double      // 64 bits

Literal is float if followed by F or
double if followed by D

class Date
  {int day;
   int month;
   int year;}

Date one_date;         // does not assign space
one_date = new Date(); // constructor

one_date.year = 2003;  // assigning to one member

Aggregate data types

Declaration does not assign space: use the constructor
This is also necessary for String

Wrapper classes for basic types

Number.
Byte.MAX_VALUE
Short.MIN_VALUE
Integer.byteValue()
Long.intValue()
Float.
Double.
BigInteger
BigDecimal

Wrapper classes

To each type corresponds a class
Note first letter is upper case
Note Integer for int, Character for char

Character aChar = new Character('a');
aChar.compareTo('b') --> int. neg if aChar < 'b', 0 if equal, pos if aChar > 'b'
aChar.equals('b') --> boolean
aChar.charValue() --> 'a'
aChar.toString() --> "a"
aChar.isUpperCase() --> boolean
 
aString.length() / aStringBuffer.length()
aStringBuffer.capacity()
aString.charAt(3) / aStringBuffer.charAt(3)
Number of characters
Capacity is allocated length for string buffer
Character at 0 .. length -1
aString.substring( 3 [,5] )
aStringBuffer.substring( 3 [,5] )
Sub string from 3 [to 5]; notice small "s". Count from 0 to len-1.
The result goes from beginIndex to endIndex-1.
aString = "Chris"; aString.substring(2,4) -- > "ri"

aString.equals(anotherString) --> true or false
aString.toUpperCase() / aString.toLowerCase()

 

aString.toCharArray() --> an array of characters  
aString.indexOf("looking for" [, int from])
aString.lastIndexOf("looking for last" [, int from])
"looking for" may be a character or a string
Returns 0..length-1, or -1 if not found
aStringBuffer.append(...)
aStringBuffer.insert(index_before, ...)
aStringBuffer.setCharAt(..., ...)
Automatic allocation of memory (but slow)
String.valueOf(a number) --> string
anObject.toString() --> string representation
Integer.valueOf("..."), Long.valueOf("...") --> number
Double.valueOf("..."), Float.valueOf("...") --> number
 
Void Wrapper for void
Boolean Wrapper for boolean
NumberFormat Class for formatting numbers according to locale
enum anEnum { ABC, DEFG, TER }; Enumeration. The elements are constants, so put in upper case.
All enums extend java.lang.Enum

DecimalFormat df = new DecimalFormat("pattern{;pattern}");
df.format( double ) --> String
###,###.###      --> 123,456.789 0.123
###.##% 12.3%    --> (0.123)
000000.000       --> 000123.450
$###,###.### CHF --> $12,345.67 CHF
###.#####E000    --> 12.34567E003

Locale cl = new Locale("en", "US");
DecimalFormatSymbols dfs = new DecimalFormatSymbols(cl);
dfs.setDecimalSeparator('.');
dfs.setGroupingSeparator('\'');
DecimalFormat df = new DecimalFormat("pattern", dfs);
df.setGroupingSize(4);

pattern: {prefix}#,##0.##{suffix}
(or {p}0,000.000{s})
prefix/suffix is a string
% --> multiply by 100 and show '%'
E --> exponent

DecimalFormat is overloaded

Objects

ClassName new_variable_name;

Declaration

new_variable_name = new ClassName(parameters);

Instantiation and initialization (the constructor initializes the object)

varable_name = null; Release memory

Arrays

char cc[];    char[] cc;
cc = new char[20];

Declares array. The two syntaxes are equivalent, although char[] is preferred.
Then create the array (initialized to zero character).

Date d[];     Date [] d;
d = new Date[10];
d[0] = new Date();
d[1] = new Date();

Declare the array
and create the array (each element is null),
then create each object!
Once the array is created, you cannot add elements.

for (int i=0; i < Date.length; i++) ... Elements 0 .. array_name.length-1
String names[] = {"Chris", "Vicky", ...};
Date d[] = {new Date(4,9,2001), new Date(5,12,2003), ...};
Shorthand initialization (note curly brackets)
Get length with names.length-1
char twoDim [][] = new char [5][7]; Shorthand rectangular array
char twoDim [][] = new char [5][]; // but not [][5]
twoDim[0] = new char[6];
twoDim[1] = new char[6];
Array need not be rectangular
int ii[] = new int[8];
ii = new int[4]
New assignement results in loss of previous array!
int a[] = new int[4];
int b[] = new int[5];
System.arraycopy(a, 0, b, 0, a.length);
Special method of the Sytem class.

anArray.binarySearch
anArray.equals
anArray.fill
anArray.sort (anArray.parallelSort)
Various methods of the java.util.Arrays class:
index of a specific value
are two arrays equal?
fill array
sorting (parallel sort in version 8)

ArrayLists

import java.util.*;
ArrayList<String> list = new ArrayList<String>();

import java.util.*;
ArrayList<String> list = new ArrayList<String>(100);

Declares array list. Name of underlying object between < and >. (called generics)
Older versions of java: ArrayList list = new ArrayList();

It is possible to give a size at creation (here 100). It is a hint, and more elements can be created.

list.add(...)
list.get(...)
list.contains(...)      list.indexOf(...)
list.remove(...)
list.size()

Add an element, get an element, test if element is in the list, remove, get number of elements

for (UnderlyingClass v : list) { ... }

Loop through the class

Collections.sort(list)

Sort using the collections class, which is also part of java.util

 

Hash Maps

import java.util.*;
HashMap map = new HashMap();
HashMap<String, Long> map = new HashMap<>();

import java.util.*;
HashMap map = new HashMap(40, 0.6F);

Declares hash map. Put generics between < and >: the first is the key and the second is the value.

It is possible to give the number of buckets at creation (here 40), and the load factor, which is the percentage of capacity at which new buckets are automatically created.

m.put(aKey, aValue);
m.get(aKey);
m.getOrDefault(aKey, aDefault);
m.containsKey(aKey);
m.containsValue(aValue);
m.size()
m.entrySet()

Adds a key-value pair, get a value based on the key (returning null if not found), get a value or use default, test for existence of a key or a value, return the number of elements, returns set of entries (for loops, use Set class in java.util) .

for (Map.Entry<String, Long> entry : m.entrySet()) {
    String theKey = entry.getKey();
    Long theValue = entre.getValue();
}

Adds a key-value pair, get a value based on the key (returning null if not found), get a value or use default, test for existence of a key or a value, return the number of elements, returns set of entries (for loops, use Set class in java.util) .

 

Math

  

 

 

 

Variables defined inside a method are automatic = local = temporary = stack. Destroyed at exit of method.

 

 


Operators

<< .
[]
(params)
For qualified names
Use for arrays
parameter list
(java.sun.com puts the postfix ++ and -- here)
<< ++ --

+ -
~
!
(cast)
a=5; x=a++; --> x==5, a==6   // postfix notation
a=5; x=++a; --> x==6, a==6   // prefix notation

Sign (note that unary + has the effect of promoting a byte, short or char to type int)
Not / bitwise complement

use ( ) around expression for type cast: (int)(expression)
    >> new New object
(java.sun.com puts the casting operator here)
    >> * /
%
Multiplication and division
modulo (integer remainder) 9 % 7 --> 2
    >> +
-
+ also for concatenation
(infix notation)
    >> <<
>>
>>>

<<  drop <--  10101010000 <--0
>>    sign--> SSSS0101010  --> drop
>>>      0--> 00000101010  --> drop

Note that operand is modulo 32, so x<<32 is same as x<<0

    >> < > <= >=
instanceof
 
    >> == != Equal (note double sign), not equal
    >> & bitwise and; both operands are always evaluated
    >> ^ bistwise xor (different)
    >> | bitwise or; both operands are always evaluated
    >> && logical and; does not evaluate second operand if first is false
    >> || logical or; does not evaluate second operand if first is true
<< cond ? expr-for-true : expr-for-false conditional
<< = *= /= %= += -=
<<= >>= >>>=
&= ^= |=
Assignement
a op= b <== equivalent to ==> a = a op b

Bitwise operations for using with flags:

int VISIBLE = 1;
int DRAGGABLE = 2;
int flags = 0;
flags = flags | VISIBLE; // set flag
flags = flags ^ VISIBLE; // flip flag
flags = flags & ~ VISIBLE; // reset flag
if ((flags & VISIBLE) == VISIBLE) { ... } // test flag

 


Flow Control

if (boolean expr) {
  ...
} else if (boolean expr) {
  ...
} else {
  ...
}
"else" is optional
switch (int expression) {
  case expr:
    ...;
    ...;
    break;
  case expr:
    ...;
    // fall through without "break"
  case expr:
    ...;
    break;
  default:   
    ...;
    break;  // last "break" is good practice
}
Works with byte, short, char, int, enumerated types, and with classes such as String, Character, Byte, Short, and Integer.

Remember the "break"!
for (init, init; boolean expr; alter expr, alter expr) { ... }
example:
for (i=0; i<myArray.length; i++) {
  ...
  break;
  ...
}
 
int[] iArray;
for (int i : iArray) { ... }
With arrays and collections
while (boolean expr) {
  ...
  break;
  ...
}
 

do {
  ...
  break;
  ...
} while (boolean expr);

 
break [label];
continue [label];
label: ...;
break ... out of loop
continue ... at beginning of next iteration of loop
the ingredient for spaghetti code!
java.lang.Object
  java.lang.Throwable
    java.lang.Exception

      java.lang.RuntimeException

    java.lang.Error

Throw --> catch if you can, otherwise the program terminates

Error --> let program terminate
Runtime --> useful during debug
Others --> handle (the compiler won't let you forget)

Exception is in java.lang, therefore an import statement is not necessary

try {
  //protected code
} catch (TheException e) {
  // code to handle exception e
  System.out.println(e.toString);
} catch (AnotherException | YetAnotherException e) {
  // more code
} catch (Exception e) {
  System.err.println(e.getMessage());
  // generic handle, but too general to be useful
} finally {
  // code that is always executed
  // typically close objects if open
  // (except in case of System.exit)
}

Examples:

ArithmeticException
NullPointerException
ClassCastException
NegativeArriySizeException
ArrayIndexOutOfBoundsException

TheException and AnotherException are throwable objects

Multiple exceptions separated by "|" (pipe)

public class MyException extends Exception { }

class another
...
try {
... throw new MyException (); ...
} catch(myException e) {...}   

 

oneMethod {
  try {
    anotherMethod();
  } catch (AnException) {
    doErrorProcessing;
  } catch (AnotherException) {
    doErrorProcessing;
  }
}
anotherMethod throws AnException, AnotherException {
  thirdMethod();
}
thirdMethod throws AnException {
   ... // some treatment that can cause AnException
}

Rule "declare or handle": either use a "try{}catch(){}" block or put in declaration (as on left) so that calling method can handle.

The compiler checks that some exceptions are handled: these are checked exceptions. Others are runtime exceptions and the compiler will not complain if there is no handler.

passVarNumberOfArgs(type aParam, type... aVararg) varargs:
For the last parameter, put the type, three dots (ellipsis), a space, and the parameter name. Allows zero or more parameters. Treat as an array. Get the number of parameters with aVararg.length.

 

Threads

In java, threads are "pre-emptive", that is higher priority "pre-empts" a lower priority thread that is running. Runnable threads are placed in queues according to priority. Otherwise, execution passes from one thread to another when the previous thread stops (or sleeps). A stopped thread goes to the back of the queue.

A thread (small "t") has: A Thread (big "T") is an instance of the class java.lang.Thread
See example below.
CPU Thread t
code class 'instanceOfRunnable'
data instance 'r' of the class

public class InstanceOfRunnable implements Runnable /* or extends Thread */ {
  // Must have run() method
  public void run() {
    synchronized(this) {
      while (cond-not-fulfilled) {
        try {this.wait();} // wait for condition
        catch (InterruptedException e) { }
      }
      ...... // Here, do treatment that is protected by synchronized
      this.notify(); // waiting threads can start
    } // end synchronized
    try { Thread.sleep(10); } // Eventual pause
    catch (InterruptedException e){ }
  
}
}

Runnable r = new InstanceOfRunnable();
Thread t = new Thread(r); // constructor for Thread takes an instance of Runnable
t.start(); // start the execution

t.sleep(n); // pause minimum of n milliseconds, threads of lower priority may be executed
t.suspend() //
t.yield();  // only yield to threads of same priority level
t.stop();   // cannot be re-started
Thread.currentThread()
     --> thread currently running (use to get handle on itself);
     not necessary if extending Thread
t.isAlive() --> thread is started and not stopped and has not reached the end of its "run()" method

Each object has two queues: queue for lock and queue for wait/notify.

Locking

Make code consistent in a class by holding a lock; locked threads join a sort of queue:
method a { synchronized (this) { /* statements that modify data */ } }
method b { synchronized (this) { /* statements that modify data */ } }

All of a method can be synchronized, but more danger of deadlocks:
sychronized void aMethod() {}
N.B. Protected data should be private
N.B. One strategy of prevent deadlocks is to take the locks always in the same order.

Thread interaction (wait / notify)

object.wait(); --> thread no longer runnable, on wait queue of object
object.notify(); --> first in queue is runnable
object.notifyAll(); --> all in queue are runnable
An InterruptedException also terminates the wait state
N.B. Put wait() and notifiy() inside a synchronized block.

(See comment) 

 

 


Classes

public class Date {
  private int day, month, year;
  public Date(int d, int m, int y) {
    day = d; month = m; year = y;
  }
}

Constructor method has exactly the same name as the class; it cannot return a value (do not put void).

If the constructor is
  public --> all classes can create an instance;
  private --> ??
  protected --> only subclasses and classes in package
  (no specifier) --> only classes in package

Overloading the constructor name is possible. Use "this" to refer to one of the constructor methods when within the class. Use super(...) in the constructor of a subclass

public static void main() Starting point
Static indicates no need for invoking an instance. A static method is a class method.
<access level> [<modifiers>] <return_type>
     <identifier>( [<type> <argument>
                   [, <type> <argument>]] )
    [ throws <exceptions> ]
    { <block> }

Method declaration:
access level = public, private, ...
modifiers = static, abstract, final, native, synchronized
return_type: put void if none

Arguments are always passed by value. For reference types, the reference cannot be modified, but the object's values can be (i.e. the values to which the reference points). Classes are reference type objects.

If arguments have same name as the class's member variables, then they "hide" the member variables. Use "this." to refer to class members. Note that hiding is error-prone.

<access level> static aMethod(args)

static {
  ... // use to initialize static variables
}

A static method becomes a class method that can be called without creating an instance. However only static variables and the arguments can be used; "this" cannot be used. Other variables and methods are available "through" an instance of the class. By default, members are non-static.
<access level> final A final class cannot have sub-classes.
Final methods cannot be overridden (static or private methods are final anyway).
A final variable acts as a constant.

<access level> abstract class ... {
  public abstract ... ( args ); // no body
  public ... (); { /* non-abstract method */ }
}

Abstract classes declares methods without bodies that must be implemented in sub-classes. Instantiate the subclass, not the abstract class (x = new SubClass();).
<access level> native Method implemented in another language
<access level> synchronized Method needs a monitor to run
return [a_value]; Return a value (must be of return type); no value if void. For classes: an object of that class or a sub-class
public void display(int i)
public void display(float f)
Overloading method names is creating several methods with the same name but with unambiguous differences in the argument lists. However, the type does not differentiate methods, just the argument list.

public class StandardClass ...

public class MyClass extends StandardClass ...
public class MySecondClass extends StandardClass ...

MyClass inherits variables and methods (but not constructors) from StandardClass, which is the parent class. A class can only inherit from one parent class (except interfaces). Public and protected members are inherited, as well as package access members if in the same package as the superclass.

public class StandardClass {
  public String Display () {
  ...
  }
}

public class MyClass extends StandardClass {
  public MyClass () { \\ constructor
    super(...);
  }
  public String Display () {
    return super.Display + "more details"
  }

Methods with the same name, return type and arguments override the methods of the parent class. The runtime type of the object determines which method is used.

Note that subclass variables with the same name hide those of the superclass. Access hidden variable with "super.".

Use "super." to reference a method of the parent class (or of the ancestor class). Refer to the parent constructor by using "super()" as the first statement in the constructor.

An overriding method cannot be less accessible that the parent's method e.g. a private method cannot override a public method. And an overriding method cannot throw more exceptions than the method that it overrides.

Final methods cannot be overridden. Static methods can be hidden but not overridden.

It is a good idea to always define a no-argument constructor

class EnclosingClass { // also called "outer class"
  static class StaticNestedClass() { } // if static then called "static nested class"
  class InnerClass() { } // if not static then called "inner class"
}
Nested classes see also private members of enclosing class. Two types: static nested class and inner class (non-static)

[public] interface AnInterface
  [extends SuperInterfaces, AnotherSuperInterface] {
  ...
  aMethod(params); // no body for methods, just ';'
}
public class RealClass
  implements AnInterface, AnotherInterface {
  ...
}

An interface is an abstract class where no methods have bodies and where there are no member variables (just constants that are by definition public static final). Methods are by definition public and abstract.

A class can inherit several interfaces (but only one class).

Unrelated classes can inherit the same interface.

The interface can be used as a type (for parameters).

StandardClass anObject = new MyClass();
  // but specificities of MyClass are not visible
  // MyClass myObject = new StandardClass(); not possible
Polymorphism is referring to an object as if it is of a parent class. Objects have several forms.
StandardClass anArray[] = new StandardClass[10];
anArray[0] = new MyClass();
anArray[1] = new StandardClass();
A heterogenous collection contains objects with common ancestor. If the collection is of type java.lang.Object, then the collection can contain any type of object.
MyClass myObject = new MyClass();
   --> (myObject instanceof MyClass) is true
   --> (myObject instanceof StandardClass) is also true
   --> ( (Object)whateverObject instanceof MyClass) is false

Subclassing

Note cast "(Object)whateverObject"

aStandardObject = myObject;

Casting "up" is possible by simple assignment

if (anObject instanceof MyClass) myObject = (MyClass)anObject;

Casting "down" is allowed by compiler if the new cast is a subclass
A run-time error occurs if the runtime type is not the subclass.

// myObject = (MyClass)objectOfMySecondClass;

Casting "across" is not possible

finalize {
  ...
  super.finalize();
}
Override the finalize of the object class for any cleaup if necessary (usually not necessary). Call super.finalize as the last statement.
import java.util.Enumeration;

Enumeration TheEnumMembers = AservletContext.getAttributeNames();
while (TheEnumMembers.hasMoreElements()) {
  String OneEnumMember = TheEnumMembers.nextElement().toString();
  System.out.println(OneEnumMember);
}
Simple display of all members of an enumeration. This may be out of date and remplaced by enum type (see above).

 

Class description includes:

N.B.

 


AWT

import java.awt.*; Preceding each object's name with "java.awt." is not necessary.
Button b; b = new Button("OK");  
Frame f; f = new Frame("Example");
f.setLayout(new FlowLayout() );
f.add (b); // add the button defined above
f.pack; // without pack, size is zero
f.setSize (200, 300); // instead of pack
f.setVisible(true);
BorderLayout by default.
f.add("South", b); With Border (default) layout manager, use one of the five regions North, East, Center, West, South.Only one component per region.
new BorderLayout() // default, 5 areas (N, S, E, W, center)
new FlowLayout()  
new GridLayout ( 3, 2) // 3 rows, 2 columns
new GridBagLayout (?)
new CardLayout (?)
new BoxLayout (?)
 
Panel p = new Panel(); f.add(p); p.add(...); A panel has a layout manager and components
public class ButtonHandler
   implements java.awt.event.ActionListener,
              java.awt.event....Listener
         // Interface name
{
  ....
    b.addActionListener(new ButtonHandler());
  ....
  public void actionPerformed(java.awt.event.ActionEvent e) {
    // Handler method
    ....
  }
}

Handler method must be exactly as shown. The class must be an implementation of ActionListener. It can also extend ActionListener.

Category is "Action"
Interface name is "ActionListener"
Method is "actionPerformed(ActionEvent)"

aLabel.setText("..."); Label
new Checkbox("label", false); // label and default value See item category for events
CheckboxGroup radio = new CheckboxGroup();
Checkbox a = new Checkbox ("a", radio, false);
 
Choice c = new Choice(); See item category for events
Canvas c  
.requestFocus method forces focus on canvas, label, ...  
TextArea t = new TextArea ("...", r, c); // rows and columns t.setEditable(boolean)
Note that size may be ignored by layout manager.
Sub-class of TextComponent
TextField f = new TextField("...", len); See action category for events (triggered by pressing enter)
Use setEditable method to make read-only.
Note that size may be ignored by layout manager.
Sub-class of TextComponent
List l = new List ( h, true); h is preferred height in rows (may be overridden by layout manager)
Allows multiple selections.
Dialog d = new Dialog(f, "...", false);
d.setVisible(true);
d.add("Center", new Label("..."); d.pack();
Separate dialog window
Listen to windowClosing so as to hide the window.
FileDialog d = new FileDialog ( f, "FileDialog");
d.setVisible(true);
String fname = d.getFile();
 
ScrollPane sp = new ScrollPane();
sp.add(aPanel); aFrame.add(sp);
 
MenuBar theMenuBar = new MenuBar(); // horizontal menu
aFrame.setMenuBar(theMenuBar);
Menu theMenuFile = new Menu("File");
Menu theMenuHelp = new Menu("Help");
theMenuBar.add(theMenuFile) ;
theMenuBar.add(theMenuHelp) ;
theMenuBar.setHelpMenu(theMenuHelp) ;

MenuItem theMenuItemSave new MenuItem("Save");
MenuItem theMenuItemQuit new MenuItem("Quit");
theMenuFile.add (theMenuItemSave);
theMenuFile.addSeparator;
theMenuFile.add (theMenuItemQuit);

Use action category for the events on the menu items. Action events on menus are possible but unusual.

Can only add a menubar to a frame

CheckboxMenuItem aCheckboxMenuItem = new CheckboxMenuItem ("..");
aMenu.add (aCheckboxMenuItem);
Use the ItemListener interface.
PopupMenu aPopupMenu = new PopupMenu("Popup");
aPopupMenu.add(aMenuItem);
anyComponent.add(aPopupMenu);
aPopupMenu.show ( anyComponent, x, y);
      // method to display the popup
Show generally inside an event
setForeground( new Color(r,g,b) )
setBackground( new Color(r,g,b) )
See java.awt.Color class
setFont("TimesRoman", Font.PLAIN, 14) See java.awt.Font class
Dialog, Helvetica, TimesRoman, Courier
Font.BOLD, Font.ITALIC, Font.PLAIN,
Font.BOLD+Font.ITALIC

Events

Handler method: public void methodNameSeeBelow (java.awt.event.WindowEvent e) { }

Category Interface Handler method

 

Action ActionListener actionPerformed(ActionEvent e) e.getActionCommand() returns label by default.
Change with e.setActionCommand()
Item ItemListener itemStateChanged(ItemEvent e) e.getStateChange() returns ItemEvent.DESELECTED or ItemEvent.SELECTED
e.getItem()
returns label  
Mouse Motion MouseMotionListener mouseDragged(MouseEvent e)
mouseMoved(MouseEvent e)
e.getX() e.getY() returns position
Mouse Button MouseListener mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mouseClicked(MouseEvent e)
 
Key KeyListener keyPressed(keyEvent e)
keyReleased(keyEvent e)
keyTyped(keyEvent e)
e.getKeyChar() returns the character
Focus FocusListener focusGained(Event e)
focusLost(Event e)
 
Adjustment AdjustmentListener adjustmentValueChanged
    (AdjustmentEvent e)
 
Component ComponentListener componentMoved(ComponentEvent e)
componentHidden(ComponentEvent e)
componentResized(ComponentEvent e)
componentShown(ComponentEvent e)
 
Window WindowListener windowClosing(WindowEvent e)
windowOpened(WindowEvent e)
windowIconified(WindowEvent e)
windowDeiconified(WindowEvent e)
windowClosed(WindowEvent e)
windowActivated(WindowEvent e)
windowDeactivated(WindowEvent e)
 
Container ContainerListener componentAdded(ContainerEvent e)
componentRemoved(ContainerEvent e)
 
Text TextListener textValueChanged(TextEvent e)  

Overwrite the event handler and return true so that the event is not propagated to the parent component.

Methods

g.drawString("...", x, y)

x and y are baseline
paint(Graphics g)

Draw the display. Called to handle exposure. Eventually, use the clip rectangle.

Exposure causes paint() to be called;
repaint() causes update() to be called, which should call paint()

repaint() Ask the AWT to change the display by calling update
update (Graphics g) Normally clears the display and calls the method paint
g.drawImage ( anImage, x, y, image-observer) The image observer is the class with the paint method.

 

 

Class hierarchy:
java.lang.object
  java.awt.Component
    java.awt.Button
    ....
    java.awt.TextArea
    java.awt.Container
      java.awt.Frame
      java.awt.Panel
        java.applet.Applet

 

 


Swing

JavaTM Foundation Classes (JFC). Do not mix with AWT. Needs Java2.

Visual index to the Swing Components on Sun's site

   
import javax.swing.*;

public class HelloWorldSwing {
   public static void main(String[] args) {
   JFrame frame = new JFrame("HelloWorldSwing");
   final JLabel label = new JLabel("Hello World");
   frame.getContentPane().add(label);

   // Close window when requested:
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   frame.pack();
   frame.setVisible(true);
   }
}

Minimal example v.1.3

Swing components often use AWT :
import java.awt.*;
import java.awt.event.*;

JFrame
Single main window
JDialog
Secondary windows
JApplet
Applet display area
frame.addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent e) {
     System.exit(0);
   }
});
Listener to use in version prior to 1.3
try {
   UIManager.setLookAndFeel( class-name );
} catch (Exception e) {}
Define look and feel
UIManager.getCrossPlatformLookAndFeelClassName()
JButton button = new JButton("...");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {....}
});

Button

This is an anonymous event handler

JLabel label = new JLabel("...");
label.setLabelFor(button);
Label
pane.setBorder(BorderFactory.createEmptyBorder( t, l, b, r ); Border (top, left, bottom, right)
JTextField f = new JTextField(5);
f.setText("...");
getText()--> string
Text box of width 5
String can be "<html>...</html>"
ImageIcon anIcon = new ImageIcon("xyz.gif", "label");
aButton = new JButton(anIcon);
Add an image to a button

Note on threads: once a swing component has been realized (constructed and made visible), then all code should be in the event-dispatching thread. There are exceptions, like the methods repaint and revalidate (these methods do not paint but queue a request to paint).

Use the methods invokeLater (request code to be executed in event-dispatching thread) and invokeAndWait (waits for code to execute).

 


java.io

Have a look at this http://www.cafeaulait.org/books/javaio/ioexamples/

import java.io.*;

Two types of streams:
Character (char type / 16 bits) streams: Reader and Writer abstract classes
Byte streams (int type / 8 bits), descendants of InputStream and OutputStream
int read() --> returns one by, -1 for EOF
int read(byte[]) --> returns number of bytes, data in array
int read(byte[], int, int) --> same, but within a sub-range
int available() --> number of bytes available to read
skip (long n) --> discard n characters
markSupported()
mark(int)
reset()
Input Streams
write(int) --> write byte
write(byte[]) --> write array
write(byte[], int, int) --> write sub-range
flush() // force output (committal)
Output Streams
void close() Should close after use
InputStreamReader inputReader;
inputReader = new InputStreamReader (System.in [, "8859_1"] );
BufferedReader in; new BufferedReader (input_Reader);
while ( (s=in.readLine()) != null) { ... }
Basic reading from the standard input channel. Some other encoding options are US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16

File aFile = new File ( ["path/",] "abcd");
File aDir = new File ("dir"); File aFile = new File ( aDir, "abcd");

String getName()
String getPath()
String getAbsolutePath()
String getParent()
boolean exists()
boolean canWrite()
boolean canRead()
boolean isFile()
boolean isDirectory()
boolean isAbsolute()
long lastModified()
long length()
boolean renameTo(File newName)
boolean delete()
createNewfile() //
boolean mkdir()
String[] list() String[] listFiles()  

Class File (or class FileDescriptor)

File streams: FileReader, FileWriter, FileInputStream, FileOutputStream

For random access files, see [1] page 12-16

The file can be a directory too; see listing with listFiles()

File aFile = new File ( ["path/",] "abcd");
try (FileInputStream s = new FileInputStream(aFile)) {
  .. // read file
} catch (IOException e) {
  System.out.println("Cannot read file");
}

try-with-resources statement ensures that the file is closed even in the case of an error

import java.io.*;

public class Copy {
   public static void main(String[] args) throws IOException {
     File inputFile = new File("abc.txt");
     File outputFile = new File("def.txt");
     FileReader/FileInputStream in =
         new FileReader/FileInputStream(inputFile);
     FileWriter/FileOutputStream out =
         new FileWriter/FileOutputStream(outputFile);

     int c;
     while ((c = in.read()) != -1) {
       out.write(c);
     }

     in.close();
     out.close();
}
}
Example

 

 

 

 

 


java.net

import java.net.*;

 
java.net.URL.getDocumentBase() --> URL of current page
java.net.URL.getCodeBase() --> source of the applet code
 
java.net.URL.getImage(URL, filename) --> Image
java.net.URL.getAudioClip(URL, filename) --> AudioClip
 
   

 

Server   Client

import java.net.*;
import java.io.* ;

  import java.net.*;
import java.io.*
;
ServerSocket serverSocket;
try {
  serverSocket = new ServerSocket(5432);
} catch (IOException e) {}
Register with service
Socket socket;
socket = serverSocket.accept();
Socket Socket socket;
socket = new Socket("server", port#);
OutputStream sOut;
DataOutputStream dataOut;
Streams InputStream sIn;
DataInputStream dataIn;
sOut = socket.getOutputStream();
dataOut = new DataOutputStream (sOut);
dataOut.writeUTF("a string");
Output and input stream sIn = socket.getInputStream();
dataIn = new DataInputStream(sIn);
String st = new String (dataIn.readUTF());
dataOut.close();
sOut.close();
Close stream dataIn.close();
sIn.close();
socket.close(); Close socket socket.close();

 

 

 


Other Classes

import java.text.DateFormat;
import java.util.Date;

Date dtCurrent = new Date(); // defaulted to now

System.out.println(DateFormat.getDateInstance().format(dtCurrent));
System.out.println(DateFormat.getTimeInstance().format(dtCurrent));
System.out.println(DateFormat.getDateTimeInstance().format(dtCurrent));
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(dtCurrent));

// Get date format once and use several times:
DateFormat df = DateFormat.getDateInstance([DateFormat.LONG, Locale.FRANCE]);
myDate = df.parse(myString);
Also for time:
DateFormat df = DateFormat.getTimeInstance ([DateFormat.LONG, Locale.FRANCE]);

Formats are SHORT, MEDIUM, LONG, FULL
The method format defines how to display the date. For parsing, see below.
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

String dateString = "Nov 4, 2003 8:14 PM";
DateFormat format = DateFormat.getDateTimeInstance();

try {
Date dtDate = format.parse(dateString);
  System.out.println(dateString + " --> " dtDate.toString());
}
catch(ParseException pe) {
  System.out.println("ERROR: could not parse date in string \"" + dateString + "\"");
}
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

SimpleDateFormat aFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

try {
   Date parsed = aFormat.parse(dateString);
   System.out.println("The parsed date is: " + parsed.toString());
}
catch(ParseException pe) {
   System.out.println("Cannot parse \"" + dateString + "\"");
}
GG = era
yyyy, M, MM, MMM, MMMM, d, dd
h, hh, a (H, HH for 24 hr format), m, mm, s, ss, SSS (millisec)
EEE, EEEE (day in week), D, DDD (day in year), w (week in year), z (timezone)
'...' : literal text

 


JDBC

JDBC home page

 

First step: install the driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Load the driver
String url = "jdbc:odbc:ODBC-data-source-name";
Connection c =
      DriverManager.getConnection(url, "myLogin", "myPassword");
c.close(); // Close when done
Establish the connection
Statement stmt = c.createStatement();
int n = stmt.executeUpdate("DDL statement or update statement" );
stmt.close(); // Close when done
Create update statement
n is number of rows affected
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ..." );
while (rs.next()) {
   String s = rs.getString("col1");
   float n = rs.getFloat("col2");
   System.out.println(s + " " + n);
}
stmt.close(); // Close when done

getString can be used with all data types

getByte, getShort, getInt, getLong
getFloat, getDouble, getBigDecimal
getBoolean, getString, getBytes, getObject
getDate, getTime, getTimeStamp
getAsciiStream, getUnicodeStream, getBinaryStream

PreparedStatement pStmt = c.prepareStatement( "... WHERE A=?;");
pStmt.setInt(n, value); // where n is placeholder
pStmt.executeUpdate(); // no arguments
Prepared statements, precompiled by DBMS
c.setAutoCommit(false);
... c.executeUpdate();
c.commit();
Transactions
Evetually use setTransactionIsolation() method
c.setAutoCommit(false);
try {
  ................
  c.commit();
} catch(SQLException SQLe) {
   System.err.println("SQLException: " + SQLe.getMessage());
   if (c != null) {
     try {
       c.rollback();
     } catch(SQLException excep) {
       System.err.println("SQLException: " + excep.getMessage());
       System.err.println("State: " + excep.getSQLState());
       System.err.println("Err  : " + excep.getErrorCode());
     }
   }
}
Rollback in catch, itself with another try/catch
CallableStatement cs = c.prepareCall("{call PROC_NAME}");
ResultSet rs = cs.execute();
Stored procedures using a callable statement. Use parameters are for prepared statements.
SQLWarning warning = stmt.getWarnings();
// also use with resultSet object: rs.getWarnings()
if (warning != null) {
   while (warning != null) {
     System.out.println(warning.getMessage());
     System.out.println(warning.getSQLState());
     System.out.print("warning.getErrorCode());

     warning = warning.getNextWarning();
   }
}
SQLWarning is a sub-class of SQLException

 

Working minimal example. It uses the default ODBC driver (windows). A data source "PRDT" should be defined.It assumes that a user SCOTT exists.

import java.sql.*;

public class testJdbc {
   public static void main (String[] args) throws SQLException {

   try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   } catch(java.lang.ClassNotFoundException e) {
     System.out.println("Class not found: " + e.getMessage());
   }

   String url = "jdbc:odbc:PRDT";
   Connection c = DriverManager.getConnection(url, "scott", "tiger");

   Statement stmt = c.createStatement();
   ResultSet rs = stmt.executeQuery ("SELECT DISTINCT OWNER FROM ALL_OBJECTS");
   while ( rs.next() ) {
     System.out.println( rs.getString(1) );
   }
   System.out.println ("Done");
   }
}

 

 


JDK Tools

javac
-classpath --> gives location of classes
-d directory --> put classes in directory
-g --> enable debugging
-verbose --> more output
filename.java

Compile
Must have .java extension.

java [options] class_name args

java
-debug
-cs, -checksource -->
check the timestamp of .java and compiles if necessary
-classpath path --> tell where classes are
-v, -verbose -->

Classes must be in files called class_name.class.
javadoc
[options]
package | filename.java
Creates packages.html, tree.html, AllNames.html and classname.html
appletviewer [-debug] urls url must be an html document with <applet> tag
jdb [options] Debugger

 

 


Miscellaneous

System.out.println ("....");  
... = Integer.parseInt ( string expr ); Convert a literal string to integer
Math.random() Random from 0 to 1
Math.sqrt(number) Square root
Packages: lower.case
Class, interface: NounsWithInitialUpperCase
Methods: verbsWithMixedCaseExceptFirstLetter
Variables: withMixedCaseExceptFirstLetter (like methods)
Constants: ALL_UPPER_CASE
Conventions
... main ( String[] args) {
System.out.println ( args[0] );}
Command line arguments:
args[0] is first argument

<APPLET CODE=x.class >
<PARAM NAME="p1" VALUE="FirstParameter">
<PARAM NAME="p2" VALUE="SecondParameter">
</APPLET>

public void init() {
  aString = getParameter ( "p1" );
  anotherString = getParameter ( "p2" );
}

Passing parameters with an applet

Null if empty.

Not case sensitive.

Generally one public class per .java file. Generally should contain in the following order:

// comments or whitespaces only
package what.ever; // package definition
// imports
// class and interface definitions
public class Aclass

The class in the above file will be put in ${CLASSPATH}/what/ever/Aclass.class
The -d option of javac should refer to the same directory as CLASSPATH

Encoding

The URLEncoder.encode() function works only for Java default encoding.

String unreserved = new String("/\\- _.!~*'()
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789");
StringBuffer out = new StringBuffer(url.length());
for (int i = 0; i < url.length(); i++)
{
  int c = (int) url.charAt(i);
   if (unreserved.indexOf(c) != -1) {
     if (c == ' ') c = '+';
     out.append((char)c);
     continue;
   }
   byte [] ba;
   try {
     ba = url.substring(i, i+1).getBytes("UTF8");
   } catch (UnsupportedEncodingException e) {
     ba = url.getBytes();
   }
   for (int j=0; j < ba.length; j++)
   {
     out.append("%" + Long.toHexString((long)(ba[j]&0xff)).toUpperCase());
   }
}
String encodedUrl = out.toString();

(source Oracle)

Use executable in the bin directory:
native2ascii -encoding UTF-8 file1 > file2
Then run:
sed 's/[[:cntrl:]]//g' file2 > file3

 

Sources: