introduction to java dr. billy lim applied computer science department illinois state university

130
Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Upload: dominick-lamb

Post on 16-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Introduction to Java

Dr. Billy LimApplied Computer Science DepartmentIllinois State University

Page 2: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Objectives

• Upon completion of this course, you will be able too Understand the architecture of Java technologyo Use the various programming language features of

Javao Develop basic Java applicationso Write OO applications using Java

Page 3: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Why Java?

• Observations …o 4 million Java programmers and the community is growing at the rate

of 30 percent a yearo Java is now running on everything from smart cards to the Mars Rovero Java 2 Platform, Standard Edition v 1.4 hits the million mark

In less than a month, the latest version of J2SE has been downloaded over a million times

o More than 20,000 attendees in a recent Java developer conference (JavaOne)

o 100-million Java Consortium formed by some of the biggest software companies (IBM, Oracle, …)

o Number of Fortune 500 adopting Javao More than 1/2 millions Java developerso … (many many more!)

Page 4: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Java’s Penetration ...

Page 5: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

History of Java

• “Java’s ancestor was a toaster!”

• Began life as a programming language for consumer electronics

• C/C++ not up to task! (not chip-independent)

Page 6: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

History of Java (2)

• 1990: James Gosling at Sun designing a language called “Oak”, a small, reliable, architecture-independent language

• 1993: WWW appeared and took Internet “by storm”

• Gosling and his team thought, “hey, this is bigger than we thought.”

Page 7: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

History of Java (3)

• Sun wrote a new WWW browser named HotJavao First browser to support Java applets However,

only “alpha” Java API

• Netscape later announced Java support• Later a beta API, and soon a Java 1.0 API

released• The rest is history

Page 8: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

What is Java?

• From “The Java Language: A White Paper” (by Sun):

“A simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language”

Page 9: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Simple

• What’s simple?o Can learn quicklyo Looks familiaro Poor programming features removed (e.g., no goto)o No pointerso Garbage collection - no memory leaks

Page 10: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Object-Oriented

• OO is ubiquitous!o Lots of commercially produced code in C++ (and

Java, Smalltalk, etc.)

• Focus on data, not procedures• Encapsulates data and functions• More “natural”• Exploits inheritance• (Almost) Everything in Java is an object!

Page 11: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Distributed

• Designed to support applications on networkso Applets downloaded over the neto Resources accessed via URLs

• Socket class built ino easy to write

clients and servers, collaborative programs

• Reliable stream network connections• Furthers goal towards making the network is the

computer

Page 12: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Interpreted

• Java compiler’s output is in “byte-code” format

• Must run an interpreter to run these bytecodeso Java Virtual Machine (JVM) is the interpretero may be realized by software or hardwareo JVM is built into AppletViewer, Netscape, IE,

HotJava, etc. These bytecodes are architecture-neutral

Page 13: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Architecture-Neutral

• Bytecodes run on any machine, as long as an interpreter exists

• Neutrality helps programmers -- no porting requiredo Unlike C/C++, no implementation-dependent features (e.g., int is

always 4 bytes)

• Using the AWT, we can create architecture-neutral windowing applications!

o Abstract Windowing Toolkit (AWT) and “peer” classes give appropriate “look and feel”

Page 14: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Architecture-Neutral (2)

Java Compiler

JVM

Windows

JVM

Solaris

JVM

OS390

JVM

Mac

Java Source

Java Bytecode

“Write Once, Run Anywhere”

Page 15: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Robust

• Highly reliable• Helped by:

o Strong typing featureso Object-orientationo Java Memory Modelo No Pointerso Garbage Collectiono Exception Handling

Page 16: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Secure

• Security is very important in networked environments

• No pointers

• Applet only: Can’t access any computers other than host

• Evolving security measureso JDK 1.02: sandbox (e.g., no disk I/O for applets)o JDK 1.1: signed applets o JDK 1.2 and beyond: “security policy” (with the SecurityManager class)

• JVM enforces restrictions on applets

• JAVA does not stand for “Just Allow Virtually Anything”

Page 17: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Portable

• Makes sure there are no implementation-dependent aspects

• Strong API

• Java compiler: written in Java

• Java run-time system: written in ANSI C

Page 18: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

High-Performance

• Interpreted: won’t be as fast as C (getting closer every day though!)

• Performance-critical applications: JIT (“just in time”) compilers

• HotSpot technology (Sun), Jikes (IBM)• Native methods• The spectrum:

o Tcl/Tk, shells < Java <= C and C++

Page 19: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Multithreaded

• Multiple things at once• Supports multiple threads of execution (lightweight

processes)o garbage collection threado sound and animation

• Java has built-in support for synchronization primitives o Thread class built ino synchronized keyword

Page 20: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Dynamic

• Dynamic class loading, as required, possibly over the net

• Classes have run-time information

• These classes can be anywhere on the Internet

• All of this run-time loading is invisible to user

Page 21: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

How Do I Use Java (on the net)?

• Web Userso transparent to you

• Web Page Designerso use the <APPLET> tag in HTMLo thousands of applets out there!

• Java Developerso create Java applets, servlets (“server-side applets”),

and/or JSP (Java Server Pages)

Page 22: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Java Editions

• Free download from http://java.sun.com o J2SE (Java 2 Standard Edition)o J2EE (Java 2 Enterprise Edition)o J2ME (Java 2 Micro Edition)

Page 23: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

J2SE

Page 24: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

