\documentclass[10pt]{article}

\usepackage{hyperref}
\usepackage[a4paper, total={6in, 8in}, top=.75in, bottom=1in]{geometry}

\usepackage{graphicx}
\usepackage{comment}
\usepackage{url}
\usepackage{courier}
\usepackage{color}
\usepackage{amssymb}

\usepackage[normalem]{ulem}
\useunder{\uline}{\ul}{}
\DeclareGraphicsExtensions{.pdf,.png,.jpg}
\usepackage{color}
\newcommand*\ShiftLeft{\ll}
\newcommand*\ShiftRight{\gg}
\newcommand*\BitOr{\mathrel{|}}
\newenvironment{ppl}{\fontfamily{courier}\selectfont}{\par}


\definecolor{pblue}{rgb}{0.13,0.13,1}
\definecolor{pgreen}{rgb}{0,0.5,0}
\definecolor{pred}{rgb}{0.9,0,0}
\definecolor{pgrey}{rgb}{0.46,0.45,0.48}

\usepackage{listings}
\lstset{language=Java,
  showspaces=false,
  showtabs=false,
  breaklines=true,
  showstringspaces=false,
  breakatwhitespace=true,
  commentstyle=\color{pgreen},
  keywordstyle=\color{pblue},
  stringstyle=\color{pred},
  basicstyle=\ttfamily,
  moredelim=[il][\textcolor{pgrey}]{$$},
  moredelim=[is][\textcolor{pgrey}]{\%\%}{\%\%}
}

\setlength\parindent{0pt}
\begin{document}
\title{Building Blocks -- Class Declarations, Chapter 4.4}
\author{Dr. Yvon Feaster}
\date{}
\maketitle

\section*{Class Declarations}
In this section we will discuss the fundamental concept of a Java class.  A class can be thought of as a template or blue print that describes the behaviors and states that objects of the class specific type will support.

A class  can contain any of the following:

\begin{itemize}
	\item Local variable 
	\item Instance variables
	\item Class variable
	\item Methods 
\end{itemize}

\noindent The Variables documents provides an in depth discussion on the different type of variable.  A class can have any number of methods (functions).  You should already be familiar with the definition of a method (function), so I will not elaborate on this again.

So what do we need to declare a class.  The following is the Syntax of Class Declarations:\\

[{\em{ClassModifiers}}] class {\em{ClassName}}  [extends \textit{SuperClass}]  [implements \textit{Interface1, Interface2, ...}]\\
\{\\

\hspace{.75 cm}\textit{ClassMemberDeclarations}\\

\}\\

The Class Modifiers are described in Table~\ref{tab:class_modifiers}:\\

\begin{table}[h]
\centering
\begin{tabular}{|l|l|}
\hline
no modifier & \begin{tabular}[c]{@{}l@{}}When no modifier is present, by default, the class is \\ accessible by all the classes within the same package. \\ (We will discuss packages later.)\end{tabular} \\ \hline
public      & A public class is accessible by any class.                                                                                                                                                   \\ \hline
abstract    & An abstract class contains abstract methods                                                                                                                                                  \\ \hline
final       & A final class may not be extended, that is, have subclasses                                                                                                                                  \\ \hline
\end{tabular}
\caption{Class Modifier}
\label{tab:class_modifiers}

\end{table}

Other important facts about class declarations:

\begin{enumerate}
	\item Each file contains only one class that is declared public
	\item The name of the class must be the same as the name of the file with `.java' extension. (i.e., public class Point me be stored in a file named Point.java)
	\item Each file may contain numerous nonpublic classes.
	\item The extends clause specifies the superclass of this class.  (We will discuss extends in more detail later)
	\item The implements specifies the interfaces being implemented by this class. (We will discuss implement in more detail later)
	\item The body of the class consist of fields, methods and nested classes.
\end{enumerate}

\subsubsection*{Methods}

The syntax for method declaration is as follows:
[\textit{MethodModifiers}] \textit{ReturnType MethodName} ([\textit{ParameterList}])\\
\{\\

\hspace{.75 cm} \textit{Statements}\\

\}\\

The return type for methods is required.  If there is no return value \textit{void} should be used.  Parameters should be separated by commas. 

Table~\ref{tab:method_modifiers} defines the modifiers that apply to only methods:\\


\begin{table}[h]
\centering
\begin{tabular}{|l|l|}
\hline
abstract     & An abstract method defers implementation to its subclass.    \\ \hline
synchronized & A synchronized method is atomic in a multithread environment \\ \hline
native       & A native method is implemented in C and C++                  \\ \hline
\end{tabular}
\caption{Unique Modifiers for Methods Only}
\label{tab:method_modifiers}
\end{table}

Below is an simple class declarations:\\

\begin{lstlisting}
public class Point
{
     public double x,y;
     public void move(double dx, double dy)
     {
          x += dx; y += dy;
     }
}

\end{lstlisting}


\subsubsection*{Fields}
The syntax for field declaration is as follows:

[\textit{FieldModifier}] \textit{ Type FieldName1} [\textit{=initializer1}], \textit{FieldName2} [\textit{=initializer2}] ....;\\


Modifiers that \textbf{apply only to fields} are shown in Table~\ref{tab:field_modifiers}.\\

\begin{table}[h]
\centering
\begin{tabular}{|l|l|}
\hline
volatile  & \begin{tabular}[c]{@{}l@{}}A volatile field may be modified by nonsynchronized methods in a\\ multithread environment.\end{tabular} \\ \hline
transient & A transient field is not part of the persistent state of the instance.                                                              \\ \hline
\end{tabular}
\caption{Unique Field Modifiers}
\label{tab:field_modifiers}
\end{table}

Table~\ref{tab:modifiers} defines the modifiers that apply to methods, fields, and inner classes:
\begin{table}[h]
\centering

\begin{tabular}{|l|l|}
\hline
no modifier & \begin{tabular}[c]{@{}l@{}}When no modifier is present, by default, the class is \\ accessible by all the classes within the same package. \\ (We will discuss packages later.)\end{tabular}                                           \\ \hline
public      & A public class is accessible by any class.                                                                                                                                                                                             \\ \hline
protected   & \begin{tabular}[c]{@{}l@{}}A protected  member is accessible by the class itself,\\ all its subclasses, and all the classes within the same package.\end{tabular}                                                                      \\ \hline
private     & A private member is accessible only by the class itself                                                                                                                                                                                \\ \hline
static      & \begin{tabular}[c]{@{}l@{}}A static field is shared by all instances of the class.  A static \\ method accesses only static fields.  A static nested class does \\ not have an implicit reference to the enclosing class.\end{tabular} \\ \hline
final       & \begin{tabular}[c]{@{}l@{}}A final method may not be overridden in subclasses.  A \\ final field has a constant value, which may not be changed.\end{tabular}                                                                          \\ \hline
\end{tabular}
\caption{Modifiers for Methods, Fields, and Inner Classes}
\label{tab:modifiers}
\end{table}

\subsubsection*{Class and Object Naming Convention}
I believe this has already been covered but I am going to cover it again, just in case it has not.  The following applies:  

\begin{itemize}
	\item \textit{Class} and \textit{interface} names should begin with uppercase letters, as in \textbf{Student} 
	\item \textit{Field} and \textit{method} names should begin with lowercase letters, as in \textbf{student}
	\item If a name consist of multiple words, it is formed as follows:
	\begin{itemize}
		\item a long class name -- CheckBoxMenuItem
		\item a long object name, printOptionMenue
	\end{itemize}
\end{itemize}
\subsubsection*{Creating and Initializing Objects}

There are four basic ways to initialize the fields of a class:

 an explicit initializer in a declaration, default initial values, constructors, or an initialization block.  
\begin{itemize}
	\item explicit initializer in a declaration (ex. public double x = 0.0, y = 0.0;
	\item default initial values.  If fields are not explicitly initialized, they are implicitly initialized to their default values;
	\item constructors -  you should be familiar with constructor, which are similar to constructor of other object oriented languages.  If no constructor is provided Java will provide a constructor that initializes the object to a default value.  
\end{itemize}

\subsubsection*{Accessing Fields and Methods}
\textbf{objectReference.method(Parameters)}
\textbf{objectReference.field}
Instance of an object must use the \textbf{new} operator\\


Example: \\

Point p1 = new Point();// you must use the new operator\\
double x1 = p1.x;  //the value is 0.0\\
p1.move(10.0, 20.0)\\
double x2 = p1.x //the value is 10.0\\

\subsubsection*{Method Invocation and Parameter Passing}
If the method has a return value all paths of the method body must be terminated by a return value. \\

Will the following block of code cause a compile error????

\begin{lstlisting}
	public class PurchaseOrder
	{
	    //...
	    public double calculateItemTotal(double unitPrice, int quantity)
	    {
	        if(quantity >= 0)
	        {
	            return unitPrice * quantity;
	        }
	    }
	}
	    
\end{lstlisting}

Yes!! This block of code will cause a compile error.  Suppose the quantity is less than 0, then the function will not terminate. \\

This block of code can be corrected by the following;
\begin{lstlisting}
	public class PurchaseOrder
	{
	    //...
	    public double calculateItemTotal(double unitPrice, int quantity)
	    {
	        double total = 0.0;
	        if(quantity >= 0)
	        {
	            total = unitPrice * quantity;
	        }
	        
	        return total;
	    }
	}
	
	
	or 

	public class PurchaseOrder
	{
	    //...
	    public double calculateItemTotal(double unitPrice, int quantity)
	    {
	        double total;
	        if(quantity >= 0)
	        {
	            total = unitPrice * quantity;
	        } else{
	        
	            total = 0.0;
	        }
	        
	        return total;
	    }
	}    	
	    
\end{lstlisting}

\subsubsection*{Parameter Passing}

All parameters of methods are passed by value not by reference.  This means all primitive types (ints, double, floats, etc.), objects, and arrays (remember an array is an object) are all pass by value.  Basically, when a parameter is passed to a method the value of that parameter (rather that be an address or actual value) is copied.  Lets look at a couple snippets of code.\footnote {Some of this info came from \url{http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/}}



\begin{lstlisting}
    //method name Receiving that expects an integer to be passed in.
    public void Receiving (int var)
    {
        var = var + 2;
    }
    :
    :
    public static void main(String[] args)
    {
        int passing = 3;
        Receiving (passing);
        System.out.println("The value of passing is:  " + passing);
    }
    
\end{lstlisting}

You would think passing would be 5 (3 + 2), but it is not.  The parameter var is a primitive type and the value of var when passed in was 3.  Var was copied and the copy changed to 5 but not the actually `var'.  

