Software Engineering

Java Introduction

This guide is intended to function as a basic Java reference for students who are familiar with Python or C++. There are a number of more complete guides on the Internet; here are a few:

The documentation for the Java standard library API can be found at https://docs.oracle.com/javase/8/docs/api/. Make sure to use this reference!

Java shares features with both Python and C++. Here is a breakdown of a few of the more prominent features:

PythonC++Java
Syntax
Blocks Indentation-based Explicit via braces Explicit via braces
Statement Termination Newline Semicolon Semicolon
Type Annotations None Required Required
Semantics
Variable Declaration Implicit Explicit Explicit
Memory Management Garbage-collected Manual (new and delete) Garbage-collected
Allocation Always dynamic (via reference) Either static (e.g. on stack) or dynamic (via pointer) Static for primitives (e.g. int) and dynamic for objects
Environment
Compilation None required To native machine code To JVM bytecode
Typical Execution Interpreted Natively executed Interpreted or JIT-compiled

This guide provides a collection of mostly-matching examples in all three languages to give some impression of the parallels. They are divided into the following sections:

Expressions, Statements, and Basic Syntax

DescriptionPythonC++Java

Variable declaration and assignment

x = 4;
int x = 4;
int x = 4;

Conditionals

if x > 4:
  x -= 1
if (x > 4) {
  x -= 1;
}
if (x > 4) {
  x -= 1;
}

While Loops

while x > 4:
  x -= 1
while (x > 4) {
  x -= 1;
}
while (x > 4) {
  x -= 1;
}

For Loops

N/A

for (int i=0;i<10;i++) {
  acc += i;
}
for (int i=0;i<10;i++) {
  acc += i;
}

For-Each Loops

for item in lst:
  acc += item
for (int item : lst) {
  acc += item;
}
for (int item : lst) {
  acc += item;
}

Function Calls

z = f(x,y)
int z = f(x,y);
int z = f(x,y);

Comments

# End-of-line comment
// End-of-line comment
/* Block comment */
// End-of-line comment
/* Block comment */

Auto-documentation Comments

def f():
  """
  Auto-doc comment in Python
  """
  ...

A variety of auto-doc formats exist for C++, but Doxygen is commonplace:

/**
 * Auto-doc comment in Doxygen for C++.
 */
int f() { ... }
/**
 * Auto-doc comment in Javadocs for Java.
 */
int f() { ... }

Allocating dynamic arrays

Python does not have arrays.

int* array = new int[4];
for (int i=0;i<4;i++) {
  array[i] = i;
}
int[] array = new int[]{0,1,2,3};

Dynamically allocating an object

obj = SomeClass()
SomeClass* obj = new SomeClass();
SomeClass obj = new SomeClass();

Deallocating a dynamically allocated object

N/A

delete obj;

N/A

Standard Libraries

DescriptionPythonC++Java

Dynamically allocating a string object

s = "hello"
string* s = new string("hello");
String s = "hello";

Comparing two strings

s = "hello"
t = "hel" + "lo"
print(s == t) # prints "True"
string* s = new string("hello");
string* t = new string(string("hel") + string("lo"));
cout << (*s == *t) << endl; // prints 1
cout << (s == t) << endl; // BAD: prints 0!
String s = "hello";
String t = "hel" + "lo";
System.out.println(s.equals(t)); // prints true
System.out.println(s == t); // BAD: prints false!

Dynamically allocating and initializing a canonical list

lst = [1,2,3]
vector<int>* lst = new vector<int>();
lst->push_back(1);
lst->push_back(2);
lst->push_back(3);
List<Integer> lst = new ArrayList<>();
lst.add(1);
lst.add(2);
lst.add(3);

Dynamically allocating and initializing a canonical dictionary

m = {1:"one",2:"two"}
unordered_map<int,string>* m =
  new unordered_map<int,string>();
m->at(1) = "one";
m->at(2) = "two";
Map<Integer,String> m = new HashMap<>();
m.put(1,"one");
m.put(2,"two");

Declarations

DescriptionPythonC++Java

Functions

def f(x):
  return x + 1
int f(int x) {
  return x + 1;
}

Java has no concept of top-level functions. However, classes may be given static methods.

public class Utilities {
  public static int f(int x) {
    return x + 1;
  }
}

Classes

class Point(object):
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def distance_from_origin(self):
    return math.sqrt(
      self.x ** 2 +
      self.y ** 2)
