Java

From 太極
Revision as of 11:23, 27 November 2021 by Brb (talk | contribs) (→‎Install openjdk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Installation

OpenJDK

On my Ubuntu 12.04, I have two versions.

$ whereis java
java: /usr/bin/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz
$ java -version
java version "1.6.0_38"

$ sudo apt-get -y install openjdk-7-jdk
$ ls -l /usr/lib/jvm
total 12
lrwxrwxrwx 1 root root   20 Nov 16  2013 java-1.6.0-openjdk-amd64 -> java-6-openjdk-amd64
lrwxrwxrwx 1 root root   20 Mar 24 06:20 java-1.7.0-openjdk-amd64 -> java-7-openjdk-amd64
drwxr-xr-x 7 root root 4096 Feb 20 08:43 java-6-openjdk-amd64
drwxr-xr-x 3 root root 4096 Jan 31  2014 java-6-openjdk-common
drwxr-xr-x 7 root root 4096 Mar 30 18:16 java-7-openjdk-amd64

$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 Jan 31  2014 /usr/bin/java -> /etc/alternatives/java

Question: how to switch to 1.6 or 1.7 version of java? (For example, snpEff requires java 1.7)

$ update-java-alternatives -l
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-1.7.0-openjdk-amd64 1051 /usr/lib/jvm/java-1.7.0-openjdk-amd64
$ sudo apt-get install icedtea-7-plugin
$ sudo update-java-alternatives -s java-1.7.0-openjdk-amd64
update-java-alternatives: plugin alternative does not exist: /usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/IcedTeaPlugin.so
$ update-java-alternatives -l
java-1.6.0-openjdk-amd64 1061 /usr/lib/jvm/java-1.6.0-openjdk-amd64
java-1.7.0-openjdk-amd64 1051 /usr/lib/jvm/java-1.7.0-openjdk-amd64
$ java -version
java version "1.7.0_95"

Question: How to install OpenJDK 8 on 14.04 LTS? (for example, Picard 2 requires Java 1.8)

$ sudo apt-get -y install openjdk-8-jdk   # works for Ubuntu 14.10 and later
# Unable to locate package openjdk-8-jdk on my Ubuntu 14.04

So the solution is to install Sun jdk.

Oracle JAVA

sudo apt-add-repository -y ppa:webupd8team/java
sudo apt-get update
echo debconf shared/accepted-oracle-license-v1-1 select true |  sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true |   sudo debconf-set-selections
sudo apt-get install oracle-java8-installer

java -version

Multiple versions

If we have multiple versions of JRE/JDK, we can use the following command to set the default version

sudo update-alternatives --config java

This approach seems to be working in the case JAVA_HOME cannot be honored.

How to Set JAVA_HOME Variable in Ubuntu Linux Correctly

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

NetBeans

Packaging and Deploying Desktop Java Applications

https://netbeans.org/kb/articles/javase-deploy.html

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

Cheat sheet

http://introcs.cs.princeton.edu/java/11cheatsheet/

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

Access modifier protected means variables are available to classes in the same package and to subclasses.

Below is an example of creating a subclass.

public class Book extends Product
{
  private String author;

  public Book()
  {
    super(); // call constructor of Product superclass
  }

  @Override
  public String toString() // override the toString method
  {
    return super.toString() +  // call method of Product superclass
       "Author: " + author + "\n";
  }
}

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.

Inheritance with interfaces

When an interface inherits other interfaces, any class that implements that interface must implement all of the methods declared by that interface and the inherited interfaces.

public interface ProductReader {}
public interface ProductWriter {}
public interface ProductConstants {}
public interface ProductDAO extends ProductReader, ProductWriter, ProductConstants {}

DAO stands for "Data Access Object".

packages

When we work with packages, we need to make sure that the name of the package corresponds with the name of the directory for the package.

src -- taichi -- package1
                     class11Name.java
                     class12Name.java
              -- package2
                     class2Name.java          

Then in class11Name.java

package taichi.package1;
public class class11Name {...}

and in class2Name.java

package taichi.package2;
import taichi.package1.*;
public class class2Name {...}

Libraries

If we want to make the packages of an application available to other applications, you can store them in a library.

After you create the project, you compile it to create a Java Archive (JAR) file that contains the packages and classes for the library. The jar file is stored in the dist subdirectory of the project's root directory, and it has the same name as the project.

To run a jar file, issue java -jar XXXX.jar.

Array

Collection, generics

Dates, strings

Text and binary files

Swing

Hello World Example

For example, create a new subdirectory 'start' and put HelloWorldSwing.java there. Then we can build and run the swing program by

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