J2SE Software Development Toolkit (SDK)• javac

o Java compiler, converts .java to .classo All Java source codes must be stored in files with .java extension

• javao Java virtual machine (i.e., the interpreter)

• javadoco generates HTML documentation from Java source files (/** … */ segment)

• appletviewero allows applet to be run outside of a browser

• jaro Java archive tool (JDK 1.1 only)

• javaho Java C header and stub generator

• jdbo Java Debugger

Page 25: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

SDK (cont’d)• Java Package Library

o java.lang, java.io, java.awt, java.net, java.util, java.applet (JDK 1.02)o java.beans, java.sql, java.rmi, … (a lot more) etc. (JDK 1.1, Java 1.2,

Java 1.3)

• JDK available in:o Unix platformso Windows 95/98/NT/2000o OS/2o Macintosho Windows 3.1o OS 390

And more!!!

Page 26: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Java IDE Tools

• Eclipse (Apache Open Source Project)o Based on IBM VisualAge for Java

• IBM WebSphere Application Developer (WSAD)• BlueJ• Borland JBuilder • Oracle JDeveloper • Symantec Visual Café• Sun Forte for Java• ...

Page 27: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

First Java Program: Hello, World!

// This is a comment// The file is named HelloWorld.javapublic class HelloWorld {public static void main(String args[]) {

System.out.println(“Hello World!”);}

}

• Note: If the class is public, the name of the class (i.e., HelloWorld) must be the same as the name of the file plus the .java extension (i.e., HelloWorld.java)

Page 28: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

main(): Not quite so simple anymore

• In Java, we can’t simply write main()

• We have to create main as a method in a Java class which returns nothing (void)

• Furthermore, we must make this method public and statico public: Anything can call ito static: It belongs to the class itself, not a instance of

the class

Page 29: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

println explained

• What exactly is System.out.println(“...”)?

System is a classIt has a class variable named outout refers to an object of type PrintStreamPrintStream objects have an instance method named println

QED

Page 30: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

A Java Program Skeletonpackage MyPackage; // used if adding class to a package

import packageName; // used if a package/class is to be “loaded”

accessType class ClassName extends SuperClass {

// Field Declarations are given hereaccessType dataType fieldName;private int salary;

// Method Definitions are given hereaccessType returnType methodName (parameter list) {

… // method body}public void print () {

System.out.println(“Salary is ” + salary);}

}

ClassName.java

Bold - keywords

Access Types:privatepublicprotecteddefault = “friendly”

Page 31: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Applications and Applets

• Applications are stand-aloneo No security restrictions

• Applets are designed for the webo Security restrictionso Integrates with HTMLo Shows up in WWW browser

In the last few years, two other kinds of Java programs have

been introduced – Servlets and JSPs

Page 32: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

The “Hello World” Applet// HelloApplet.javaimport java.awt.*;import java.applet.*;public class HelloApplet extends Applet {

Font f = new Font(“TimesRoman”, Font.BOLD, 36);

public void paint(Graphics g) {g.setFont(f);g.setColor(Color.red);

// draw string at x=5, y=50 (pixels)g.drawString(“Hello World!”, 5, 50);}

}

Page 33: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Java: The Programming Language

Page 34: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Edit-Compile-Run Cycle in Java

Compiler (e.g., javac )

.java (source file)

.class (bytecodes)

Java VM (e.g., java)

output

Page 35: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

How to Compile and Run

• Compile a source code file by typing javac <filename>.java (e.g., javac HelloWorld.java)

o If no compile-time error appears, a .class file is produced.

• Run an application by typing

java <class name> (e.g., java HelloWorld)

Not java HelloWorld.class

Page 36: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Features Similar to C/C++’s

• Same comment styleso new: /** to be processed by javadoc … */

• Same literals and data typeso new: true and false for the boolean data typeo new: strings not null terminated, not mutableo new: numeric sizes and their machine independence

• Same operators• Same control structures

Page 37: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Keywords

short else static package throws byte while new import throw int do instanceof abstract volatile

long for this extends native float switch super interface transient double case void implements const boolean break public try goto char continue private catch class return protected finally if final default synchronized

Page 38: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Java’s Basic Constructs

• Commentso // comment on one lineo /* comment on one or more lines */o /** documenting comments */

• Statementso int x; // statement ends with a semicolon (;)o x = 1 + 2;

Page 39: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Primitive Data Types

• There are 8 primitive data types in Javao All the numeric types (integer and floating point

types) are signed (meaning they can be positive or negative). No unsigned numeric types in Java (unlike C/C++).

• Three categories of data types:o Primitive data typeso Class data types (coming later)o Interface data types (coming later)

Page 40: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Basic Data Types

• Integerso byte (8 bits)o short (16 bits)o int (32 bits)o long (64 bits)

• Characterso char (16 bits Unicode)

• Floatso float (32 bits)o double (64 bits)

• Booleano boolean (1 bit)

• Stringso String (an example of class

data type)

capital case (because it is a class, not a primitive)

Primitive data types

Page 41: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Identifiers and Literals• Identifiers

o case sensitiveo have no maximum lengtho start with a letter, underscore, or dollar sign

e.g., user_name, _file, $money

• Literalso numeric: 2 (int), 3L (long), 2.0f (float) 3.14 (double), 077 (octal),

0xDC (hex)o character: ‘a’, ‘t’o boolean: true, falseo string: “hello”

Watch out for these!

Page 42: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Booleans

• Has value true or false (different from numeric type)

