Java: Difference between revisions

From 太極
Jump to navigation Jump to search
 
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Install openjdk =
= Installation =
See http://openjdk.java.net/install/. On Ubuntu, I can use
 
== OpenJDK ==
* See http://openjdk.java.net/install/.
* [https://www.cyberciti.biz/faq/install-java-on-ubuntu-20-04-linux/ How to Install Java on Ubuntu 20.04 LTS Linux]
* [https://www.linuxuprising.com/2019/03/how-to-install-oracle-java-12-jdk-12-in.html How To Install Oracle Java 12 (JDK 12) In Ubuntu, Linux Mint Or Debian (Using PPA)]
 
On my Ubuntu 12.04, I have two versions.
{{Pre}}
$ 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
</pre>
 
Question: [http://askubuntu.com/questions/64329/how-to-replace-openjdk-6-with-openjdk-7 how to switch to 1.6 or 1.7 version of java?] (For example, snpEff requires java 1.7)
{{Pre}}
$ 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"
</pre>
 
Question: [http://askubuntu.com/questions/464755/how-to-install-openjdk-8-on-14-04-lts How to install OpenJDK 8 on 14.04 LTS?] (for example, [https://github.com/broadinstitute/picard Picard 2] requires Java 1.8)
{{Pre}}
$ 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
</pre>
So the solution is to install Sun jdk.
 
== Oracle JAVA ==
* http://askubuntu.com/questions/521145/how-to-install-oracle-java-on-ubuntu-14-04
* Install Java silently
** https://javaguru.fi/unattended-java-install-ubuntu-14-04.html
** http://askubuntu.com/questions/190582/installing-java-automatically-with-silent-option
 
{{Pre}}
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
</pre>
 
== Multiple versions ==
If we have multiple versions of JRE/JDK, we can use the [https://www.digitalocean.com/community/tutorials/how-to-install-java-on-ubuntu-with-apt-get following command] to set the default version
<pre>
<pre>
sudo apt-get install openjdk-7-jdk
sudo update-alternatives --config java
</pre>
</pre>
This approach seems to be working in the case JAVA_HOME cannot be honored.
[https://itsfoss.com/set-java-home-ubuntu/ How to Set JAVA_HOME Variable in Ubuntu Linux Correctly]


= Some projects written in Java =
= Some projects written in Java =
Line 16: Line 84:
* [http://www.ntu.edu.sg/home/ehchua/programming/java/J9c_PackageClasspath.html Package, classpath]
* [http://www.ntu.edu.sg/home/ehchua/programming/java/J9c_PackageClasspath.html Package, classpath]
* [http://www.codecademy.com/ codecademy]
* [http://www.codecademy.com/ codecademy]
* [https://web.stanford.edu/class/archive/cs/cs106a/cs106a.1178/textbooks.html CS106a textbook] Eric Roberts, Stanford University.


= Compile a simple Java program =
= Compile a simple Java program =
Line 55: Line 124:
3.0822070014844885
3.0822070014844885
</pre>
</pre>
= [https://netbeans.org/kb/index.html NetBeans] =
== Packaging and Deploying Desktop Java Applications ==
https://netbeans.org/kb/articles/javase-deploy.html


= Set the Java version for a project =
= Set the Java version for a project =
Line 64: Line 137:


= Java Programming =
= Java Programming =
== Cheat sheet ==
http://introcs.cs.princeton.edu/java/11cheatsheet/
== Main method ==
== Main method ==
Main method has to be declared within a class declaration.
Main method has to be declared within a class declaration.
Line 199: Line 276:
One line
One line
<pre>
<pre>
className variableName = new ClassName(argumentList);
ClassName variableName = new ClassName(argumentList);
</pre>
</pre>


Line 223: Line 300:


== Inheritances ==
== 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.
<pre>
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";
  }
}
</pre>


== Interfaces ==
== 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'''.


<pre>
// 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);
  }
}
</pre>
To use the print method of the Product class
<pre>
// product is both a Product object and a Printable object.
Printable product = new Product("java");
product.print();
</pre>
Interfaces are similar to abstract classes.
For example, a Printable interface is written as
<pre>
public interface Printable
{
  public abstract void print();
}
</pre>
and a Printable abstract class looks like
<pre>
public abstract class Printable
{
  public abstract void print();
}
</pre>
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.
<pre>
public interface ProductReader {}
public interface ProductWriter {}
public interface ProductConstants {}
public interface ProductDAO extends ProductReader, ProductWriter, ProductConstants {}
</pre>
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.
<pre>
src -- taichi -- package1
                    class11Name.java
                    class12Name.java
              -- package2
                    class2Name.java         
</pre>
Then in class11Name.java
<pre>
package taichi.package1;
public class class11Name {...}
</pre>
and in class2Name.java
<pre>
package taichi.package2;
import taichi.package1.*;
public class class2Name {...}
</pre>
== 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 ==
== Array ==


== Collection, generics ==
== Collection, generics ==

Latest revision as of 10:23, 27 November 2021

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