Java
First steps
Java Installation
- JRE
- JDK
- java
- javac
There are several implementation of Java, one currently controlled by Oracle and it can be downloaded from Oracle.com but as far as I know there are various problematic licensing restrictions. A better choice is to download the Open JDK.
On MS Windows install it by unipping the .zip file and then configuring the PATH to include the bin/ directory.
Before we even write a line of code we would like to make sure that both the java compiler and the java runtime is accessible for us. So we open a command line window or a Power Shell window and we type in javac --version and java --version respectively.
On MS Windows
> javac --version
javac 14.0.2
> java --version
openjdk 14.0.2 2020-07-14
OpenJDK Runtime Environment (build 14.0.2+12-46)
OpenJDK 64-Bit Server VM (build 14.0.2+12-46, mixed mode, sharing)
Java Installation on Ubuntu Linux
sudo apt install openjdk-24-jdk-headless
$ javac -version
javac 24-ea
$ java --version
openjdk 24-ea 2025-03-18
OpenJDK Runtime Environment (build 24-ea+16-Ubuntu-1)
OpenJDK 64-Bit Server VM (build 24-ea+16-Ubuntu-1, mixed mode, sharing)
An older version
$ javac -version
javac 1.8.0_252
$ java -version
openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252-8u252-b09-1ubuntu1-b09)
OpenJDK 64-Bit Server VM (build 25.252-b09, mixed mode)
Java from Oracle
- Download Java from Oracle
- JRE - Java Runtime Environment (Java Virtual Machine JVM)
- JDK - Java Development Kit (Java Compiler javac)
$ java -version
java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)
$ javac -version
javac 1.8.0_60
Hello World in Java
- System.out.println
- System
- println
Printing Hello World on the screen is a bit more complex in Java than in many of the so-called scripting languages, but still it is probably the most simple thing you can do in the language. So let's see it.
Create a file with a name like HelloWorld.java . The extension .java is important , so is the name. In the file we create a class with the same name as the name of the file.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
$ javac HelloWorld.java # Compiles the file and creates HelloWorld.class
$ java HelloWorld
Hello World
Java Data Types
- String
- int
- double
- boolean
- true
- false
Primitive types such as int, float, boolean, etc. Or reference types, such as strings, arrays, or objects.
42 - int
1_234 - int
true, false - boolean
"string" - string in double quotes
'x' - char in single quotes
'x' == "x" - execption as cannot compare char with string.
"abc".getClass() works and prints class java.lang.String, but does not work on any of the other data types
public class CheckDataTypes {
public static void main(String[] args) {
// https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
System.out.println("Checking Data Types");
String h = "Hello";
String w = "World";
System.out.println(h); // Hello
System.out.println(w); // World
String full = h + " " + w;
System.out.println(full); // Hello World
// int is 32 bit sigend between -2^31 and 2^31-1
int val1 = 19;
int val2 = 23;
int val3 = val1 + val2;
System.out.println(val3); // 42
// double 64-bit IEEE 754 floating point.
double db1 = 19.3;
double db2 = 22.7;
double db3 = db1 + db2;
System.out.println(db3); // 42.0
boolean b = true;
System.out.println(b); // true
b = ! b;
System.out.println(b); // false
if (!b) {
System.out.println("yeah");
System.out.println("works");
}
// Actually if there is only a single statement in the block you don't even need the curly braces, but I would recommend this practice:
if (!b)
System.out.println("this too");
// because of this:
if (b)
System.out.println("in condition");
System.out.println("NOT in condition"); // this is not inside the condition even though the indentation seems to suggest that.
}
}
javac CheckDataTypes.java
java CheckDataTypes
Checking Data Types
Hello
World
Hello World
42
42.0
true
false
yeah
works
this too
NOT in condition
Java Variable declaration
- int
- boolean
- char
With and without initialization.
public class Variables {
public static void main(String[] args) {
int aNumber;
boolean aBoolean;
char aCharacter;
int otherNumber = 12;
boolean otherBoolean = true;
char otherCharacter = 'x';
System.out.println(otherNumber);
System.out.println(otherBoolean);
System.out.println(otherCharacter);
}
}
javac Variables.java
java Variables
12
true
x
Java comments
-
//
-
/*
-
// single-line comment
-
/* multi-line comment */
Java prompt - read from STDIN
- InputStreamReader
- BufferedReader
- readLine
import java.io.*;
class Prompt{
public static void main(String[] args) throws IOException{
System.out.print("Your name: ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String name = in.readLine();
System.out.println("Your name is: " + name);
}
}
javac Prompt.java
java Prompt
Convert string to number
- Integer
- parseInt
public class Convert {
public static void main(String[] args) {
String number_str = "23";
int a_number = 19;
System.out.println(number_str); // 23
System.out.println(number_str + a_number); // 2319
int real_number = Integer.parseInt(number_str);
System.out.println(real_number + a_number); // 42
}
}
javac Convert.java
java Conver
Add Command line values
- args
- length
public class AddCmdLineArgs{
public static void main(String[] args){
if (args.length != 2) {
System.out.println("Must have exactly 2 values on the command line");
System.exit(1);
}
System.out.println("First: " + args[0]);
System.out.println("Second: " + args[1]);
System.out.println(args[0] + args[1]);
}
}
javac AddCmdLineArgs.java
java AddCmdLineArgs Foo Bar
Add Command line integers
- args
- Integer
- parseInt
public class AddCmdLineNumbers{
public static void main(String[] args){
if (args.length != 2) {
System.out.println("Must have exactly 2 values on the command line");
System.exit(1);
}
System.out.println("First: " + args[0]);
System.out.println("Second: " + args[1]);
System.out.println(Integer.parseInt(args[0]) + Integer.parseInt(args[1]));
}
}
javac AddCmdLineNumbers.java
java AddCmdLineNumbers 19 23
Java for-loop
- for
- ++
public class ForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
$ javac ForLoop.java $ java ForLoop
Java while-loop
- while
public class WhileLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
}
}
Java command line arguments
public class CmdLineArgs{
public static void main(String[] args){
System.out.println("The following command line arguments were passed:");
for (int i=0; i < args.length; i++){
System.out.println("arg[" + i + "]: " + args[i]);
}
}
}
javac CmdLineArgs.java
java CmdLineArgs --name "Foo Bar" --email foo@bar.com
Concatenate strings in Java
-
-
Use the + operator
public class ConcatStrings {
public static void main(String[] args) {
String h = "Hello";
String w = "World";
String full = h + " " + w;
System.out.println(full); // Hello World
}
}
$ javac ConcatStrings.java
$ java ConcatStrings
Use class
class Greeting {
public static void hello() {
System.out.println("Hello World");
}
}
public class GreetingsA {
public static void main(String[] args) {
System.out.println("Hello");
Greeting.hello();
}
}
javac GreetingsA.java
java GreetingsA
Hello
Hello World
Method signature
class Greeting {
public static void hello() {
System.out.println("Hello World");
}
public static void hello(String message) {
System.out.println("Hello World " + message);
}
}
public class GreetingsB {
public static void main(String[] args) {
System.out.println("Hello");
Greeting.hello();
Greeting.hello("Brave New World");
}
}
javac GreetingsB.java
java GreetingsB
Hello
Hello World
Hello World Brave New World
Use Java class from another class
public class Calculator {
public static Integer add(Integer a, Integer b) {
if (a == 10) {
return 10;
}
return a+b;
}
}
public class UseCalc {
public static void main(String[] args) {
Number a = Calculator.add(2, 3);
System.out.println(a);
Number b = Calculator.add(10, 3);
System.out.println(b);
}
}
cd examples/mymath
rm -f *.class; javac Calculator.java UseCalc.java ; java UseCalc
Calc
public class Calc {
public static void main(String[] args) {
Number c = add(2, 3);
System.out.println(c);
}
public static Integer add(Integer a, Integer b) {
/* System.out.println(a);
System.out.println(b); */
return a+b;
}
}
Cat
import java.io.*;
/**
This class demonstrates how to read a line of text from the keyboard
Based on http://www.abbeyworkshop.com/howto/java/readLine/ReadLine.java
*/
public class Cat{
public static void main(String[] args){
try {
String CurLine = ""; // Line read from standard in
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
CurLine = in.readLine();
while (CurLine != null){
System.out.println(CurLine);
CurLine = in.readLine();
}
}catch (IOException e){
System.out.println("IO Exception\n");
}
}
}
Grep
import java.io.*;
import java.util.regex.*;
/**
This class demonstrates how to read a line of text from the keyboard
Based on http://www.abbeyworkshop.com/howto/java/readLine/ReadLine.java
*/
public class Grep{
public static void main(String[] args){
try {
Pattern pattern = Pattern.compile(args[0]);
String line = "";
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
line = in.readLine();
while (line != null){
Matcher matcher = pattern.matcher(line);
if(matcher.find()) {
System.out.println(line);
}
line = in.readLine();
}
}catch (IOException e){
System.out.println("IO Exception\n");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("Usage: java Grep REGEX (and then type strings on STDIN, Ctr-D to exit)\n");
}
}
}
Read file
import java.io.*;
/**
Source: http://www.abbeyworkshop.com/howto/java/readFile/ReadFile.java
*/
public class ReadFile{
public static void main(String[] args){
try {
/* Sets up a file reader to read the file passed on the command
line one character at a time */
FileReader input = new FileReader(args[0]);
/* Filter FileReader through a Buffered read to read a line at a
time */
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line number of count
// Read first line
line = bufRead.readLine();
count++;
// Read through file one line at time. Print line # and line
while (line != null){
System.out.println(count+": "+line);
line = bufRead.readLine();
count++;
}
bufRead.close();
}catch (ArrayIndexOutOfBoundsException e){
/* If no file was passed on the command line, this expception is
generated. A message indicating how to the class should be
called is displayed */
System.out.println("Usage: java ReadFile filename\n");
}catch (IOException e){
// If another exception is generated, print a stack trace
e.printStackTrace();
}
}// end main
}
Read line
import java.io.*;
class ReadLine{
public static void main(String[] args) throws IOException{
String CurLine = ""; // Line read from standard in
System.out.println("Enter a line of text (type 'quit' to exit): ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
}
}
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadLines {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Must have exactly 1 value on the command line");
System.exit(1);
}
String filename = args[0];
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(filename));
String line;
while ((line = inputStream.readLine()) != null) {
System.out.println(line);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
}
- Character stream
- read bytestream
- reads characters byte-by-byte
Regex
import java.io.*;
import java.util.regex.*;
public class Regex{
public static void main(String[] args){
{
String line = "STRING";
Pattern pattern = Pattern.compile("S.R");
Matcher matcher = pattern.matcher(line);
if(matcher.find()) {
System.out.println(line);
System.out.println("Found '" + matcher.group() +
"' starting at index " + matcher.start() +
" and ending at index " + matcher.end() + ".");
}else{
System.out.println("*** NO MATCH ***");
}
}
}
}
Regex Test harness
import java.io.*;
import java.util.regex.*;
/*
* Source: http://java.sun.com/docs/books/tutorial/extra/regex/example-1dot4/RegexTestHarness.java
*/
public final class RegexTestHarness {
private static String REGEX;
private static String INPUT;
private static BufferedReader br;
private static Pattern pattern;
private static Matcher matcher;
private static boolean found;
public static void main(String[] argv) {
initResources();
processTest();
closeResources();
}
private static void initResources() {
try {
br = new BufferedReader(new FileReader("regex.txt"));
}
catch (FileNotFoundException fnfe) {
System.out.println("Cannot locate input file! "+fnfe.getMessage());
System.exit(0);
}
try {
REGEX = br.readLine();
INPUT = br.readLine();
} catch (IOException ioe) {}
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);
System.out.println("Current REGEX is: "+REGEX);
System.out.println("Current INPUT is: "+INPUT);
}
private static void processTest() {
while(matcher.find()) {
System.out.println("I found the text \"" + matcher.group() +
"\" starting at index " + matcher.start() +
" and ending at index " + matcher.end() + ".");
found = true;
}
if(!found){
System.out.println("No match found.");
}
}
private static void closeResources() {
try{
br.close();
}catch(IOException ioe){}
}
}
Split a string
- StringTokenizer
import java.util.*;
/**
* This class demonstrates how to use the StringTokenizer class to split apart
* strings of text.
* Source: http://www.abbeyworkshop.com/howto/java/splitString/SplitString.java
*/
class SplitString {
public static void main(String[] arguments) {
StringTokenizer ex1, ex2; // Declare StringTokenizer Objects
int count = 0;
String strOne = "one two three four five";
ex1 = new StringTokenizer(strOne); //Split on Space (default)
while (ex1.hasMoreTokens()) {
count++;
System.out.println("Token " + count + " is [" + ex1.nextToken() + "]");
}
count = 0; // Reset counter
String strTwo = "item one,item two,item three,item four"; // Comma Separated
ex2 = new StringTokenizer(strTwo, ","); //Split on comma
while (ex2.hasMoreTokens()) {
count++;
System.out.println("Token " + count + " is [" + ex2.nextToken() + "]");
}
}
}
Java: Run external program
- InputStream
- Runtime
- getRuntime
- exec
//import java.io.BufferedReader;
import java.io.InputStream;
import java.io.IOException;
class Runls {
public static void main(String[] args) {
try
{
// Command to create an external process
String command = "ls";
InputStream iStream = null;
// Running the above command
Runtime run = Runtime.getRuntime();
Process proc = run.exec(command);
iStream = proc.getInputStream();
int line;
while ((line = iStream.read()) != -1) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Method Overloading
class MethodOverloading {
public static void main(String[] args) {
System.out.println("main");
MethodOverloading.hello();
MethodOverloading.hello("Brave New World");
MethodOverloading.hello(42);
}
public static void hello() {
System.out.println("hello");
}
public static void hello(String message) {
System.out.println("hello with message: " + message);
}
public static void hello(int answer) {
System.out.println("the answer is: " + answer);
}
}
$ javac MethodOverloading.java
$ java MethodOverloading
main
hello
hello with message: Brave New World
the answer is: 42
Public instance attributes
public class TryPoint {
public static void main(String[] args) {
Point a = new Point(2, 3);
System.out.println(a);
System.out.println(a.x);
a.x = 7;
System.out.println(a.x);
//System.out.println(a.getX);
}
}
public class Point {
public int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Getter for private instance attributes
public class TryPoint {
public static void main(String[] args) {
Point a = new Point(7, 3);
System.out.println(a.getX());
}
}
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
}
Setter for private instance attributes
public class TryPoint {
public static void main(String[] args) {
Point a = new Point(7, 3);
System.out.println(a.getX());
a.setX(23);
System.out.println(a.getX());
}
}
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public void setX(int x) {
this.x = x;
}
}
Compile and Run in shell
{% embed include file="src/examples/java/run.sh)
Static or Class attribute
public class Bike {
private static int count = 0;
public static int getCount() {
return Bike.count;
}
public Bike() {
Bike.count++;
}
public void finalize() {
Bike.count--;
System.out.println("Finalize");
}
}
public class RunBike {
public static void bike_shop() {
System.out.println(Bike.getCount());
Bike a = new Bike();
System.out.println(Bike.getCount());
Bike b = new Bike();
System.out.println(Bike.getCount());
Bike c = new Bike();
System.out.println(Bike.getCount());
b = null;
//System.gc();
System.out.println(Bike.getCount());
}
public static void main(String[] args) {
bike_shop();
System.out.println(Bike.getCount());
}
}
// The finalize methods is supposed to be similar to a destructor, but it might be never called in the life of the program. So we cannot rely on it.
inheritance
public class Person {
public String name;
public Person(String full_name) {
name = full_name;
}
}
public class Worker extends Person {
public int id;
public Worker(String full_name, int id_number) {
super(full_name);
id = id_number;
}
}
public class TryClass {
public static void main(String[] args) {
System.out.println("Hello");
Person p1 = new Person("Joe");
System.out.println(p1); // Person@2a139a55
System.out.println(p1.name); // Joe
Person p2 = new Person("Jane");
System.out.println(p2); // Person@15db9742
System.out.println(p2.name); // Jane
p1.name = "Joseph";
System.out.println(p1.name); // Joseph
System.out.println(p2.name); // Jane
// System.out.println(p2.id); // will not compile
Worker w1 = new Worker("Zorg", 23);
System.out.println(w1.name); // Zorg
System.out.println(w1.id); // 23
}
}
Combination
public class Point {
private int x;
private int y;
public Point(int a, int b) {
x = a;
y = b;
}
public String showCoord() {
return "(" + x + ", " + y + ")";
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public int getx() {
return x;
}
public int gety() {
return y;
}
}
import java.lang.Math;
public class Line {
private Point a;
private Point b;
public Line(Point aa, Point bb) {
a = aa;
b = bb;
}
public String showLine() {
return a.showCoord() + "___" + b.showCoord();
}
public double length() {
return Math.pow(Math.pow(a.getx()-b.getx(), 2) + Math.pow(a.gety()-b.gety(), 2), 0.5);
}
}
public class RunCode {
public static void main(String[] args) {
System.out.println("Hello");
Point p1 = new Point(2, 3);
System.out.println(p1);
// System.out.println(p1.x); // x has private access in Point
System.out.println(p1.showCoord());
p1.move(3, 7);
System.out.println(p1.showCoord());
Point p2 = new Point(2, 6);
System.out.println(p2.showCoord());
Line line = new Line(p1, p2);
System.out.println(line.showLine());
System.out.println(line.length());
}
}
Other
Other examples
public class PrintAdd {
public static void main(String[] args) {
int a = 3;
int b = 5;
System.out.println("The sum: " + (a+b));
}
}
public class Characters {
public static void main(String[] args) {
char t = '0';
char x = (char) 97;
System.out.println(t);
System.out.println(x);
}
}
Regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MyRegex {
public static void main(String[] args) {
String[] emails = {"abc@corporate.com", "demo-id12@corporate.com", "demo-id12@other.com"};
Pattern pattern = Pattern.compile("demo-id[0-9]+@corporate\\.com$");
for (int i=0; i < emails.length; i++) {
System.out.println(emails[i]);
Matcher matcher = pattern.matcher(emails[i]);
if (matcher.find()) {
System.out.println("OK");
}
}
}
}
Split
public class MySimpleSplit {
public static void main(String[] args) {
String planetNames = "Mercury,Venus,Earth,Mars";
System.out.println(planetNames);
System.out.println(planetNames.length());
String[] planets = planetNames.split(",");
System.out.println(planets[0]);
System.out.println(planets.length);
System.out.println("");
for (int i=0; i < planets.length; i++) {
System.out.println(planets[i]);
}
}
}
Substring
public class MySubstring {
public static void main(String[] args) {
String text = "The black cat climbed the greeen tree.";
System.out.println(text);
int textLength = text.length();
System.out.println(textLength);
// substring(from)
String tail = text.substring(textLength-5);
System.out.println(tail);
// substring(from, to)
String word = text.substring(textLength-5, textLength-1);
System.out.println(word);
}
}
Mixing types in add
+
is overloaded in Java so if one side is a string and the other is an integer, the integer will be automatically converted to a string and then+
will be concatenation.
public class MixedAdd {
public static void main(String[] args) {
String a = "19";
String b = "23";
int c = 23;
double d = 2.3;
float f = 2.3f;
System.out.println("The sum: " + (a+b));
System.out.println("The sum: " + (a+c));
System.out.println("The sum: " + (a+d));
System.out.println("The sum: " + (a+f));
System.out.println("The sum: " + (f+a));
String line = "-";
// MixedAdd.java:16: error: bad operand types for binary operator '*'
// System.out.println(line * 23);
System.out.println(line.repeat(23));
}
}