In the above example, if we had used an instance of a class then the \textbf{value} copied when passed in would have been an address that points to a real object.  Yep!  I know you are most likely pretty confused.  Lets look at a couple more examples.  We will pretend we have created a PersonClass.

\begin{lstlisting}
    //Create an object by passing in a name and age:
    PesonClass variable1 = new PersonClass("Mary", 32);
    
    PersonClass variable2;
    
    //Both variable2 and variable1 now both name the same object;
    variable2 = variable1;
    
    // this also changes variable1, since variable2 and variable1 name the same object:
    variable2.set("Jack" , 22);
    
    System.out.println(variable); 
    
    
    The output:
    Jack 22
\end{lstlisting}

So how does this work!  

\begin{figure}[h]
\begin{center}
  \leavevmode
  \includegraphics[width =1.0\textwidth]{Slide1.jpg}
\end{center}
\caption{Pass-by-Value Example}
\label{fig:pass_by_value}
\end{figure}

As shown in Figure~\ref{fig:pass_by_value} when variable1 is created an address to the object is stored and variable1 is pointing to that address. However, variable2 did not use the new operator so a reference is not created.  When we set variable2 = variable1 then variable2 is now referencing the same address as variable1. Clear as mud now.  The last thing that appeared in the above example is variable 2 is set to Jack 22.  So when variable2 is set to Jack 22 then so was variable1 since they both hold a reference to the same object.