• Returned by relational operators• Required for conditional statements• E.g.,

o // if x is an into C/C++: if (x) { ...} // OK in C/C++, not OK in Javao Java: if (x == 1) { ...}

Page 43: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Strings

• String is a “built-in” class provided by Javao e.g., String s1 = “Hi there!”;

• The ‘+’ operator is used for String concatenationo e.g., String s1 = “abc”;o String s2 = s1 + “ ” + s1;

• String objects represent constant strings (content cannot be altered)

• Many methods supported in the String class

Page 44: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Strings (2)

• ExamplesString lastName = “Schaefer”;lastName.length() // gives 8lastName.toUpper() // gives “SCHAEFER”lastName.toLower() // gives “schaefer”lastName.indexOf(“e”) // gives 4lastName.indexOf(“x”) // gives –1 (for not found)lastName.indexOf(“e”,5) // gives 6lastName.substring(2,5) // gives “hae” (1st index is inclusive, 2nd

index is exclusive)

Page 45: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Declarations & Assignments// TestDataType.javapublic class TestDataType {

public static void main(String[] args) {int x = 1;float y = 3.1415f;boolean truth = true;char c = ‘X’;String str1 = “Hello”, str2 = “World”, str3;str3 = str1 + str2;System.out.println("x="+x+"y="+y+"truth="+truth+"c="+c+"str3="+str3);

System.out.println(“Length of str3 = “ + str3.length());}

}

Syntax (first look):objectRef.methodName(argument list)

Note: If the + operation has a string involved, a concatenation of all the operands is performed.Java automatically converts all data involved to their string representations.

Page 46: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Operators

• Partial list (in order of precedence):o ++, --o !, (type)o *, /, %o +, -o <, >, <=, >=, instanceofo ==, != (equal to and not equal to operators, respectively)

o && (this is the logical AND operator)

o || (this is the logical OR operator)

o =, *=, /=, +=, ...

++ (Preincrement, Postincrement) // increments a variable by 1 e.g., x = 1; System.out.println(x++); // displays 1 System.out.println(x); // displays 2 e.g., x = 1; System.out.println(++x); // displays 2 System.out.println(x); // displays 2 -- (Predecrement, Postdecrement) // decrements a variable by 1 e.g., x = 1; System.out.println(x--); // displays 1 System.out.println(x); // displays 0 e.g., x = 1; System.out.println(--x); // displays 0 System.out.println(x); // displays 0

Page 47: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Casting and Promotion

• Casting o conversion of one data type to another data typeo Two ways to cast in Java:

implicit - Java does it for you automatically For primitives, if expression on the right differs from the type of the

variable on the left, automatic cast will happen if no possibility of losing information. The narrower data type will be promoted to the wider one.

For objects, later on this. explicit - the programmer must take care of the casting

For primitives, if expression on the right differs from the type of the variable on the left and there is a possibility of losing information.

For objects, later on this.

Page 48: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Promotion and Casting

• e.g., // TestDataType2.java

int x, y = 1;

double z = 1.23;

x = y / z; // compilation error

x = y / (int) z; // OK

x = (int) (y / z); // OK

z = x; // OK

Page 49: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Decision Structures

• Syntax (if, else):

if (boolean expr) {

statements;

} else {

statements;

}

• Example:int status;...if ( status == 1) {

deduction = 500; marriedCount ++;

} else { deduction = 100;singleCount ++;

}Note: else part is optional

Page 50: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Decision Structures (2)

• Syntax (switch):switch (expr) {

case expr1:stmt1;break;

case expr2:stmt2;break;

default:stmt;break;

}

• Example:switch (status) {

case 1: marriedCount++;break;

case 2: singleCount ++break;

default:// error;break;

}

Page 51: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Looping Structures

• Syntax (for):

for (initial expr; boolean expr; update expr) { statements;

}

• Example:

for (int k = 0; k < 10; k++) { System.out.println(k);

}

Page 52: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Looping Structures (2)

• Syntax (while):

while (boolean expr) {

statements;

}

• Examples:

int k = 0;while (k < 10) {

System.out.println(k);

k++;

}

keepGoing = ‘y’;

while (keepGoing == ‘y’) {

// determine if you need to keep going

}

Page 53: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Arrays

• Arrays are objects• Like C/C++, subscripts start from 0• No pointers in Java => no pointer arithmetic

• To create an array, o use “new”

e.g., int a[] = new int[5]; // creates an array of 5 ints same as: int [] a = new int[5];

o or array initializer int a[] = {1, 2, 3, 4, 5};

• To access an array element, use a[i] where 0 <= i < arraySize• Array boundaries are checked at runtime

Page 54: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Arrays (cont’d)

• The following will throw an exception (can be caught and handled)o e.g., int a[] = new int[5]; a[5] = 123; // array out of bound exception

• Can use length to determine array sizeo e.g., public void doSomething ( int a[] ) { for (int i = 0; i < a.length; i++) a[i] = 0; }

Passing an int array into a method

Page 55: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Arrays (cont’d)

• Creating an array of objects:o Student classList [] = new Student[25];

o classList[0] = new Student();

classList

nullnullnull

null

classList

…nullnull

null

aStudent

Page 56: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Arrays (cont’d)

• Initial values:o // TestArray1.javao String names [] = {“John”, “Mary”}; or

String names [] = new String [2];names[0] = “John”;names[1] = “Mary”;

o Can’t do this: int list[5]; // error: Can’t specify array dimension in type declaration

