Home CPSC 330

More Java

Packages & Imports

Java groups classes together inside of packages. When we imported the Scanner class, we did so with:

import java.util.Scanner;

The Scanner class is inside of the package "java.util". We could have avoided the import statement by using the full class name:


public class Input {
  public static void main(String args[]) {
    // create a Scanner object
    java.util.Scanner in = new java.util.Scanner(System.in);
    
    // prompt for input
    System.out.println("Enter your name: ");

    // read in a string
    String name = in.next();

    // Skip the newline
    in.nextLine();

    // prompt for input
    System.out.println("Enter your age: ");
    
    // read in an int
    int age = in.nextInt();

    // greet
    System.out.printf("Hello %s, you are %d years old!\n", name, age);
  }
}

Packages are like namespaces, and the import statement is like a "using" statement from C++.

Packages exist to avoid the names of classes colliding with one another.

An import can also import all classes in a package with the wildcard * character:


import java.util.*;

Creating a Package

To create a package, include a package statement at the top of your program:


package testpackage;

public class Package {
  public static void main(String args[]) {
    System.out.println("A Java package!");
  }
}

This puts the "Package" class into the "testpackage" package.

This Java program has to be not only in a file called "Package.java", it must be in a directory called "testpackage".

To compile and run this program:


> javac testpackage/Package.java
> java testpackage.Package

Sub-Packages

Packages can also be broken into sub-packages such as the "java.util" package.

When this is done, there must be a directory for each portion of the package. The code for the Scanner class, would have to be in a "java/util/" directory.

In order to ensure name collisions are impossible, Java convention says that you should use the domain name of your organization (in reverse) as the beginning of the package name.


Public and Non-Public Classes

Each Java source file can only declare one public class - which must have the same name as the file. However, a Java file can also have other non-public classes in it. For example, this program has two classes in one file.


// a circle class
class Circle {
  // constructor
  public Circle(double r) {
    radius = r;
  }

  // return the area of the circle
  public double getArea() {
    return Math.PI * radius * radius;
  }

  // return the circumferenece of the circle
  public double getCircumference() {
    return 2 * Math.PI * radius;
  }

  // private member data
  private double radius;
}

public class CircleProgram {
  public static void main(String args[]) {
    // make a circle and print the area
    Circle c = new Circle(10.0);
    System.out.printf("Circle has circumference %f and area %f.\n",
      c.getCircumference(), c.getArea());

  }
}

A class that is not declared public, such as "Circle" is only visible inside of its package.

A public and non-public class have different intents:


Programs with Multiple Files

Using multiple files in Java is easier than in C++.

This example splits the Circle program above into two files.

To compile this example:


javac circle_example/*.java
java circle_example.CircleMain

Java Naming Conventions


ArrayLists

Java arrays, like the arrays of C++, are fixed size when they are created and cannot grow and shrink.

ArrayList objects are commonly used in Java for storing data that can expand and shrink. ArrayLists are in the java.util package.

They are generic and can store elements of any object type. This is similar to templates in C++:


ArrayList<String> names = new ArrayList<String>();

Unlike arrays, ArrayList objects support adding and removing elements.

ArrayLists cannot hold primitive types, only objects.


For Loops

Java supports the same style of for loops as C++, but it also supports another kind for looping through elements of arrays, ArrayLists, or other data structures.

The form of this for loop is:


for(<element-type> <identifier> : <array>) {
  // use identifier in some way
}

For example, this program loops through an ArrayList using this kind of loop:


import java.util.*;

public class Foreach {
  public static void main(String args[]) {
    ArrayList<String> names = new ArrayList<String>();

    // add some names
    names.add("Alice");
    names.add("Bob");
    names.add("Claire");
    names.add("Donald");

    // loop through them
    for(String name : names) {
      System.out.println(name);
    }
  }
}


This type of loop is often called a "Foreach" loop.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.