\subsection*{Object Reference ``this"} 
Just as with C++, the keywork ``this" can be used to refer to the current object.  There are multiple uses of ``this", such as\footnote{\url{http://www.javatpoint.com/this-keyword}} ``JavaTpoint" discusses 6 usage of java's ``this" keyword:

\begin{itemize}
	\item this keyword can be used to refer current class instance variable
	\item this() can be used to invoke current class constructor
	\item this keyword can be used to invoke current class methods (implicitly)
	\item this can be passed as an argument in the method call
	\item this can be passed as arguments in the constructor call
	\item this keyword can also be used to return the current class instance
\end{itemize}
The website listed in the footnote has examples of each of the 6 items listed above.  Check them out.

For now we are only going to look at passing ``this", (1) to the receiving object instance as a parameter to other methods and (2) to access instance fields that are shadowed, or hidden, by local variables.  

\subsubsection*{Passing ``this" as a Parameter} 
Here is an example of this being passed as a parameter:

\begin{lstlisting}
class S2
{
     void m(S2 obj)
     {
          System.out.println("method is invoked");
     }
     
     void p()
     {
          m(this);
     }
     
     public static void main(String [] args)
     {
         S2 s1 = new S2();
         s1.p();
     }
     
}


The output:

method is invoked
\end{lstlisting}

\subsubsection*{Accessing Shadowed Fields}
So, first things first.  What the heck is a shadowed field?  Good questions!!  From \footnote{\url{http://www.xyzws.com/javafaq/what-is-variable-hiding-and-shadowing/15}}, we are told there are various kinds of variables in Java.  Each type of variable has differing scopes.  ``A variable is shadowed if there is another variable with the same name that is closer in scope.  In other words, referring to the variable by name will use the one closest in scope, the one in the outer scope is shadowed."  Below are a couple examples.  One where ``this" is used in a construct and one where ``this" is used in a setter method.

\begin{lstlisting}
//Setter method example
class Program
{
     int a;
     int b;
     
     void setA(int a)
     {
          /* here, the local variable has closer scope than the instance
             variable, so the expression set parameter equal to itself*/
          a = a;  
          
          /* the correct way to set the parameter to the instance variable*/
          this.a = a;
     }
}

//constructor method example
public class Point
{
     public int x = 0; 
     public int y = 0;
     
     //constructor
     public Point(int x, int y)
     {
          this.x = x;
          this.y = y;
     }
}

//this can also be used in a constructor
public class Rectangle
{
     private int x, y, width, height;
     
     public Rechtangle()
     {
          this(0,0,1,1);
     }
     
     public Rectangle(int width, int height)
     {
          this(0,0,width,height);
     }
     
     public Rectangle (int x, int y, int width, int height)
     {
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
     }
     ......
     
}


\end{lstlisting}

\subsection*{Interfaces and Abstract Classes}
\footnote{The Java Tutorial - A Short Course on the Basics, 6$^th$ edition} Objects use the methods to define their interaction with the outside world.  Methods provide the object's interface with the outside world.  An example is the buttons on the front of the television set act as the interface between you and the electrical wiring in the casing of the television.  You press the ``on" button and the television turns on or off.  \\
 
Our book says, Interfaces can be thought of as a special form of class, which declares only the features to be supported by the class.  Java interfaces provide no implementation.  Implementation is deferred to the classes  that implement the interface.  The syntax of an interface declaration is:\\

[\textit{ClassModifiers}] \textbf{interface} \textit{InterfaceName} [\textbf{extends}\textit{Interface1, Interface2...}]\\
{\\
     \textit{InterfaceMemberDeclarations}\\
}\\   

Interface members can be either \textit{abstract methods} or constants (final fields or static fields). Implementation of abstract methods is deferred to subclasses. Abstract methods are declared as \textit{MethodModifiers ReturnType MethodName} ([\textit{ParameterList}]);

All interfaces are public, and all interface methods and constants are public.  Class (static) methods are not allowed in interfaces.  Interfaces have no constructors, and no instances of interfaces are allowed.  Below is an example of an interface:

\begin{lstlisting}
interface Bicycle
{
     // wheel revolutions per minutes
     void changeCadence(int NewValue);
     
     void changeGear(int newValue);
     
     void speedUp(int increment);
     
     void applyBrakes(int decrement);
}
\end{lstlisting}


To implement this interface you would need to create a new class such as:
\begin{lstlisting}
public class ACMEBicycle implements Bicycle
{
   int cadence = 0; 
   int speed = 0; 
   int gear = 1;
   
   //the compiler will now require that methods
   //changeCadence, changeGear, speedUp, and applyBrakes
   //all be implemented.  Compilation will fail if those
   //methods are missing from this class
   
   :
   :
}


\end{lstlisting}

An interface is form of a contract between the class and the outside world, and this contract is enforced at build time by the compiler.  If you implement an interface your class must implement all methods of the interface before the code will compile.\\

An abstract class is a class that includes or inherits at least one abstract method.  Abstract classes may not have instances.  Abstract classes can not be instantiated.  It is used as a subclass.  If a class has an abstract method the class must be abstract.  A method that is abstract must be implemented by the child class.  Examples of an abstract class is shown in \url{http://www.tutorialspoint.com/java/java-abstraction.htm}


\subsection*{Strings}
Strings are a sequence of characters.  Strings are indexed in the same manner as an array.  The String type is class not a primitive data type.  Java provides two classes that supports string types:  1) String class, which is immutable (this means it the string can not be changed), and 2) StringBuffer and StringBuilder classes -- an instance of the StringBuffer or Builder class is mutable.  \\

Two unique attributes about the String class is:

\begin{itemize}
	\item A string, that is, an instance of the String class, can be created using \textit{string literals}
	\item Operators + and += can be applied to strings
\end{itemize}

You can determine the equality of two strings references (s1 ==  s2).  So if s1 == s2 is true if and only if both s1 and s2 point to the same memory location.  To determine if the two Strings are identical in content (case sensitive) you use s1.equals(s2).  Non case sensitive  you will use s1.equalsIgnoreCase(s2).  Use compareTo() compares two strings lexicographically -- this means that the function compares ascii values.  The return value will be <0 if s1 is less than s2.  If the values of s1 and s2 are equal then the return value will be 0.  If s1 is greater than s2 then the return value will be >0.    

The following is an example:  

String str1 =  ``FooBar";\\
String str2 = str1;\\
String str3 = new String(``FooBar");\\

Basically, str1 and str2 reference the same string object, however, str3 is a different string object with the same contents.  Java's String class privately maintains a pool of strings, where String literals are automatically interned.  When the intern() method is invoked on a String object it looks for the string contained by the String object in the pool, if the string is found there then the string from the pool is returned.  

Below is a program that demonstrates a few of the String methods:

\begin{lstlisting}

public class StringComparison
{
    public static void main(String[] args)
    {
         String str1 = "FooBar";
         String str2 = str1;
         String str3 = new String("FooBar");
         String str4 = "FooBar";
         String str5 = "Foo" +"Bar";
         String str6 = new String("Foo") + new String("Bar");
    
         System.out.println("str1 == str2: " + (str1 == str2));
         System.out.println("str1 == str3: " + (str1 == str3));
         System.out.println("str1 == str4: " + (str1 == str4));
         System.out.println("str1 == str5: " + (str1 == str5));
         System.out.println("str1 == str6: " + (str1 == str6));
         System.out.println("str1.equals(str2): " + str1.equals(str2));
         System.out.println("str1.equals(str3): " + str1.equals(str3));
         System.out.println("str1.equals(str4): " + str1.equals(str4));
         System.out.println("str1.equals(str5): " + str1.equals(str5));
         System.out.println("str1.equals(str6): " + str1.equals(str6));
         System.out.println("str1.compareTo(str2): " + str1.compareTo(str2));
         System.out.println("str1.compareTo(str3): " + str1.compareTo(str3));
         System.out.println("str1.compareTo(str4): " + str1.compareTo(str4));
         System.out.println("str1.compareTo(str5): " + str1.compareTo(str5));
         System.out.println("str1.compareTo(str6): " + str1.compareTo(str6));
    
         str2 = str2.intern();
         str3 = str3.intern();
         str4 = str4.intern();
         str5 = str5.intern();
         str6 = str6.intern();
    
         System.out.println("After interning");
         System.out.println("str1 == str2: " + (str1 == str2));
         System.out.println("str1 == str3: " + (str1 == str3));
         System.out.println("str1 == str4: " + (str1 == str4));
         System.out.println("str1 == str5: " + (str1 == str5));
         System.out.println("str1 == str6: " + (str1 == str6));
         
    }
}


The output is:

str1 == str2: true
str1 == str3: false
str1 == str4: true
str1 == str5: true
str1 == str6: false
str1.equals(str2): true
str1.equals(str3): true
str1.equals(str4): true
str1.equals(str5): true
str1.equals(str6): true
str1.compareTo(str2): 0
str1.compareTo(str3): 0
str1.compareTo(str4): 0
str1.compareTo(str5): 0
str1.compareTo(str6): 0
After interning
str1 == str2: true
str1 == str3: true
str1 == str4: true
str1 == str5: true
str1 == str6: true
\end{lstlisting}

Table~\ref{tab:string_methods} shows a common methods available for the String class.\\

\begin{table}[h]
\centering
\begin{tabular}{|l|l|}
\hline
Method            & Description                                                                                                                                                                         \\ \hline
s.length()        & Returns the length of string s                                                                                                                                                      \\ \hline
s.charAt(i)       & Returns the \textit\{i\}th character of string s                                                                                                                                    \\ \hline
s.indexOf(c)      & \begin{tabular}[c]{@{}l@{}}Returns the index of the first occurrence of character c; \\ returns -1 if c does not occur in s\end{tabular}                                            \\ \hline
s.indexOf(c,i)    & \begin{tabular}[c]{@{}l@{}}Returns the index of the first occurrence of character c \\ after (including) index i; returns -1 if c does not occur \\ in s after index i\end{tabular} \\ \hline
s.indexOf(s1, i)  & \begin{tabular}[c]{@{}l@{}}Returns the index of the first occurrence of string s1 after\\ (including) index i; returns -1 if s1 does not occur in s after\\ index i\end{tabular}    \\ \hline
s.substring(i)    & Returns the substring of s from i to the end                                                                                                                                        \\ \hline
s.substring(i, j) & Returns the substring of s from i to j - 1, inclusive                                                                                                                               \\ \hline
s.toLowerCase()   & Returns a string with all the characters in s converted to lowercase                                                                                                                \\ \hline
s.toUpperCase()   & Returns a string with all the characters in s converted to uppercase                                                                                                                \\ \hline
s.trim()          & Returns a string with all the leading and trailing white space of s removed                                                                                                         \\ \hline
s.endsWith(s1)    & Returns true if strings1 is a suffix of s                                                                                                                                           \\ \hline
s.startsWith(s1)  & Returns true if string s1 is prefix of s                                                                                                                                            \\ \hline
\end{tabular}
\caption{String Class Methods}
\label{tab:string_methods}
\end{table}

The \textit{StringBuffer and StringBuilder} classes are used when it is necessary  to modify Strings of characters.  The major difference between StringBuffer and StringBuilder is that the StringBuilder are not thread safe, meaning they are not Synchronized.  StringBuilder is faster, but if thread safety is necessary you should use StringBuffer.  

\paragraph{String and Character Array}
In C a string is a character array. In Java strings are instances of the String class.  However, a string can be converted to character arrays and vice versa.  

As an example:  \\
char [] data = \{ `F', `o', `o'\};  //this is a char array the contains Foo\\
We can convert this to a String.  \\
String str = new String(data);  \\
This is the equivalent to  String str = ``Foo";\\

also\\

String str = ``Bar";\\
char [] data = str.toCharArray(); \\

is equivalent to \\

char [] data = \{`B', `a', `r'\};\\

There are also other string -- char array conversions available.

\subsubsection*{Reading and Writing Strings}

You will often need to read and write strings from standard input and outputs.  The \textit{System} class contains the resources needed for String input -- output from the command line.  

The next several examples are from \textit{Object-Oriented Software Development} by Xiaoping Jia.

Example 1:  \\

This illustrates reading and writing strings. This program reads the characters read from the standard input line by line and writes each line to the standard output.\\

\begin{lstlisting}
import java.io.*

public class Copy{
    public static void main(String[] args)
    {
       try
       {
          BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
          String line;
          while((line = in.readLine()) != null)
          {
             System.out.println(line);
          }
       } catch(IOException e){}
    }
}

To run:  java Copy < infile.txt > out file.txt
\end{lstlisting}


Example 2: \\

This illustrates reading and writing text files.  This program copies the contents of one text file to another text file, line by line.

\begin{lstlisting}
import java.io.*;

public class CopyTextFile
{
   public static void main(String[] args)
   {
      if(args.length >= 2)
      {
         try
         {
            BufferedReader in = new BufferedReader(new FileReader(args[0]));
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));
            
            String line;
            
            while((line = in.readLine()) != null)
            {
               out.println(line);
            }
            out.flush();
            out.close();
         } catch(IOException e){}
      }
   }
}

To run:  java CopyTextFile infile.txt outfile.txt
\end{lstlisting}


You can find other examples at the following links:\\

\url{http://www.tutorialspoint.com/java/java_files_io.htm}\\
\url{http://www.tutorialspoint.com/java/io/bufferedreader_read_char.htm}\\


We can also divide strings into small pieces, known as tokens, that are separated by separators or delimiters.  Let's look at an example.  

\begin{lstlisting}

import java.io.*;

public class BreakRecords
{
   public static void main(String[] args)
   {
      BufferedReader in = new BufferedReader(new InputStreamREader(System.in));
      try{
         String record, field;
         char deli = ' : '; // the delimiter
         
         for(int n = 1; (record = inreadLine()) != null; n++)
         {
            System.out.println("Record " + n);
            int begin, end, i;
            
            begin = 0;
            for(i = 0; (end = record.indexOf(deli, begin)) >= 0; i++)
            {
               field = record.substring(begin, end);
               begin = end + 1; //skip the delimiter
               System.out.println("\tField " + i ": " + field);
            }
            field = record.substring(begin): //the last field
            System.out.println("\tField " + i + ": " + field);
         }
      }catch(IOException e){}
   }
}

Michael:Owen:123 Oak Street:Chicago:IL:60606
James:Gosling:456 Sun Blvd.: Mountain View:CA:45454

Output:
Record 1
	Field 0: Michael
	Field 1: Owen
	Field 2: 123 Oak Street
	Field 3: Chicago
	Field 4: IL
	Field 5: 60606
	
Record 2
	Field 0: James
	Field 1: Gosling
	Field 2: 456 Sun Blvd.
	Field 3: Mountain View
	Field 4: CA
	Field 5: 45454
   
\end{lstlisting}

You can also use the StringTokenizer.\\

Tables~\ref{tab:constructors},\ref{tab:methods} show constructors and methods used in the String Tokenizer.


\begin{table}[h]
\centering
\begin{tabular}{|l|l|}
\hline
Constructor                       & Description                                                                                                                                                                                  \\ \hline
StringTokenizer(str)              & \begin{tabular}[c]{@{}l@{}}Tokens are delimited by one or more while spaces,\\ and the delimiters are discarded.\end{tabular}                                                                \\ \hline
StringTokenizer(str, delim)       & \begin{tabular}[c]{@{}l@{}}Tokens are delimited by andy character in delim, and \\ the delimiters are discarded.\end{tabular}                                                                \\ \hline
StringTokenizer(str, delim, keep) & \begin{tabular}[c]{@{}l@{}}Tokens are delimited by any character in delim.  The\\ delimiters are returned as tokens if keep is true.\\ Otherwise, the delimiters are discarded.\end{tabular} \\ \hline
\end{tabular}
\caption{StringTokenizer Methods}
\label{tab:constructors}
\end{table}


\begin{table}[h]
\centering
\begin{tabular}{|l|l|}
\hline
Method          & Description                                \\ \hline
hasMoreTokens() & Returns true if there are remaining tokens \\ \hline
nextToken()     & Returns the next token and advance         \\ \hline
countTokens()   & Returns the number of remaining tokens     \\ \hline
\end{tabular}
\caption{StringTokenizer Constructors}
\label{tab:methods}
\end{table}

CHALLENGE:\\
Using the above examples and the constructors and methods provided try to write a program that will read text from standard input and breaks the text into words.  

\subsubsection*{Wrapper Classes}
Earlier we discussed primitive data types, which are not considered to be objects.  (boolean, byte, char, double, float, int, long, short)  Sometime you want to be able to use a primitive data type as you would an object, therefore there are Wrapper classes for each the primitive data types.  A Wrapper class allows you to use a primitive data type as an object.  All wrapper classes that involve numbers are subclasses of the abstract class \textit{Number} which is part of the java.lang package.  The primitive type of char has a wrapper class provided by the Character class which is also part of the java.lang package.\\  


Another class that you might be interested in is the math class, which is part of the java.lang package.
\end{document}


