Anda di halaman 1dari 42

Java Review

Rem Collier

A Statement
I have been asked to do these Lectures at YOUR request.

They are to help YOU with any Java question that you have.
How to do File Input / Output How to do User Input How to do Searching / Sorting

To succeed, they need YOUR input.

Tell me what problems you are having, and I will try to help you!

Programming in Java
In Java, a program generally has the following structure:
Declaring variables/ initializations
E.g. int balance;

reading inputs process inputs show output

Exit the program

Data Types Variables & Initializations

String for strings of letters e.g. String LastName = Kim; char for characters e.g. char alphabet = A;

byte, short, int, and long for integer numbers e.g. int number = 3;
float & double for real numbers e.g. double pi = 3.14159 boolean for logical e.g. boolean check = true;

Expressions and Operators

( ), * ,/ , +, -

&& || ! == != for for for for for AND OR NOT equal NOT equal

Selection Statements
if statement ex)
if (A>B) { System.out.println(A>B); } if (A>B) { System.out.println(A>B); } else { System.out.println(A<=B); }
switch (A) { case 1: { System.out.println(A=1); break; } case 2: { System.out.println(A=2); break; } default: { System.out.println(A Undefined); } }

ifelse statement ex)

switch Statement


Repetitions(while, do while, and for)

An example adding all numbers between 1 to 100

Using While:
// Variable Declaration & Initialization int sum = 0; int count = 0; // Processing while (count <= 1000) { sum = sum + count; count = count +1; //same as count++ } // Output System.out.println(Sum: + sum);

Repetitions(while, do while, and for)

Using do-while:
// Variable Declaration & Initialization int sum =0; int count =0; // Processing do { sum = sum + count; count = count +1; //same as count++ } while (count <=1000);

Using for:
// Variable Declaration & Initialization int sum =0; // Processing for (int count =0; count <= 100; count++) sum = sum +count; } {

Introducing Methods
Method Structure
returnvaluetype methodName

A method is a collection of statements that are grouped together to perform an operation.


parameter list

public static double readDouble() { double d = 0.0; try { String str = df.readLine(); st = new StringTokenizer (str); d = new Double (st.nextToken()).doubleValue(); } catch (IOException ex) { System.out.println(ex); } return d; }

Declaring Methods
/** * This method returns the maximum of two numbers * @param num1 the first number * @param num2 the second number * @return either num1 or num2 */ int max(int num1, int num2) { if (num1 > num2) { return num1; } else { return num2; } }

Passing Parameters
/** * This method prints a message a specified number * of times. * @param message the message to be printed * @param n the number of times the message is to be * printed */ void nPrintln(String message, int n) { for (int i=0; i<n; i++) { System.out.println(message); } }

The main method

One of these methods is required for every program you write.
If your program does not have one, then you cannot run it.

The main method has a very specific syntax:

public static void main(String[] args) { // Your code goes here! }

For example:
public static void main(String[] args) { System.out.println(Hello World!); }

An Example Program
class MyProgram { /** * This method prints a message a specified number * of times. * @param message the message to be printed * @param n the number of times the message is to be * printed */ void nPrintln(String message, int n) { for (int i=0; i<n; i++) { System.out.println(message); } } public static void main(String[] args) { nPrintln(Hello World!, 10); } }

Your Turn
How do you write a program that prints:

I am the coolest programmer

twenty times on the screen

Declaring Array Variables

Option A:
datatype[] arrayname;

int[] myList;

Option B:
Syntax: datatype arrayname[]; Example: int myList[];

Creating Arrays
arrayName = new datatype[arraySize];

myList = new int[10];

Declaring and Creating in One Step

Option A:
Syntax: datatype[] arrayname = new datatype[arraySize]; Example: double[] myList = new double[10];

Option B:
Syntax: datatype arrayname[] = new datatype[arraySize]; Example: double myList[] = new double[10];

Initializing Arrays
Using a loop:
for (int i = 0; i < myList.length; i++) { myList[i] = (double)i; }

Declaring, creating, and initializing in one step:

double[] myList = {1.9, 2.9, 3.4, 3.5};

Searching Arrays
/** * This method searches a specified array for a value. * @param array the array to be searched * @param value the value to be searched for * @return true if the value is in the array, false * otherwise */ boolean contains(double[] array, double value) { boolean found = false; int index = 0; while ((index <= array.length) && !found) { if (array[index] == value) { found = true; } } return found; }

Again, your turn

How do you write a program that searches through the following list of numbers: 23.2, 12.1, 34.3, 6.8, 4.0, 34.5, 22.7, 313.6, 12.5, 81.2, 56.3, 363.3, 135.5, 176.4, 5.3, 44.2, 76.5, 29.1, 2.7, 24.5, -42.0, 23.19, -200.4, 0.0, 9.9, 564.3, 235.0, 83.16, 43.38, 1.2, 18.16 to see whether 2.7 is in the list. Now write a program to check whether 8.1 is in the same list.

Object-Oriented Programming in Java

Java programs are formed from a set of classes.
A class is a container for code. Whenever you create a program, you write your code inside one or more classes.

Some of the classes you will use in your programs are prewritten and are provided as part of the Java Application Programming Interfaces (APIs).

Other classes you must write yourself.

Object-Oriented Programming in Java

When we run a Java Program, we may create objects.

Objects are instances of classes.

Classes describes a general set of features. Objects specify concrete values for those features.

For example:
Let us start with a general description of a car:
A Car has four wheels, an engine, a chassis, a colour, some doors

The next two descriptions refer to particular cars.

My car is brown and has a 2 litre engine, a Saab chassis, and five doors. Peter has a yellow car with a 1.4 litre engine, a VW Polo chassis, and three doors.

How does this relate to Java?

The general description of a Car is like a class in Java a general description of what constitutes a car. Both my car and Peters car are described in terms of the general description of a car (i.e. the colour, engine size, chassis type, number of doors). These particular cars are like objects in Java - a concrete instance of the general description of a Car. Note: The number of wheels is the same for all cars.
We call things that are the same for all cars constants.

Data Attributes Methods, and Messages

Classes contain two types of feature:
Data attributes describe the information that a class contains (for example the colour of a car, the type of chassis, etc.) Methods describe operations that can be performed by instances (objects) of the class (for example, a Bank Account class may include methods to withdraw or deposit cash).

To get an object to perform a method we send a message:

This message must be sent to that object identifying the method to be performed. This message should also include any data (parameters) required by the method.

Class Declaration
class Circle { public double radius = 1.0;

Data attribute

/** * This method calculates the area of the circle. * @return the area of the circle */ public double findArea() { Method return radius*radius*3.14159; }

Declaring Object Variables

ClassName objectName;

Circle myCircle;

Creating Objects
objectName = new ClassName();

myCircle = new Circle();

Declaring/Creating Objects in a Single Step

ClassName objectName = new ClassName();

Circle myCircle = new Circle();

Accessing Objects
Referencing the objects data:


Referencing the objects method (sending a message):



Constructors are special methods that are called upon creation of an object.
Their purpose is to initialise objects as they are created.

ClassName() { // Initialisation code goes here! }

Example: Circle(double r) { radius = r; }

Example (cont):
Circle() { radius = 1.0; }

We can specify which constructor to use when we create a new object. Example:
myCircle = new Circle(5.0);

By default, the class, variable, or data can be accessed by any class in the same package.
The class, data, or method is visible to any class in any package.

The data or methods can be accessed only by the declaring class.

An Example Program
class TestCircle { public static void main(String[] args) { Circle myCircle = new Circle(); System.out.println("The area of the circle of radius " + myCircle.radius + " is " + myCircle.findArea()); } }

class Circle { double radius = 1.0;

/** * This method calculates the area of the circle. * @return the area of the circle */ double findArea() { return radius*radius*3.14159; } }

There are thousands (if not tens of thousands) of Java classes.
Finding the right one can be difficult (i.e. I want a class that does file input) Finding a meaningful name can be difficult (think of yahoo usernames!)

Packages are used to organise Java classes.

Packages are like domain names they are hierarchical (e.g. packages can have sub-packages, which can have sub-packages, and so on). There are five basic Java packages: java.lang Classes that are part of the basic language (e.g. Strings) Classes that do input and output Classes for networking java.awt Classes for creating Graphical Interfaces java.util General Utility Classes So, if I want a class that does file input, I look in the input/output (io) package!

Referencing Classes in Different Packages

If we want to use a class that is in a package (with the exception of those in the java.lang package), we need to declare our intention at the top of the program. We do this with an import statement
For example:

If we want to use multiple classes from a single package we can use the following statement:

This means any class

Some Useful Java Classes

One of the most useful sets of Java classes are the input/output (io) classes.
These classes are located in the package and are part of the default Java API.
These classes allow programs to perform input/output in a variety of ways.

There are many different types of io class.

You are not expected to know them all intimately, but you should know how to do a few basic things with them (e.g. User input, File input/output, etc.)

You have already used an io class implicitly when you write information to the screen. System.out refers to a data attribute of the System class.
This attribute is an instance of the class PrintStream. This class is used for output only.

The PrintStream class includes a method, println, that prints a string to the specified output.
We dont know where this output comes from! We dont need to know we just need to know where it goes to (i.e. the screen).

Handling User Input

To get input from the user, we use another data attribute of the System class:

This attribute is an instance of the InputStream class.

The InputStream class is not easy to use (it works only with bytes). To make things easier, we can wrap the input stream in other io classes.

In particular, we use two classes:

InputStreamReader. This class converts the byte stream into a character stream (this is much more useful honestly!). BufferedReader. This class buffers data from the enwrapped stream, allowing smoother reading of the stream (it doesnt wait for the program to ask for the next character in the stream).

Handling User Input

To wrap an io object, we create a new io object, passing the old io object into the constructor.
For example, to wrap within an InputStreamReader, we write:
new InputStreamReader(

To use the BufferedReader (which, remember, is an optimisation), we wrap the InputStreamReader object we created above.
For example:
new BufferedReader(new InputStreamReader(

Once we have a BufferedReader, we can use a nice method it provides called readLine() which reads a line of text!
This makes life much easier!

Handling User Input

Now that we have a way of reading a line of text from the System input stream (i.e. the keyboard), how do we use it?
public String readString() { BufferedReader in = new BufferedReader( new InputStreamReader(; String line = null; try { line = in.readLine(); while (line == null) { line = in.readLine(); } } catch (IOException ie) { System.out.println(The following problem occurred + when reading input: + ie); } return line; }

More Help - Books

Java How to Program by Deitel & Deitel

Introduction to Java Programming by Daniel Liang

An Introduction to Java programming with Java by Thomas Wu Easier books can be found in

More Help - Websites
Loads of free tutorials Java Documentation for all Java classes
Free registration Tech support, training, articles, resources, links
Java directory page Thousands of applets and resources All-around Java resource References, games, downloads, talk to experts...