This is an old revision of the document!


Java Introduction

These are my notes for the Java programming language. I'm a professional programmer but I'm new to Java. I'm jotting down the fundamentals here as I learn them.

Hello World

An initial Java application looks like the following.

public class Application {

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

}

Compile to Bytecode

Java code starts as plain text files and then is compiled to bytecode. If the code above is in a file called Application.java then the following command compiles that.

javac Application.java

That creates an Application.class file. You can then run the application (Application.class) using:

java Application

Using Libraries

You can download and use libraries as .jar files. In this example I'll load the SQLite-jdbc library. You'll find it on Bitbucket at the URL below.

https://bitbucket.org/xerial/sqlite-jdbc/downloads

Download the latest version and place it in the same directory as your application.

Import the file into your application with the following line. This line will differ depending on the library you're loading. See the libraries documentation for the exact line to use. For the SQLite-jdbc library, in the Hello World example above, this will be the first line in the Application.java file.

  import java.sql.*;

After importing the file you will compile your application again.

  javac Application.java

Then you need to execute your application with the library specified in the -classpath (or -cp) argument. The way you do this differs slightly between Unix like OS's and Windows. Here's how you do it on Unix like OS's.

  java -classpath ".:sqlite-jdbc-(VERSION).jar" Application

Here's the Windows variation.

  java -classpath ".;sqlite-jdbc-(VERSION).jar" Application

Make sure you replace (VERSION) with the actual version of the sqlite-jdbc library you downloaded into the current working directory.

I believe the colon (:) and semi-colon (;) are separators while the dot (.) indicates the current directory.

Here's a full example of our Application.java file loading in the SQLite-jdbc library and using it.

import java.sql.*;

public class Application {

	public static void main(String[] args) {
	
	    Connection c = null;
	    try {
	      Class.forName("org.sqlite.JDBC");
	      c = DriverManager.getConnection("jdbc:sqlite:hello.db");
	    } catch ( Exception e ) {
	      System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	      System.exit(0);
	    }
	    System.out.println("Opened database (hello.db) successfully");
	
	}

}
comments powered by Disqus
java_introduction.1433858633.txt.gz · Last modified: 2020/06/01 22:53 (external edit)