Java J2SE

By Sandeep Desai (http://www.thedesai.net/)

 

See SCJP notes for Java Basics Source listings

 

Features

·           Syntax Similar to C++

·           Complies to platform independent byte code, so it can be run on any platform that has the Java Runtime Environment

·           Execute using bytecode interpreter

·           Garbage Collection

·           Java Byte Code available on most platforms

·           Provides API to do GUI, Web, XML, SQL Database Development and more

·           Is a platform more than a language

·           One public Class per file (can have many inner classes)

 

Books

·           Thinking in Java (www.bruceeckel.com)

·            

 

Websites

 

Major API’s

·           Swing for doing GUI

·           RMI (Invoke Remote Java Objects over Network)

·           JDBC for working with Relational Databases (JDBC driver for each database vendor

·           Servlets, Java Server Pages for Web development for writing Web Applications

·           SAX and JDOM for XML Parsing

 

Java Development Kit

·           Standard Edition (Java Compiler, Byte Code Interpreter Basic classes and Swing, RMI)

·           Enterprise Edition (JDBC, Enterprise Java Beans, XML, SOAP etc) Requires an Server (container) for most APIs

·           Micro Edition

·           JavaDoc provides Help on API

·           IDE’s provided, JDeveloper by Oracle, JBuilder by Borland, Eclipse Open source (www.eclipse.org)

 

Using JDK

·           Download JDK from http://java.sun.com

·           Install JDK

·           Compile using javac e.g. javac Hello.java (creates Hello.class)

·           Run java Hello

·           If API is not part of JDK then requires setting CLASSPATH environment variable which points to Java Archive containing classes e.g to use the Servlet API requires that the Servlet API be downloaded e.g download servlet.jar and set CLASSPATH=c:\servlet.jar;c:\myjar.jar

 

 

 

Language Features

·           OOP

·           Single inheritance

·           All objects inherit from java.lang.Object

·           Multiple inheritance for interfaces

·           Structured Exception Handling

·           Data types are consistent across all platforms

·           32-bit

·           Applet (run in a sandbox (secure mode) in a browser)

§          Can sign the applet to allow creating files etc on browser machine

·           New 1.4 Features

§          Assertions

§          Logging API

·           New 1.5 Features

§          Generics (similar to C++ templates)

§          enhanced for loop (Iterators)

§          autoboxing support

§          enumerations

 

Java Standard Edition API

 

 

Examples

 

// Hello.java

public class Hello {

   public static void main(String[] args) {

       System.out.println(“Hello World!”);

    }

}

 

// To compile

<JAVA_HOME>/bin/javac Hello.java

// To run

<JAVA_HOME>/bin/java –cp . Hello

 

Use the –cp option for java or set the CLASSPATH to all the jar files and directories you want java to look in to find all your code. Put a ‘.’ to ensure java looks in current directory

set classpath=.;servlet.jar;c:\foo

 

javac

Compile java program

java

Run Java Program

javaw

Run Java program with launching a DOS window

javadoc

Generate HTML JavaDoc from source code

 

 

jar

Create Java Archive Files (like a tar file or zip file containing many Java classes)

jdb

Command line Java Debugger

 

 

Java Primitive Data types

Primitive type

Size

Minimum

Maximum

Wrapper

Boolean

 

 

 

Boolean

char

16-bit

Unicode 0

Unicode 2^16-1

Character

byte

8-bit

-128

+127

Byte

short

16-bit

-215

+215+1

Short

int

32-bit

-231

+231-1

Integer

long

64-bit

-263

+263-1

Long

float

32-bit

IEEE754

IEEE754

Float

double

64-bit

IEEE754

IEEE754

Double

void

 

 

 

void

 

 

Operator precendence

Mnemonic

Operator Type

Operators

Ulcer

Unary

+ - ++ --

Addicts

Arithmetic and Shift

* / % + - << >>

Really

Relational

> < <= >= == !=

Like

Logical and bitwise

&& || & | ^

C

Conditional (ternary)

a > b ? c : d

A lot

Assignment

= += *= %= /=

 

Wrapper conversion

primitive xxxValue() to convert Wraper to primitive

primitive parseXxx(String) to convert String to a primitive

Wrapper valueOf(String) to convert a String to Wrapper

Method

s=static

n=NFE Exception

Boolean

Byte

Characater

Double

Float

Integer

Long

Short

byteValue

 

x

 

x

x

x

x

x

doubleValue

 

x

 

x

x

x

x

x

floatValue

 

x

 

x

x

x

x

x

intValue

 

x

 

x

x

x

x

x

longValue

 

x

 

x

x

x

x

x

shortValue

 

x

 

x

x

x

x

x

 

 

 

 

 

 

 

 

 

parseXxx s,n

 

x

 

x

x

x

x

x

parseXxx s,n

(with radix)

 

x

 

 

 

x

x

x

 

 

 

 

 

 

 

 

 

valueOf s,n

x

x

 

x

x

x

x

x

valueOf s,n

(with radix)

 

x

 

 

 

x

x

x

 

 

 

 

 

 

 

 

 

toString

x

x

x

x

x

x

x

x

toString s

(primitive)

x

x

x

x

x

x

x

x

toString s

(primitive, radix)

 

 

 

 

 

x

x

 

 

 

 

 

 

 

 

 

 

toBinaryString s

 

 

 

 

 

x

x

 

toHexString s

 

 

 

 

 

x

x

 

toOctalString s

 

 

 

 

 

x

x

 

 

 

Core Java

 

File

Description

AssertApp.java

// 1.4 feature

public class AssertApp {

   public static void main(String[] args) {

     boolean s = false;

     assert s : “s failed”;

   }

}

 

javac –source 1.4 AssertApp.java

java –ea:AssertApp –cp . AssertApp

AppProperties.java

//work with Properties which can be loaded from file e.g Test.properties

//Property1=value1

//Property2=value2

 

import java.util.Properties;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.PrintStream;

 

public class AppProperties {

    public  Properties m_properties;

    private String m_propFileName;

    public AppProperties(String propFileName) {

       m_propFileName = propFileName;

       m_properties = new Properties();

    }

    public void loadProperties() throws Exception  {

       try {

         FileInputStream propInputStream =

            new FileInputStream(m_propFileName);

         m_properties.load(propInputStream);

         propInputStream.close();

       }

       catch (Exception e) {

         throw e;

       }

    }

    public void saveProperties() throws Exception {

       try {

         FileOutputStream propOutputStream =

             new FileOutputStream(m_propFileName);

         m_properties.save(propOutputStream , "");

         propOutputStream.close();

       }

       catch (Exception e) {

         throw e;

       }

    }

    public void list(PrintStream p) { m_properties.list(p); }

    public String getProperty(String propertyName) { return m_properties.getProperty(propertyName); }

    public void setProperty( String propertyName, String propertyValue) {

       m_properties.put(propertyName, propertyValue);

    }

 }

Areflect.java

uses the Reflection API that allows you to dynamically load classes and browse the class info such as methods, members and invoke them

ArrayList.java

uses the ArrayList Collection

import java.util.ArrayList;

ArrayList a = new ArrayList();

a.add("hello");

a.add("world");

String[] as = new String[a.size()];

a.toArray(as);

for (int i = 0; i < as.length; ++i)

  System.out.println(as[i]);

Beep.java

java.awt.Frame f = new java.awt.Frame();

f.getToolkit().beep();

Toolkit.getDefaultToolkit().beep();

EAIORServer.java

 

Exec.java

Launches an appliction

try {

  Runtime rt = Runtime.getRuntime();

  String s[] = new String[2];

  s[0] = "c:\\winnt\\notepad.exe";

  s[1] = "c:\\junk\\todo.txt";

  Process p = rt.exec(s);

}

catch (Exception e) {

  System.out.println(e);

}

File.java

 

FileDialog.java

Show AWT Open File Dialog

FileRead.java

Read Text files line by line

GetLocalHost.java

java.net.InetAddress localhost = java.net.InetAddress.getLocalHost();

 

 

 

 

 

 

RMI

define interface and use rmic to generate client stubs and server skeleton

JVM will marshall and umarshall for RMI communication

Run rmiregistry to register server object

Lookup sever object in rmiregistry

each method must declare java.rmi.RemoteException in its throw clause

 

 

Setting Locales

 

    java.util.Locale defaultLocale = Locale.getDefault();

    Locale newLocale = new Locale(“en”, “us”);

    Locale.setDefault(newLocale);

     ... some code...

    Locale.getDefault(defaultLocale);

 

Reading a  japanese file

 

     java.io.FileInputStream fis =

        new FileInputStream(getServletContext().getRealPath("/HelloWorld.ISO-2022-JP"));

        //new FileInputStream(req.getRealPath("/HelloWorld.ISO-2022-JP"));

      InputStreamReader isr = new InputStreamReader(fis, "ISO-2022-JP");

      BufferedReader reader = new BufferedReader(isr);

      String line = null;

      while ((line = reader.readLine()) != null) {

        System.out.println(line);

      } 

 

Converting string to japanese

try {
  ustr = new String(str.getBytes("SJIS"),"8859_1");
  } catch (IOException e){ System.err.println("IO error: str="+str);

 

Java Servlet 2nd Edition by Jason Hunter and William Crawford has good infomation and code for Internationalization in Java

 

Java Thread

 

class PrimeRun implements Runnable {
  long minPrime;
  PrimeRun(long minPrime) { this.minPrime = minPrime; }
 
  public void run() { // compute primes larger than minPrime   }
}

 

//The following code would then create a thread and start it running:

PrimeRun p = new PrimeRun(143);
new Thread(p).start();
 

Apache Regular Expression

 

import org.apache.regexp.RE;

import org.apache.regexp.RECompiler;

 

public class regtest {

  public static void main(String[] args) {

    try {

    String match = args[0];

    String expr = "^S";

    RE r = new RE(expr);

    //RECompiler compiler = new RECompiler();

    //r.setProgram(compiler.compile(expr));

    if (r.match(match))

       System.out.println("match=" + match);

    else System.out.println("no match=" + match);

    }

    catch (Exception e) {

      System.out.println(e);

    }

  }

}

 

Java Webstart (JNLP)

It is installed on a client machine and allows you to download Java Applications over the web and run it locally.  It can be run as a browser plugin or a standalone application. It caches the application and updates the jar files if they change. It is an implementation of the JNLP (Java Network Launch Protocol)

 

Steps to create a certificate

·           keytool –genkey –keystore myKeystore –alias myself

·           keytool –selfcert –alias myself –keystore myKeystore

·           keytools –list –keystore myKeystore

Sign the jar file with the following command

·           jarsigner –keystore myKeystore test.jar myself

 

Create a jnlp file and. Copy the jnlp file and the jar files to a Web server directory.

 

 

<?xml version="1.0" encoding="utf-8"?>

<!-- JNLP File for Analytic Workspace Manager Application -->

<jnlp

  spec="1.0+"

  codebase="http://sbdesai-pc2:7778/"

  href="awm.jnlp">

  <information>

    <title>Analytic Workspace Manager</title>

    <vendor>Oracle Corp.</vendor>

    <homepage href="docs/help.html"/>

    <description>Analytic Workspace Manager</description>

    <description kind="short">AWM 9.2.0.3.1</description>

    <icon href="awm.jpg"/>

    <icon kind="splash" href="awm.gif"/>

    <offline-allowed/>

  </information>

  <security>

      <all-permissions/>

  </security>

  <resources>

    <j2se version="1.4+" initial-heap-size="512m"/>

    <jar href="awm.jar"/>

    <jar href="classes12.jar"/>

  </resources>

  <application-desc main-class="oracle.olap.awm.app.AwmApp"/>

</jnlp>

 

Netx (Network Execute) is an open source implementation of JNLP download from http://jnlp.sourceforge.net/netx

 

java -jar netx-0.5.jar -jnlp http://localhost/awm.jnlp

 

JDBC

 

JDBC 2.0 Compliance requires

Data Source support

Java Transaction API (JTA) and XA connection support, XA is used for distributed transaction support

Connection Pooling

Complete Data type support

 

Oracle has 3 types of JDBC driver, thick driver (requires Oracle Client) thin driver

 

e.g Oracle JDBC Url, note username/password is optional

·           Thin JDBC jdbc:oracle:thin:scott/tiger@localhost:1521:ORCL

·           Thick JDBC jdbc:oracle:oci8:scott/tiger@orcl

·           Java in Database connection jdbc:oracle:kprb

 

// Code to insert a japanese unicode string row into a table

// create table test (col as varchar2(100));

 

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

Connection conn = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl";, "scott", "tiger");

conn.setAutoCommit(true);

String query = "insert into test values (?)";

PreparedStatement pstmt = null;

pstmt = conn.prepareStatement(query);

String jpstr = "\u4eca\u65e5";

String dbstr = toUTF8String(jpstr);

pstmt.setString(1, jpstr);

pstmt.executeUpdate();

conn.close();

 

 

Java and Log4J (Apache API for Logging in Java)

 

Loggers: named entities and have a hierarchy based on names. (name hierarchy is similar to package names)

Appenders: are output destinations can be console, file or user implementable. Multiple appenders can be set for a Logger. Loggers will write to all appenders for the current Logger and to all the appenders set for the ancestors.

Layouts is responsible for formatting the logging request according to the user's wishes

 

Chainsaw Massacre is a GUI viewer for log messages

 

Loggers have level, the logged output is logged for level >= level set by user

Logger printing methods are debug(), info(), warn(), error(), fatal() and log().

 

For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

 

package com.foo;

import org.apache.log4j.Logger;

import org.apache.log4j.BasicConfigurator;

 

public class MyApp {

public static void main(String[] args) {

  // Set up a simple configuration that logs on the console.

  BasicConfigurator.configure();

  Logger  logger = Logger.getLogger("com.foo");

  logger.setLevel(Level.INFO);

  logger.warn("Low fuel level.");

  logger.debug("Starting search for nearest gas station.");

  Logger barlogger = Logger.getLogger("com.foo.Bar");

  barlogger.info("Located nearest gas station.");

  barlogger.debug("Exiting gas station search");

}

}

 

output will be

 

Low fuel level

Located nearest gas station

 

Logger.addAppender(new org.apache.log4j.ConsoleAppender());

 

For example, the PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output something akin to:

 

176 [main] INFO  org.foo.Bar - Located nearest gas station

 

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.

 

// BasicConfigurator replaced with PropertyConfigurator.

PropertyConfigurator.configure(“MYAPP.PROPERTIES”);

 

e.g. MYAPP.PROPERTIES

# Set root logger level to DEBUG and its only appender to A1.

log4j.rootLogger=DEBUG, A1

 

# A1 is set to be a ConsoleAppender.

log4j.appender.A1=org.apache.log4j.ConsoleAppender

 

# A1 uses PatternLayout.

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

 

# Print only messages of level WARN or above in the package com.foo.

log4j.logger.com.foo=WARN

 

Swing

 

Swing provides all the UI Controls for building a Java GUI. It extends AWT, (Abstract Windowing Toolkit) which is the older GUI API

 

import javax.swing.*

 

abstract class JTextComponent base class for Swing text components

setEditable(boolean)

setText(String)

String str = getText();

 

// JTextArea extends JTextComponent  // multiline Text Field

jtf = new JTextArea();

setRows(int rows)

setLineWrap(true);

setWrapStyleWord(true); // wrap on word boundaries

 

 

// JCheckBox extends JtoggleButton extends AbstractButton // Check box

AbstractButton.getModel().isSelected();

 

// JComboBox extends JComponent // text field with drop down list

JComboBox jc = new JComboBox();

jc.addItem(“Item1”);

jc.addItem(“Item2”);

String str = (String) jc.getSelectedItem();

jc.setSelectedItem(“Item2”);

 

DefaultComboBoxModel dc = new DefaultComboBoxModel();

dc.removeAllElements();

dc.addElement(“Hola”);

JComboBox jcm = new JComboBox(dc);

jcm.addActionListener(new ActionListener()

{

  public void actionPerformed(ActionEvent e)

  {

     JComboBox cb = (JComboBox) e.getSource();

     String si = cg.getSelectedItem();

  }

});

 

// JList extends JComponent

DefaultListModel dlm = new DefaultListModel();

dlm.addElement(“test”);

JList jl = new JList(dlm);

 

 

 

JTextField extends JTextComponent  // single line text field

JTextFeld tf = new JTextField();

tf.setBorder(javax.swing.BorderFactory.createLoweredBevelBorder());
String val = tf.getText(); 
tf.getDocument.addDocumentListener(new DocumentListener()
        public void changedUpdate(DocumentEvent e) { }
        public void insertUpdate(DocumentEvent e) {}
        public void removeUpdate(DocumentEvent e) {}
}

 

JLabel label = new Jlabel(“Enter Data”);

label.setLabelFor(tf); // Accessibility

label.setMnemonicChar(‘E’); // Accessibility

label.setOpaque(true);

label.setBackgroundColor(Color.white);

 

JRadioButton rb1 = new JRadioButton(“Option1”);

JRadioButton rb2 = new JRadioButton(“Option2”);

ButtonGroup bg = new ButtonGroup();

bg.add(rb1);

bg.add(rb2);

rb1.getModel().isSelected();

rb1.getModel().setSelected(true);

 

 

JFrame extends java.awt.Frame // top level Window

addWindowFocusListener(new WindowAdapter()) {

  public void windowClosing(WindowEvent e) { System.exit(0); }

  public void windowActivated WindowEvent e)

  public void windowGainedFocus (WindowEvent e)

 

});