int list2[]; // OK; declares list to be an array of int but does not allocate any space for it yet list2[0] = 1; // error: because list2 has not been not allocated any space.

// Need to use: int list2[] = new int[10];

Page 57: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Arrays (cont’d)

• Cannot resize arrayso int myArray[] = new int[5]; // myArray is an array of 5 ints

o myArray = new int[10]; // myArray is a different array, with 10 ints

// Will discuss this further in Objects

• Copying arrayso Use System.arraycopy methodo int copyFrom[] = {10, 20};o int copyTo[] = {100, 200,300};o System.arraycopy(copyFrom,0, copyTo,0, copyFrom.length);o Result: copyTo has {10,20,300};

Page 58: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Multi-Dimensional Arrays

• Arrays of arraysint twoDim [][] = new int [4][];

twoDim [0] = new int [5];

twoDim [1] = new int [5];

twoDim [2] = new int [5];

twoDim [3] = new int [5];

o Alternatively,int twoDim [][] = new int [4][5];

Page 59: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Command Line Arguments

• The entry point to your Java application must have the following method:o public static void main (String argv[]) {...}

• argv[] must be present -- it holds the command line arguments

• argv[0] gives the first argument

• Use argv.length to get the number of arguments

Page 60: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Command Line Arguments (2)

• e.g., // TestCmdLine.javapublic class TestCmdLine {

public static void main (String argv[]) { if (argv.length == 0)

System.out.println(“No argument given!”); else

for (int i=0; i < argv.length; i++) System.out.println(argv[i]); }}

Page 61: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Naming Conventions

• Methods & variables:o Mixed case, starting with lower-case for the first word and

each subsequent word starts with a capital lettero E.g.,: myFirstMethod(), myBankAccount

• Classes & interfaces:o Mixed case, starting with upper-case for the first letter of

the first word and each subsequent word starts with a capital letter

o E.g.,: MyClass, MyInterface

Page 62: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Naming Conventions (cont’d)

• Constants:o Upper case, with words separated by underscoreso E.g.,: MY_LARGE_CONSTANT

• Packages:o All lower-case letters in all the wordso E.g.,: com.billylim.project1

Page 63: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Object-Oriented Programming with Java

Page 64: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Classes

• A class is a template (i.e., blueprint) for creating objects

• A class extends another class (inheritance relationship)o e.g., public class className extends superclassName { ... }

• By default, all classes are derived from a single root class called Object

• All classes except Object have one immediate superclass

Page 65: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Classes (2)// Student.javapublic class Student {

private String name; // name is a field, attribute, or an instance variable

public Student(String n) { // This is a constructor. Note that it has the name = n; // same name as the class name. More on this later.

}public void setName (String n) {

name = n;}public String getName () {

return name;}public void print () {

System.out.println(“Name is “+name);}

}

The getter and setter methods. Typically, get and set methods are defined for each field.If a field is named, say, workAddr, then a getmethod named getWorkAddr() and a set methodnamed setWorkAddr(…) are created.

Page 66: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Classes (3)// TestStudent.java (a dummy class to test the functionality of the Student class)public class TestStudent {

public static void main (String argv[]) { Student s1 = new Student("Lee");

Student s2 = new Student("John"); s2.setName("John Jr.");s1.print(); System.out.println(s2.getName()); // can also use print() here

}}

• Note: The Student and TestStudent classes need to be in the same directory for the above to work properly.

Page 67: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Objects

• Objects/instances of classes are created using “new”o e.g., Student s = new Student(“John”);

• A variable of non-primitive type actually holds “handle” for the actual object. It is called an object reference.

• Assigning objects copies the handle, not the object.

Page 68: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Objects (2)

• Example:Student s1 = new Student(“Lee”); s1

Student s2 = s1; s1

s2

s2.setName(“Lee JR.”); // whose name is changed?

Aside: This is why System.arraycopy is needed to copy arrays

Lee

Lee

Page 69: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Objects (3)

• Example:Student s1; // s1 has the value nulls1 = new Student(“John”); s1s1 = new Student(“Mary”);

s1

s1 = null; // what is the effect of this?

John

Mary

John John will be garbage collected

Page 70: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Fields

• Field creationo Syntax:

accessType dataType fieldName;o Example:

private int hoursWorked; private String name;

• Field useo Syntax:

fieldName (if inside the class) objectReference.fieldName (if outside the class and if the field is

accessible)o Example:

if (hoursWorked < 40) … // inside class employee1.hoursWorked = 37; // outside class

optional

Page 71: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Methods

• Methods o defined the behaviors of a class (called member functions in

C++)o can only be implemented in classes (no standalone code)o must have a return type unless they are constructors (which

have no return type)o must have a comma separated list of pairs of parameter

types and names (if takes no parameter, the list is empty)

Page 72: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Method Definition• Syntax:

[accessType] [modifier(s)] returnType methodName (parameter list) {… // method body

}

• Examples:public static void main(String[] args) {

…}private int myMethod(int j, String s) {

…}String myMethod2( ) {

…}

optional

Page 73: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Constructors

• Special methods that have the same names as their classes

• Are invoked during the creation of an object by “new”

• Constructors do not have a return type• Constructors (and methods in general) can be

overloaded by varying the number of types of parameters

Page 74: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Constructors (2)

• Default constructoro A default constructor is automatically provided for

you in every class Format: public MyClass() { // assume class name is MyClass

}

o Allows you to do: MyClass mc = new MyClass( );

