Skip to content

Latest commit

 

History

History
173 lines (129 loc) · 3.44 KB

java.md

File metadata and controls

173 lines (129 loc) · 3.44 KB

Java

Java provides a mature, widely used programming language and runtime.

In terms of quality engineering, many tools are written in Java and/or designed to support it.

Install

This book’s Vagrantfile should have installed Java for you, but in case that didn’t work download and install the Java Development Kit (JDK) from Sun

Verify installation by checking the version of the Java compiler:

$ javac -version
javac 1.7.0_75

Build and run

Using Vim, create a file called Main.java:

$ vim Main.java

All Java applications have a main method Java calls to kick off the program. Copy/paste the code below into your Main.java:

class Main {
  public static void main(String[] args) {
    System.out.println("Hi");
  }
}

Compile using the java compiler:

$ javac Main.java

View the resulting Main.class:

$ ls
Main.java Main.class

Run it:

$ java Main
Hi

Repeat these steps to play with the Java syntax below.

Variables

Variables let us assign a value to a name:

int number = 0;

Operators

Operators enable us to perform actions on variables:

number = 1; // assignment
System.out.println(number);
number = i + 1; // addition
System.out.println(number);

Loops

Loops enable us to iterate over a collection of values:

String[] values = {"a", "b", "c"};
for (int i = 0; i < values.length; i++) {
  System.out.println(values[i]);
}

Conditions

Conditions allow us to require something to be true:

for (int i = 0; i < 10; i++) {
  if (i % 2 == 0) {
    System.out.println("even");
  } else {
    System.out.println("odd");
  }
}

Functions

Function allow us to name a set of commands:

static int addOne(int i) {
  return i + 1;
}
…
System.out.println(addOne(1));

Classes

Classes enable us to encapsulate common functionality:

class Number {
  int i;
  Number(int i) {
    this.i = i;
  }
  void add(int i) {
    this.i += 1;
  }
  boolean isEven() {
    if (i % 2 == 0) {
      return true;
    } else {
      return false;
    }
  }
}
…
class Hi {
    public static void main(String[] args) {
      Number n = new Number(1);
      System.out.println(n.isEven();
      System.out.println(n.add(1));
      System.out.println(n.isEven());
…

Imports

Imports let us include encapsulated code:

import java.util.ArrayListclass Main {
    public static void main(String[] args) {
      ArrayList<String> emails = new ArrayList<String>();
      emails.add("[email protected]");
      System.out.println(emails.toString());

Exercise

Write a program that accepts two numeric arguments and uses the Number class to determine if the sum of the numbers is even:

$ java Main 1 3
true
$ java Main 10 5
false

Learn more