Java

From 太極
Jump to navigation Jump to search

Install openjdk

See http://openjdk.java.net/install/. On Ubuntu, I can use

sudo apt-get install openjdk-7-jdk

Some projects written in Java

  • FastQC The code uses Java 2D graphics APIs in awt like BasicStroke, Color, Dimension, Graphics, Graphics2D, RenderingHints and javax.swing.JPanel. It also uses java.util.Vector.

Tutorial/Books

Compile a simple Java program

javac HelloWorldApp.java # generate Example.class; bytecode version of the program
java HelloWorldApp   # run bytecode in Java Virtual Machine

Get a hello world program from http://docs.oracle.com/javase/tutorial/getStarted/cupojava/unix.html.

Note that the file name can not be arbitrary. It should match with the class name. For the above example, if we rename <HelloWorldApp.java> to <example.java>, we will get an error when we run java example on the command line.

Another example that requires command line argument.

// Sqrt.java
public class Sqrt { 
    public static void main(String[] args) { 

        // read in the command-line argument
        double c = Double.parseDouble(args[0]);
        double epsilon = 1e-15;    // relative error tolerance
        double t = c;              // estimate of the square root of c

        // repeatedly apply Newton update step until desired precision is achieved
        while (Math.abs(t - c/t) > epsilon*t) {
            t = (c/t + t) / 2.0;
        }

        // print out the estimate of the square root of c
        System.out.println(t);
    }

}

$ javac Sqrt.java
$ java Sqrt 9
3.0
$ java Sqrt 9.5
3.0822070014844885

Set the Java version for a project

To change the Java version for a project if a newer version becomes available: right click on a project, then select properties

  • Libraries - Java Platform - change the version from the drop-down list. I only see JDK 1.7.

If you want to use the new features of that version and you don't need the project to run under earlier versions of Java.

  • Sources - Source/Binary format - change the version from the drop-down list. I can see a lot of choices.

Java Programming

Main method

Main method has to be declared within a class declaration.

public class InvoiceApp
{
  public static void main(String[] args)
  {
    System.out.println("Welcome to my app");
  }
}

Create objects of numerical variables, string, from a class

Eight primitive data types: byte ([-128,127]), short ([-32,768, 32,767]), int ([-2^31, 2^31-1]), long ([-2^63, 2^63-1]), float ([-3.4E38, 3.4E38]), double ([-1.7E308, 1.7E308]), char (2 bytes), boolean (1 byte).

int scoreCounter = 1;
double unitPrice = 15.9;
String firstName = "Joe";
String lastName = "Wang";
String name = firstName = " " + lastName;
Scanner sc = new Scanner(System.in);
double subtotal = sc.nextDouble(); // get a double entry from the console
Date now = new Date();
String currentDate = now.toString(); // convert the date to a string

Common packages

  • java.lang
  • java.text
  • java.util
  • java.io
  • java.sql
  • java.applet
  • java.awt
  • java.awt.event
  • javax.swing

Two ways to create an object from the Scanner class.

With an import statement

import java.util.Scanner;
Scanner sc = new Scanner(System.in);

Without an import statement

java.util.Scanner sc = new java.util.Scanner(System.in);

Console for input/output

Use the System.out object to print output to the console (println() is a method). Here, System.out refers to an instance of the PrintStream class. Because this object is created automatically by Java, you don't have to include code that creates it in your program.

System.out.println("Total: " + total);

Use the Scanner class to read input from the console

import java.util.Scanner
String name = sc.next();
int count = sc.nextInt();
double subtotal = sc.nextDouble();
String cityName = sc.nextLine();

Control statement

== , != 

equals(String) // Don't use string1 == string2;
equalsIgnoreCase(String)

if () { } else {}

while () { }

switch (switchExpression)
{ 
  case label1:
     statements;
     break;
  case label2:
     statements;
     break;
  default:
     statements;
     break;
}

Java classes useful for working with data

  • java.text.NumberFomat
  • java.lang.Math
  • java.math.BigDecimal
  • java.math.RoudingMode

Validate input

import.java.util.InputMismatchException;
import.java.util.*;

try { statements }
catch (ExceptionClass exceptionName) { statements }

Define and use classes

public class Product {
  // instance variables
  private String code;

  // constructor 
  public Product() {}

  // methods
  public void setCode(String code) {}
  public String getCode() {}

  // overload a method
  public void printToConsole(String sep) {}
  public void printToConsole() {}
  public void printToConsole(String sep, boolean printLine) {}
}

Two ways to create an object of a class.

Two lines

className variableName;
variableName = new ClassName(argumentList);

One line

ClassName variableName = new ClassName(argumentList);

static method

See p218 of Murach's Java Programming. In Chapter 4, static method can be used as the main method in the same class.

In this chapter, we learn to code static fields and methods in a separate class.

public class Product
{
  private static int objectCount = 0;
  public Product() {}
  public static int getObjectCount() {} // get the static variable  
}

To call static methods

int productCount = Product.getObjectCount();

When to use static fields and methods: when you need to create objects from a class, you should use regular fields and methods. In contrast, if you just need to perform a single task like a calculation, you can use a static method. Then, you send the method the arguments it needs, and it returns the result that you need without ever creating an object. See also stackoverflow.

Inheritances

Interfaces

In C++, a class can inherit more than one class. This is know as multiple inheritance. Although Java does not support multiple inheritance, it support a special type of coding element known as an interface.

// define an interface using the interface keyword
public interface Printable
{
  public abstract void print();
}
// a Product class that implements the Printable interface
public class Product implements Printable
{
  private String code;

  public Product(String code)
  {
    this.code = code;
  }

  public void print()
  {
     System.out.println("Code: " + code);
  }
}

To use the print method of the Product class

// product is both a Product object and a Printable object.
Printable product = new Product("java");
product.print();

Interfaces are similar to abstract classes.

For example, a Printable interface is written as

public interface Printable
{
  public abstract void print();
}

and a Printable abstract class looks like

public abstract class Printable
{
  public abstract void print();
}
Each of abstract class and interface has its own advantages.

== Array ==


== Collection, generics ==


== Dates, strings ==


== Text and binary files ==

= Swing =
== Hello World Example ==
* http://docs.oracle.com/javase/tutorial/uiswing/start/compile.html

For example, create a new subdirectory 'start' and put HelloWorldSwing.java there. Then we can build and run the swing program by
<pre>
javac start/HelloWorldSwing.java # Or javac HelloWorldSwing.java if we are in start directory
java start.HelloWorldSwing

Quit Button Example

Note that it is necessary to create the directory com/zetcode according to package statement in java code. Also the filename must be consistent with the class name.

mkdir com
mkdir com/zetcode
nano com/zetcode/QuitButtonExample.java
javac com/zetcode/QuitButtonExample.java
java com/zetcode/QuitButtonExample