Java Chapter 6 - Importing Packages

There are many classes that may be imported into your Java program.  Each class has many methods you can use.  The classes are stored in packages, or JAR files.  Recall that in C++, you import libraries versus packages.

To import a single class (ArrayList) within the util package:

import java.util.ArrayList;

To import all classes within the util package:
import java.util.*;

Below are the core packages included with Java.  This chapter examines a few of them.

Package Description Package Description
java.lang
(imported by default)
basic language functionality and fundamental types java.awt basic hierarchy of packages for native GUI components
java.util data structure classes java.swing hierarchy of packages for platform-independent rich GUI components
java.io file operations java.applet classes for creating an applet
java.math multiprecision arithmatics java.beans Contains classes related to developing beans
java.nio non-blocking i/o java.text Provides classes and interfaces for handling text, dates, numbers
java.net networking operations, sockets, DNS lookups java.rmi Provides the RMI package
java.security key generation, encryption and decryption java.time The main API for dates, times, instants, and durations
java.sql Java Database Connectivity (JDBC) to access databases    


6.1
java.lang.Math
(imported automatically)

Method Parameter(s) Returns
Math.random() - (double) A random number between 0 and 1
(int) (Math.random() * 10) + 1 - A random number from 1 to 10 (int)
Math.abs(x) int (int) The absolute value of x
Math.ceil(x) double (double) Nearest whole number >= x
Math.floor(x) double (double) Nearest whole number <= x
Math.rint(x) double (double) Closest whole number to x
Math.round(x) double or float (int or long) Closest whole number to x.  To round to a 2 decimal places:
Math.round(3.1415926 * 100) / 100.0
Math.sqrt(x) any (double) Square root of x
Math.pow(x,y) any (double) x raised to the power of y
Math.sin(x), Math.cos(x),
Math.tan(x), Math.asin(x),
Math.acos(x), Math.atan(x)
double (double) Sine, cosine, tangent, arcsine, arccosine, arctangent of x
Math.log(x) double (double) Natural logarithm of x
Math.exp(x) double (double) e raised to x

It is often necessary to cast the result of these methods to other variable types.  For example, since Math.pow() returns a double, you can assign the result to an integer by casting:

int OneByte = (int) Math.pow(2,8);

random.java

// Print a random statement

public class random
{
   public static void main ( String [] args )
   {
      int R = (int)(Math.random() * 4) + 1;
      if (R == 1)
         System.out.println("You are intelligent");
      if (R == 2)
         System.out.println("You are funny");
      if (R == 3)
         System.out.println("You are nice");
      if (R == 4)
         System.out.println("You are witty");
   }
}

Output
You are funny


6.2
Wrapper Classes

The java.lang class (automatically imported) has 8 wrapper classes for each of the primitive types.  These are Boolean, Byte, Character, Integer, Float, Double, Long, and Short.  These provide:
(1) a mechanism to "wrap" a primitive variable into a class to be used for activities that require classes such as ArrayList
(2) utility functions for primitive types like converting

Below are are some conversion methods using wrapper classes.

Method Returns Description
Integer.parseInt("25") 25 Converts String to an integer
Double.parseDouble("25") 25.0 Converts String to a double
Integer.toBinaryString(8) 1000 Converts integer to an unsigned binary String
Integer.toHexString(15) F Converts integer to an unsigned hexadecimal String
Integer.toString(25) 25 Converts integer to a String
Double.toString(1.5) 1.5 Converts double to a String

int A = 55;
String B = Integer.toString(A);    
// Converts A to String "55"
 

6. DecimalFormat

You may use the DecimalFormat class in the java.text package to format numbers.  Below is an example on formatting currency with commas and two places past the decimal point.

timer.java

import java.text.*; // needed for decimal format
public class delete2
{
   public static void main ( String [] args )
   {
      DecimalFormat Money = new DecimalFormat("$ ###,##0.00");
      double Amount = 1023.5;
      System.out.println(Money.format(Amount));
   }
}
Output
$ 1,023.50

Below are some example decimal formats.

Pattern Number Formatted String
###.### 123.45 123.456
###.# 123.45 123.5
###,###.## 1234.56 1,234.56
000.### 8.95 008.95
###.#% .967 96.7%
$#0.00 25.5 $25.50


6.4 System Time

If you need your program to access the system time, then you can use System.currentTimeMillis() or System.nanoTime().  The program below demonstrates how to show the time it takes for a for loop to run.  Your output will vary depending on the speed of your computer and other processes.

timer.java

public class timer
{
   public static void main (String[] args)
   {
      long BeginTime = System.currentTimeMillis();

      // waste some time
      for (int i=1; i<1000000000; i++)
      { }

      long EndTime = System.currentTimeMillis();

      System.out.println("Elapsed Seconds: " + (EndTime - BeginTime)/1000.0);
   }
}
Output
Elapsed Seconds: 0.019


6
.5 Calendar Class

Inside java.util.* are is the Calendar class and methods manipulating dates and times.  Most of the Western world using the Gregorian Calendar.  You can declare a calendar object and set it to the current date as follows:

// declare calendar object Now and make it equal to current time/date
Calendar Now = new GregorianCalendar();

// declare PearlHarbor and make it equal to Dec. 7, 1941
Calendar PearlHarbor = new GregorianCalendar(1941,Calendar.DECEMBER,7);  

If you were to print Now, you will see more a lot of information.  You can use the get() method to extract parts of the variable.

Method Returns
Now.get(Calendar.YEAR) The year, e.g. 2009
Now.get(Calendar.DAY_OF_YEAR) The day of the year (1 - 366)
Now.get(Calendar.DAY_OF_MONTH) The day of the month (1 - 31)
Now.get(Calendar.DAY_OF_WEEK) (1 - 7) for Sun - Sat
Now.get(Calendar.MONTH) (0 - 11) for Jan - Dec
Now.get(Calendar.HOUR) The hour (0 - 11)
Now.get(Calendar.MINUTE) The minute (0 - 59)
Now.get(Calendar.SECOND) The second (0 - 59)
Now.get(Calendar.MILLISECOND) The month (0 - 999)
Now.get(Calendar.AM_PM) 0 for AM, 0 for PM
Now.get(Calendar.HOUR_OF_DAY) The hour since midnight (0 - 23)

In addition, you can set and add fields within a Calendar object.  For example:

// set the year of the calendar to 2010
Now.set(Now.YEAR, 2010);

// add 2 days to the calendar Now
Now.add(Now.DAY_OF_MONTH, 2);

calendar.java

import java.util.*;

public class calendar
{
   public static void main (String[] args)
   {
      Calendar Now = new GregorianCalendar();
      Calendar EndYear = new GregorianCalendar(2009,Calendar.DECEMBER,31);
      System.out.print(EndYear.get(Calendar.DAY_OF_YEAR) - Now.get(Calendar.DAY_OF_YEAR) + 1);
      System.out.println(" days left in the year");
   }
}
Output
145 days left in the year