\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}]{\%\%}{\%\%}
}
\begin{document}
\title{Building Blocks -- Variables, Chapter 4.2}
\author{Dr. Yvon Feaster}
\date{}
\maketitle

\section*{Variables}
In this document we will discuss variables, a subject you should be very familiar with.  Basically a variable is a name used to refer to data stored in a memory location.  Think of a variable as a box where you store data that you will need later.  Each variable is associated with a {\em{type}}.  We discuss literals and primitive data types in a previous documents.   \\

\noindent The basic syntax of a variable declaration is: \\
Type VarName1 [= InitialValue], VarName2 [=InitialValue] ....;

\noindent This declares one or more variables of type {\em{Type}}.  Java supports two kinds of types:  primitive types and reference types.  We have already discussed primitive types.  A reference type variable holds a reference to an object or array.\\

\noindent There are 3 uses for variables\footnote{Information taken from Catherine Hochrine's notes.}  

\begin{itemize}
	\item Member variables -- a.k.a., fields in class definition
		\begin{description}
			\item [Instance variables] member variables that are non-static.  When an object of a class is instantiated, the member fields of that class are instance variable for the specific object that was instantiated.   
			\item[Class variable] member variable that are static.  These member variables belong to the class, and not any instances of the class.  There is exactly one copy of a class variable which is in one fixed location in memory, regardless of how many times the class has been instantiated.  Any object can change the value of a class variable, as can class methods.
		\end{description}
	\item Local variables -- variables in a method or block of code.
	\item Parameters -- variables in method declarations.
\end{itemize}

\noindent In Java, all programming is done inside ``classes".  The first letter of a class name should be capitalized.  Not every class is a program.  A class with a main method is a program.  \\

\noindent A class with no main, and with non-static instance variables and instance methods is a class that exists only for creating objects - it is like defining a new \textbf{type} (like int, boolean, etc).  However merely declaring a variable of some class (\textbf{type}) does not create an object.  An object is not instantiated until the \textbf{new} operator is used.  For example, if there is a {\em{class Student}} defined, declaring a variable such as:  {\em{Student std1}}; does not create an instance of that class (does not create an object) until you apply the \textbf{new} operator to it:  {\em{std1 = new Student();}} which could have been accomplished in one line, such as:  {\em{Student std1 = new Student();}}\\

\noindent  In the above {\em{Student}} example, {\em{std1}} is a pointer to an object which exists in the area of memory called the \textbf{heap}.  So, the value of {\em{std1}} variable would be the address in \textbf{heap} memory of where the object itself exists.\\

\noindent \paragraph{Static and Non-Static Variables}  Since static and non-static variables have been mentioned we are going to look at static and non-static variables a little closer.\\

\noindent A static variable is associated with a class as a whole, not with a specific instance of a class.  Basically \textbf{ALL} instances of the same class (object of the class) share a single copy of a static variable. Let's look at an example:\\

\begin{lstlisting}
public class StaticVariableDemo
{
	
	/*Only one copy of this variable needed.  No object needed to access this variable the default value is 0*/
	static int count;
	
	/*Each instance of this class has a copy of this variable. Instance needed for access of the variable.*/
	public int count2 = 0;
	
	
	
	public void increment()
	{
		count++;
		count2++;
	}
	
	public static void main(String args[])
	{
		StaticVariableDemo obj1 = new StaticVariableDemo();
		StaticVariableDemo obj2 = new StaticVariableDemo();
		obj1.increment();

		System.out.println("Obj1: count is:   " + obj1.count);//count is static -- called using an object
		System.out.println("count is:         " + count);//count is static -- do not need an object 
		System.out.println("Obj1: count2 is:  " + obj1.count2);//count2 is non-static -- must be reference by on object

		obj2.increment();
		System.out.println("obj2: count is:   " + obj2.count);//This shows each instance has a copy of the variable.
		System.out.println("obj1: count is:   " + obj1.count);//obj1 and 2 have access to the same copy of count.
		
		/*Can not access count2 with out an instance of StaticVariableDemo. 
		If I tried to do the following I will get an error:  System.out.println(count2 is:  " + count2);  I would get an error because count2 is an instance variable*/
	}
}

Output:
Obj1: count is:		1
count is:		1
Obj1: count2 is:	1
obj2: count is:		2
obj1: count is:		2

\end{lstlisting}

\subsection*{Constants}

\noindent  We have discussed static variables, so lets talk about the keyword of \textbf{final}.  This keyword or a.k.a, modifier, can be used to make a value constant, meaning it can not be changed.  Similiar to \#define in `C' a constant variable is written in all caps to distinguish it as a constant.  Here is an example:\\

final int NUMBER\_OF\_HOURS\_IN\_A\_DAY = 24;   If you try to change the value of variable you will get a compiler error.  If you want the constant to be only in the scope of a method then declare in that method.  However, if you want it to be reachable by more than one method then declare it at the top of the class definition: As an example:\\

\begin{lstlisting}

public class AllAboutHours
{
         /*since this is static you only have one copy shared with all instances of this class*/
	private static final int NUMBER_OF_HOURS_IN_A_DAY = 24;
	
	public int calculateHoursInDays(int days)
	{
		return days * NUMBER_OF_HOURS_IN_A_DAY;
	}
	
	public int calculateHoursInWeeks (int weeks)
	{
		final int NUMBE_OF_DAYS_IN_A_WEEK = 7;
		return weeks * NUMBER_OF_DAYS_IN_A_WEEK * NUMBER_OF_HOURS_IN_A_DAY;
	}
	
}

\end{lstlisting}

\noindent  Now let's take a look at the following line  private static final int NUMBER\_OF\_HOURS\_IN\_A\_DAY = 24;\\

\begin{itemize}
	\item the use of \textbf{private} means that constant will be accessible only directly inside its class \textbf{AllAboutHours} and no other classes will have access to it.
	\item as we discussed earlier, the use of \textbf{static} means that there is only one copy of that class variable - its value will be shared among all instances of any objects of the class \textbf{AllAboutHours}
\end{itemize}
\subsection*{Type Compatibility}

\noindent Now lets discuss the compatibility of variable types. The definition of Type Compatibility is as follows:  \\

\noindent Type {\em{T1}} is {\em{compatible}} with type {\em{T2}} if a value of type {\em{T1}} can appear wherever a value of type {\em{T2}} is expected, and vice versa.;\\

\noindent Let's begin with primitive types, as a reminder the primitive types in order of size is: byte, short, int, long, float, and double  \\

\noindent Widening and narrowing of numeric types.  \\

\noindent Widening = small type to larger type (e.g., `int' to `double') \\

\noindent Narrowing = larger type to smaller type (e.g., `double' to `int') \\

\noindent When widening a data type there is no fear of overflow or loss of precision.  So widening does not require casting.  However, narrowing could result in overflow or loss of precision so you must typecast with narrowing.  Narrowing and widening of reference types will be discussed later.

\subsection*{Reference Type}

\noindent  A reference type is a class, an interface, or an array type.  A reference variable will hold a reference to an object (pointer to an object)  or it may be null (if it is null it is not a reference).  As an example, Student std1 = new Student(``Sally");  std1 holds the memory address to a place in memory.  \\

std1 = an address \\
\indent However, Student std2; ( std2 is null)\\

Figure~\ref{fig:ch41ex} is another example
\begin{figure}[h]
\begin{center}
  \leavevmode
  \includegraphics[width =0.80\textwidth]{ch41ex_v2.pdf}
\end{center}
\vspace{-.7 cm}
\caption{Primitive and Reference Type Example}
\label{fig:ch41ex}
\end{figure}

\noindent Java references are different than `C' and `C++'
\begin{enumerate}
	\item C and C++ pointers can be cast to any type.  Modified through pointer arithmetic and assigned arbitrary values.  This is not allowed in Java.
	\item C and C++ pointers reference chunks of heap memory, the programmers are responsible for managing the allocation and deallocation of memory.  In Java, reference variables point to dynamically allocated memory space from memory managed by Java through something called Garbage Collection. \\
\end{enumerate}

\subsection*{Garbage Collection}

Garbage Collection is a way to allow java to automatically deallocate unreferenced or unreachable objects.  It is a very important feature of Java.\\

\noindent Garbage Collection has it's disadvantages.  The programmer can not control when the garbage collection is initiated, timing is unpredictable.  This sometimes makes Java unsuitable for software systems that require the assurance of completion certain task within specific periods of time.  In other words if timing is important java may not be an appropriate language.  However, the benefits of Java garbage collection outweighs the loss of speed.

\subsection*{Equality of Reference Variable}
std1 == std2  only test the equality of the two references, not the equality of the states of the objects or arrays.  To test the equality of the state of the object you must use the equals() method. (example std1.equals(std2))

\subsection*{Arrays}

An array in java is a data structure that stores a fixed-size sequential collection of data or elements of the same type.  An example of how to declare an array is as follows:\\

type[] arrayVariable;  //this is the preferred method of declaring an array \\

or\\

type arrayVariable[]; //this works as well, but is not the preferred method of declaring an array\\


The following are examples of creating and initializing 1D arrays:
\begin{table}[h]
\centering
%\caption{My caption}
%\label{my-label}
\begin{tabular}{ll}
int {[}{]}  first = new int{[}3{]}; & Creates an integer array of size 3; all elements initialized to 0;           \\
int {[}{]} second = \{10, 9, 8\};   & Creates an integer array of size 3; elements initialized to 10, 9, \& 8 \\
Point{[}{]} p = new Point{[}10{]};  & Creates an array of points of size 10; elements are initialized to null 
\end{tabular}
\end{table}

\noindent Initializing and accessing the elements is similar to what you're used to with `C' and `C++'.  The \textbf{System} class has a method called \textbf{arraycopy} which makes it easy to efficiently copy data from one array to another.  \\

\noindent  Below are several examples of working with arrays.  These examples came from the website tutorialspoint \url{http://www.tutorialspoint.com/java/java_arrays.htm}

\subsubsection*{Processing Arrays}
When looping through elements of arrays we often use a for loop (which you should be familiar with) or a foreach loop.  We are able to use the foreach because the elements are all of the same type.

\noindent Example1:

\begin{lstlisting}
for loop

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}


Output:  
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

foreach loop:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

Output:

1.9
2.9
3.4
3.5

\end{lstlisting}


Arrays as parameters:  \\

\noindent Example 2
\begin{lstlisting}
//method to display the elements of an int array

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}


//now you can invoke this method by passing an array to the method call
printArray(new int[]{3, 1, 2, 6, 4, 2});  Below is an example.

\end{lstlisting}


\noindent Arrays can also be returned from a method:

\begin{lstlisting}

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}

\end{lstlisting}


The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. 

\end{document}