o Will be invalidated if you add a constructor declaration with arguments

Page 75: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Access Specifiers

• As with C++, components of classes can have associated access specifierso public Accessible by allo protected Only accessible from this class,

its subclasses, and package.o private Only accessible from this class o “friendly” Accessible from the package;

Default access (no specific declaration)

Page 76: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Access Specifiers (2)

• Accessibility Criteria

Modifier Same Class Same Package Subclass All

public Yes Yes Yes Yes

protected Yes Yes Yes

Default Yes Yes

private Yes

Page 77: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Access Specifiers (3)

• Examine the classes Employee.java and TestAccess.java in your source disk.

• Compile the class TestAccess.java and observe the output. (Should see an error message.)

• Now change the name and salary fields to public and re-compile and run TestAccess.java.

• Lesson: Keep instance variables/fields private!

Page 78: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Argument/Parameter Passing

• Java passes arguments by value only

• When an object reference is passed as an argument to a method, a copy of the object reference is passed. o Thus, the contents of the actual object can be

changed in the method, but the object reference itself is never changed.

Page 79: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Argument/Parameter Passing

• Example:…public static void main (String args[]) {

int a = 10;String s = “hello”;Employee e = new Employee (“Mary”);method1(a, s, e);System.out.println(“a =“+a+”s=“+s+”e”+e); // prints 10, hello, and John

}public static void method1 (int a2, String s2, Employee e2) {

a2 = 100;s2 = “hello2”;e2.setName(“John”);e2 = new Employee(“Matt”);

}

Page 80: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Class Inheritance

• We can “inherit” from other classes• Avoids coding things which have already been coded

(i.e. reuse the structure and behavior already implemented)

• Subclass inherits everything from the superclass, but programmer can add/change things in the subclass

• Commonly referred to as the “is-a” relationship (also called Generalization/Specialization relationship)

• We use the keyword extends to inherit in Java

Page 81: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Inheritance (1)

Superclass

Subclass

Fields:

f1, f2, and f3

Methods:

m1,m2, m3, m4, m5, and m6

All the fields and methods are inherited

by the subclass

An object of Superclass:

Methods:

m6,m7, m8, and m9

A subclass may add additional fields (f4-f5) and/or methods

(m7-m9) and/or override an existing

one (m6)

Fields:

f4 and f5

An object of Subclass:

Has 3 “slots” and understand messages m1-m6

Has 5 “slots” and understand messages m1-m5, m6 (as defined in the subclass) and m7-m9

Page 82: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Inheritance (2)// Person.javapublic class Person {

private String name;public Person (String n) {

name = n;}public void setName (String n) {

name = n;}public String getName () {

return name;}public void print () {

System.out.println(“Name is “+name);

}}

// Student2.javapublic class Student2 extends Person {

private float gpa;public Student2 (String n, float g) {

super (n); // calls superclass constructorgpa = g;

}public void setGpa (float g) {

gpa = g;}public float getGpa () {

return gpa;}public void print () { // overriding

super.print(); // calls superclass print()System.out.println("gpa is” +gpa);

}}

Page 83: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Inheritance (3)

// TestPersonStudent.java

public class TestPersonStudent {

public static void main (String argv[]) {

Person p = new Person("Joe");

p.print();

Student2 s = new Student2("Joe", 0.0f);

s.setName("Joe Jr."); // setName is inherited

s.setGpa(4.00f);

s.print();

}

}

Page 84: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Overriding vs. Overloading

• Overridingo Subclass can specialize the methods of the superclass by changing the

operation of a method declared by the superclass without changing the interface.

o Overridden method can be invoked using super o Same method name, same parameter list, same return type, different

body

• Overloadingo A class can enhance its functionality by providing a means for the user

to call a method with a different number of arguments or type.o Same method name, same or different return type, different parameter

list, different body

Page 85: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Overloading: Example

class Person {private String name; // overloaded constructor with no parameterpublic Person () {

name = “ ”;}// overloaded constructor with 1 parameterpublic Person (String n) {

name = n;}public void setName (String n) { … }public String getName () { … }public void print () { … }

}

public class TestPerson {

public static void main (String argv[]) {

Person p1 = new Person();

p1.print();

Person p2 = new Person(“John”);

p2.print();

}

}

Page 86: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

this and super Keywords

• Sometimes it is necessary to refer to the instance of the object itself within a method or to refer to the superclass within a subclass.

o Use this to refer to the object itselfo Use super to refer to the super class

Page 87: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

this

• Every instance method has a variable named this associated with it

• this refers to the current object for which the method is being called

• The this variable is used implicitly by the compiler when your method refers to an instance variable of the class

Page 88: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

this: Example

public static void main (String args[]) {Student s1 = new Student (“John”);Course c1 = new Course(“Java”);c1.addAStudent(s1); // add student “John” to the course “Java”

}