class Point {
public:
  Point(double x, double y);
  double distance_from_origin();
private:
  double x;
  double y;
};

Point::Point(double x, double y) {
 this->x = x;
 this->y = y;
}

double Point::distance_from_origin() {
  return sqrt(
    this->x * this->x +
    this->y * this->y);
}
public class Point {
  private double x;
  private double y;
  public Point(double x, double y) {
    this.x = x;
    this.y = y;
  }
  public double distanceFromOrigin() {
    return Math.sqrt(
      this.x * this.x +
      this.y * this.y);
  }
}

Interfaces

Python has no formal interfaces, though abstract base classes are sometimes used:

class Readable(object):
  def read(self):
    raise NotImplementedError
  def is_exhausted(self):
    raise NotImplementedError
class Readable {
public:
  virtual string read() = 0;
  virtual bool is_exhausted() = 0;
}
public interface Readable {
  public String read();
  public boolean isExhausted();
}

Inheritance

class Subclass(Superclass):
  ...
class Subclass : public Superclass {
  ...
}
class Subclass extends Superclass {
  ...
}

or

class MyClass implements SomeInterface {
  ...
}

Parametric Polymorphism

N/A – Python does not provide any compile-time typechecking, so type parameters would have no meaning.

template <typename T, typename U>
class Pair {
public:
  Pair(T, U);
  T getFirst();
  U getSecond();
private:
  T first;
  U second;
};

template <typename T, typename U>
Pair<T,U>::Pair(T first, U second) {
  this->first = first;
  this->second = second;
}

template <typename T, typename U>
T Pair<T,U>::getFirst() {
  return this->first;
}

template <typename T, typename U>
U Pair<T,U>::getSecond() {
  return this->second;
}
public class Pair<T,U> {
  private T first;
  private U second;

  public Pair(T first, U second) {
    this.first = first;
    this.second = second;
  }

  public T getFirst() {
    return this.first;
  }

  public U getSecond() {
    return this.second;
  }
}

Common I/O Operations

DescriptionPythonC++Java

Printing a string

print("Message")
cout << "Message" << endl;
System.out.println("Message");

Printing a formatted message

print("There are %d lights" % 4)

or

print("There are {} lights".format(4))
cout << "There are " << 4 << " lights" << endl;
System.out.printf("There are %d lights\n");

Opening a file

file = open("filename.txt")
ifstream file("filename.txt");
Scanner file = new Scanner(new FileInputStream("filename.txt"));

Closing a file

file.close();
file.close();
file.close();

Reading a line from a file

line = file.readline();
string line;
getline(file, line);
String line = file.nextLine(); // where file is a Scanner

In order to read lines from standard input, Java programs often use BufferedReader around the InputStream known as System.in. For instance, consider the following program:

public class Example {
  public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    System.out.print("Hello!  What is your name? ");
    String name = userInput.nextLine();
    System.out.printf("Hello, %s!\n", name);
  }
}

Sorting

DescriptionPythonC++Java

Sorting a list

lst.sort()
std::sort(vec.begin(), vec.end());
Collections.sort(lst);

Sorting a list via a custom comparison

def odd_first_then_even(x,y):
  x_even = x%2 == 0
  y_even = y%2 == 0
  if x_even and not y_even:
    return 1
  elif y_even and not x_even:
    return -1
  elif x<y:
    return -1
  elif x>y:
    return 1
  else:
    return 0
lst.sort(cmp=odd_first_then_even)
bool odd_first_then_even(int x, int y) {
  bool x_even = x%2 == 0;
  bool y_even = y%2 == 0;
  if (x_even && !y_even) {
      return 1;
  } else if (!x_even && y_even) {
      return -1;
  } else if (x<y) {
      return -1;
  } else if (x>y) {
      return 1;
  } else {
      return 0;
  }
}
...
std::sort(vec.begin(), vec.end(), odd_first_then_even);
class OddFirstThenEven implements Comparator<Integer> {
  public int compare(Integer a, Integer b) {
    int x = a;
    int y = b;
    boolean xEven = x%2 == 0;
    boolean yEven = y%2 == 0;
    if (xEven && !yEven) {
      return 1;
    } else if (!xEven && yEven) {
      return -1;
    } else if (x<y) {
      return -1;
    } else if (x>y) {
      return 1;
    } else {
      return 0;
    }
  }
};
Collections.sort(lst, new OddFirstThenEven());