public class Course {...public void addAStudent (Student s) {

add(this, s); // Let’s say this method can’t handle the add itself. // It needs to pass the necessary info to another method.

}private void add (Course c, Student s) { // note that this is a private method

… // real processing here}

}

Page 89: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

this: Another Example

public static void main (String args[]) {Person p = new Person (“John”);…

}

public class Person {private String name;… public Person (String name) {

this.name = name;}…

} parameterfield

Page 90: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

this: Yet Another Example

public class Student2 extends Person {…public Student2 () {

this(“unknown”); // calling an overloaded constructor} public Student2 (String name) {

this(name,0.0f); // calling an overloaded constructor} public Student2 (String name, float gpa) {

super(name);this.gpa = gpa;

}…

}

Page 91: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

super: Example

class Student extends Person {private float gpa;public Student (String n, float g) {

super (n);gpa = g;

}…

}

• Note: When using super and this in a constructor, it must be the first thing you do! i.e., super and this must be the 1st line.

• Cannot use “super.super.varOrMethodName” to access a hidden variable or method two levels up in the inheritance hierarchy

Page 92: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Abstract Classes

• An abstract class allows the specifications of incomplete method definitions in a class (the methods are called abstract methods). The incomplete definitions are to be completed in the subclasses that inherit from the abstract class.

• Benefits:o subclasses know the interface specifiedo subclasses are forced to implement the interface

“A Parent gets to tell its children what to do!”

• Note: Abstract classes cannot be instantiated.

Page 93: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Abstract Classes: Example (1)

Account

CheckingAccount SavingsAccount

Fields:1. accountHolder

2. balance

Methods:1. Gets and sets for the fields

2. deposit3. withdraw

Can be made “incomplete,”i.e., give only

the interface but not the

implementation

deposit() and withdraw() methods must be overridden by the CheckingAccount and SavingsAccount classes in order for them to be treated as a “concrete” class. If not,

they become abstract as well.

Page 94: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Abstract Classes: Example (2)

abstract public class Transportation {

private int speed;

public abstract void transport (int speed);

public abstract void print ();

public void setSpeed (int s) {

speed = s;

}

public int getSpeed () {

return speed;

}

}

public class Car extends Transportation {

public void transport (int speed) { // drivesetGear();pressPedal();

}public void print () {

System.out.println("Speed =” +getSpeed());

System.out.println("Other Car related information");

}pubic void setGear() { … };public void pressPedal() { … };

}

Note the semicolon (i.e., no method implementation here; just the interface)

Page 95: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

OO Characteristics: PIE

• Polymorphismo Late binding mechanism

• Inheritanceo Through the use of extends

• Encapsulationo Class mechanismo private access specifier

Page 96: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Polymorphism

• In Greek it means “many forms” • In OO/Java it means

o “one interface, multiple implementations” (e.g., a print interface with multiple implementations from the Person and Student classes)

o “One object reference, possibly referring multiple forms of objects” (e.g., Person x; Here x can be a Person, Student, etc.) Note: an object has only one form but an object reference can be of

multiple forms (we say the object reference variable is polymorphic).

Page 97: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Polymorphism: Example...public static void main (String args[]) { HappyPerson list [] = new HappyPerson[3]; list[0] = new Student3(); list[1] = new Professor3(); list[2] = new HappyPerson(); for (int i = 0; i < list.length; i++) list[i].laugh();}...

public class HappyPerson { public void laugh() { System.out.println("Laugh Laugh Laugh"); }}

public class Student3 extends HappyPerson { public void laugh() { System.out.println("HaHaHa"); }}

public class Professor3 extends HappyPerson { public void laugh() { System.out.println("HeeHeeHee"); }}

Output?

Page 98: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Miscellaneous

Page 99: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

The instanceof operator

• When you are passed a polymorphic reference variable, sometimes you want to know what you actually have. Can find out using the instanceof operator.

• Example:public void method1 (HappyPerson p) {

if (p instanceof Student) {// Do something with a Student object// e.g., Student s = (Student) p; // The above fully restores the functionality of the object as a student// Without the cast, can’t perform: p.getGpa();// OK to say: s.getGpa();

else if (p instanceof Professor) {// Do something with a Professor object

else {// Do something with a regular happy person object

}}

Page 100: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Casting Objects

• Use instanceof to test the type• Use casting to fully restore the functionality of an object• Rules:

o Casts up hierarchy are done implicitly E.g., Person p = new Student();

o Downward casts must be done explicitly and are checked by the compiler E.g., Student s = (Student) p; // where p is of type Person

o Object type is checked at runtime (runtime error may result) E.g., Student s = (Student) p; // where p is of type Person and it is

// actually referring to a person object

Page 101: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

“has-a” Relationship

• Oftentimes a relationship is of type “has-a” (also called association) instead of “is-a.” o E.g., A car has an engine, an employee has a

department that he/she works for, etc.

class Car { private Engine e; …}

class Employee { private Department d; …}

Page 102: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

The == operator vs. equals()

• The == operator performs equivalence test, i.e., x==y returns true if and only if x and y are referring to the same object.

• The equals() method is overridden in classes in order to return true if the contents and type of two separate objects matcho Note: if not overridden, the Object class will return

false unless the two objects are the same.

Page 103: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Example of == vs. equals()public class TestEqual { public static void main(String argv[]) { Student s1 = new Student("Billy"); Student s2 = new Student("Billy"); if (s1 == s2) System.out.println("s1 == s2"); if (s1.equals(s2)) // equals() should have been overridden to return true System.out.println("s1 equals s2");

String str1 = new String("abc");String str2 = new String("abc");

if (str1 == str2) System.out.println("str1 == str2"); if (str1.equals(str2)) System.out.println("str1 equals str2");

String str3 = "abc";String str4 = "abc";

if (str3 == str4) System.out.println("str3 == str4"); if (str3.equals(str4)) System.out.println("str3 equals str4"); }}

Outputstr1 equals str2str3 == str4str3 equals str4

Page 104: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

The final Keyword

• Variables declared final must have a value assigned in their declarations. Attempt to change the variables will result in compilation error.o final int x = 10;

• Methods declared final may not be overridden.o final void cannnotOverride();

• Classes declared final may not be subclassed. o final public class lastClass { … };

Page 105: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Static Variables

• static Variableso Only one copy of the variable is kept for all objects

of the class (a class variable as opposed to an instance variable)

o e.g., public class Employee {

static private String workAddress;

}

Page 106: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Static Methods• static Methods

o can only access static variable of the classo implicitly final

e.g., // Professor.java public class Professor {

static private String workAddress;private String name;public void setWorkAddress (String addr){

workAddress = addr;}public static void setName (String n) {

name = n; // compile-error! // Need to remove static is this case

}public void print() {

System.out.println("workAddress = " + workAddress);System.out.println("name = "+name);

}}

// TestStatic.javapublic class TestStatic { public static void main (String argv[]) { Professor p = new Professor(); p.setName("Billy"); p.setWorkAddress("ACS 5150, ISU"); p.print(); }}

Page 107: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Static Methods (2)• Invoking static Methods

e.g., // Professor2.java public class Professor2 {

static private String workAddress;private String name;public static void setWorkAddress (String addr){

workAddress = addr;}public void setName (String n) {

name = n;}public void print() {

System.out.println("workAddress = " + workAddress);System.out.println("name = "+name);

}}

// TestStatic2.javapublic class TestStatic2 { public static void main (String argv[]) { Professor2 p = new Professor2(); p.setName("Billy"); p.setWorkAddress("ACS 9999, ISU, Normal, IL 61790"); p.print(); Professor2.setWorkAddress("ACS 1, ISU, Normal, IL 61790"); p.print(); }}

Syntax (first look):

class.methodName(argument list)

Page 108: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Static Methods (3)• Another static method example:

public class TestStatic3 { public static void main (String argv[]) { method1(); // Error: TestStatic3.java:3: Can't make static reference to method

// void method1() in class TestStatic3. } public void method1 () { // Need to add “static” to remove the error above method2(); // Possible to call method2 if it is to remain a non-static method? } public void method2 () {

System.out.println("method2 called!"); }}

Page 109: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Concept of “Packages”

• Obscene amount of Java classes on the net• Need a way to hierarchically classify them• Use an “inverse domain approach”

o e.g., edu.ilstu.acs.java.HelloWorldo e.g., com.ibm.ivj.examples.TicTacToe

• This allows us to place our classes on the Internet/Intranet/Extranet without fear of collision

• Usually only need this for end result

Page 110: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Packages (2)

• package keyword enables grouping of classes• Package names are dot.separated (.) words and are

stored in directories that match the wordso e.g., java.Util.Date, java.Util.Dictionary, java.net.URL, ...

• Package declaration must be specified at the beginning of the source file (only one permitted)

package com.xyz.dept1;

public class Employee { …}

Page 111: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Packages (3)• Accessing packages using import

o class packages are loaded with the import keyword, specifying the package name as the path and the class name.

o Load multiple classes within a package with * (a class is not loaded until it is actually referenced in your code).

o e.g., import java.util.Date; import java.awt.*; import com.xyz.dept1.*;

Note: import java.awt.*; brings all classes in java.awt into the current namespace (does not load them). Also, it does not bring any (sub)packages! Need to use: import java.awt.event.*; if classes from java.awt.event are to made visible.

Page 112: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Packages (4)

• Classpath Environment Variableo In order for the compiler to locate a class, say,

com.xyz.dept1.Employee, the classpath environment variable must be defined in the following way:

set classpath=C:\com\xyz\dept1;. (Windows)

setenv classpath=/com/xyz/dept1;. (Unix)

Page 113: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Java Packages

• Java language provides a suite of packages o java.applet (applet functionality)o java.awt (GUI components)o java.io (I/O and file I/O stream classes)o java.lang (language basics; automatically loaded)o java.net (TCP/IP networking protocols)o java.util (miscellaneous classes)o java.beans (component model)o java.sql (JDBC database support)o java.rmi (remote method invocation, distributed computing)o ...

Page 114: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Exceptions

• To help you build resilient code by allowing to catch error (i.e., exceptions) that are thrown and to handle the exception, when possible.

• The Exception class defines mild error conditions that your program encounters and might want to handleo Examples:

NullPointerException (attempt to access an undefined object or method), ArithmeticException (typically result of zero division), ArrayIndexOutOfBoundsException (array index out of bound)

• The Error class defines serious error conditions (that your program should not try to recover from)o Examples:

OutOfMemory

Page 115: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Exception Classes

• Class hierarchy:Object+--- Throwable +--- Error +--- VirtualMachineError +--- StackOverFlowError +--- OutOfMemoryError +--- Exception +--- RunTimeException +--- ArithmeticException +--- NullPointerException +--- IndexOfBoundsException +--- ArrayIndexOfBoundsException +--- ... +--- IOException +--- FileNotFoundException ... +--- ...

Don’t need to handle these

Page 116: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Exception Handling

• Java provides exception handling facilities to find out what exception was thrown and try to recover

• try and catcho use the try statement with code that might throw an exception that

you are to handleo use the catch statement to specify the exception to catch and the

code to execute when caughto e.g., try {

// code that might throw an exception } catch (SomeExceptionType e) {

// handle exception here }

Page 117: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Exception Handling (2)

• finally statemento defines a block of code that is always executed, regardless of

whether an exception is caught or not.o E.g. [Yellin],

try {startFaucet();waterLawn();

} catch (BrokenPipeExceptionType e) {

// handle exception here} finally {

stopFaucet();}

Page 118: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Exception Handling: Example

try {int x = 0;int y;y = 1/x;

System.out.println(“Testing 123…”);} catch (ArithmeticException e) {

System.out.println(“Div by 0”);} finally {

System.out.println(“Clean Up, always!”);}

System.out.println (“Testing 456…”);

Output:Div by 0Clean Up, always!Testing 456…

Page 119: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

More Exception Handling What if an exception is not caught?

… main(String args[]) { try{ method1(…); } catch (Exception1 e){ // Code to handle exception1

} catch (Exception e){ // Code to handle a generic exception

} finally{ // Code always to be executed

}}

void method1(…) { method2(…);}

void method2(…) { method3(…); // Exception1 thrown // from method3}

uncaught Exception1propagated

Exception1caught

uncaught Exception1propagated

Page 120: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Appendix

Page 121: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Interfaces

• Interfaces are in the Java language mainly to provide much of the functionality of multiple inheritance, but without the difficulties.

• Common usage:o Java guarantees that if you “implement(s)” an interface, you actually

provide the necessary method(s).

• A scenario:o Want Car and Boat to also have “Collectible” behavior

Transportation

Car Boat

Collectible

Page 122: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Interfaces (2)• Definition (of an interface):

o a collection of method signatures (without implementations, always public and abstract) and/or constants (always public, static, and final) that can be added to a class to provide additional behaviors not defined in the class itself or inherited from its superclasses

• Syntax:o // To create an interface:

public interface MyInterface [extends Interface1, Interface2, ...] {// all methods here are defaulted to public and abstract.// all variables here are defaulted to final, static, and public.

}o // To use an interface:

public class MyClass implements MyInterface {// must implements all the methods specified in the interface MyInterface

}

Page 123: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Interfaces (3)

public interface Comparable {

public int compare(Sortable obj);

}

public class Student2 extends Person implements Comparable {

private float gpa;

… // all the methods from Student2 discussed earlier

public int compare(Comparable obj) {

Student2 s = (Student2) obj;

return (gpa < s.gpa)? -1: 1;

}

}

public class Sort {

static void bubbleSort(Comparable [] sortArr) {

for (int i = 0; i < sortArr.length; i++)

for (int j = i; j < sortArr.length; j++) {

Comparable temp = sortArr[i];

if ( temp.compare(sortArr[j]) > 0 ) {

temp = sortArr[j];

sortArr[j] = sortArr[i];

sortArr[i] = temp;

} // if

} // for

} // bubbleSort

} // Sort

Page 124: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Interfaces (4)

public class TestInterface {

public static void main(String args[]) {Student2 stuArr[] = new Student2[10];for (int i = 0; i < stuArr.length; i++) {

int rand = (int) (10 * Math.random());String name = String.valueOf(rand);float gpa = (float) (4 * Math.random());stuArr[i] = new Student2(name, gpa);

}

Sort.bubbleSort(stuArr);

for (int j = 0; j < stuArr.length; j++) stuArr[j].print();

}}

Page 125: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Interfaces (5)

• Notes:o Interfaces are very commonly used in the AWT and

the event model public class MyClass implements ActionListener {

public void actionPerformed(…) { …}

}

o Interfaces can extend multiple interfaces

Page 126: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Wrapper Classes

• Used for wrapping primitive data types so that they can be used as objectsPrimitive data types Wrapper classes

boolean Booleanbyte Bytechar Charactershort Shortint Integerlong Longfloat Floatdouble Double

Page 127: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

Wrapper Classes (cont’d)

• Example:o int myInt = 1;o Integer wrapperInt = new Integer (myInt);o // do something with wrapperInt (e.g., insert it into a Vector)o myInt = wrapperInt.intValue();

o int myInt2 = Integer.valueOf(“12345”).intValue();

Page 128: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

The Vector Class

• Provides methods for working with dynamic arrays of varied elementso Maintains a capacity and capacityIncrement. As elements

are added, storage for the vector increases in chunks the size of the capacityIncrement

o Useful for dynamically storing heterogeneous collection of elements

Page 129: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

The Vector Class (2)

import java.util.*;

public class TestVector {

public static void main(String args[]) {

MyVector v = new MyVector() ;

int digit = 5;

float real = 3.14f;

String s = new String ("Hi there!");

v.addInt(digit);

v.addFloat(real);

v.addString(s);

v.printVector();

}

}

class MyVector extends Vector { public void addInt(int i) {

addElement(new Integer(i)); // requires Object arg } public void addFloat(float f) {

addElement(new Float(f)); } public void addString(String s) {

addElement(s); } public void printVector() { Object o; int length = size();

System.out.println("Number of vector elements is " + length + " and are:"); for (int i = 0; i < length; i++) { o = elementAt(i);

System.out.println(o.toString()); } }}

Page 130: Introduction to Java Dr. Billy Lim Applied Computer Science Department Illinois State University

References

• Java Programming, Sun Microsystems, 1996-99.

• Howell, Developing in Java, IBS, 1996.

• Cornell & Horstmann, Core Java, 2nd Edition, Prentice-Hall, 1997.

• van der Linden, P., Just Java and Beyond, 3rd Edition, Prentice-Hall, 1998.

• http://www.cs.ucla.edu/csd-grads-gs2/decuir/java/