java review rem collier. a statement i have been asked to do these lectures at your request. they...

42
Java Review Rem Collier

Post on 21-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

Java Review

Rem Collier

Page 2: 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

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.– E.g.

• 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!

Page 3: 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

Programming in Java

• In Java, a program generally has the following structure:– Declaring variables/ initializations

• E.g. int balance;

– Processing• reading inputs• process inputs• show output

– Exit the program

Page 4: 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

Data Types – Variables & Initializations

• String for strings of letterse.g. String LastName = “Kim”;

• char for characterse.g. char alphabet = ‘A’;

• byte, short, int, and long for integer numberse.g. int number = 3;

• float & double for real numberse.g. double pi = 3.14159

• boolean for logicale.g. boolean check = true;

Page 5: 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

Expressions and Operators

• Expressions:( ), * ,/ , +, -

• Operators:&& for AND|| for OR ! for NOT== for equal!= for NOT equal

Page 6: 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

Selection Statements

• if statement ex) if (A>B) {System.out.println(“A>B”);

}

• if…else statement ex) if (A>B) {System.out.println(“A>B”);

} else {System.out.println(“A<=B”);

}

• switch Statement ex) switch (A) { case 1: { System.out.println(“A=1”); break; } case 2: { System.out.println(“A=2”); break; } … default: { System.out.println(“A Undefined”); }}

Page 7: 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

Repetitions(while, do while, and for)

• An example adding all numbers between 1 to 100

• Using While:

// Variable Declaration & Initializationint sum = 0;int count = 0;

// Processingwhile (count <= 1000) {

sum = sum + count;count = count +1; //same as count++

}

// OutputSystem.out.println(“Sum: “ + sum);

Page 8: 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

Repetitions(while, do while, and for)

• Using do-while:

// Variable Declaration & Initializationint sum =0; int count =0;

// Processing do {

sum = sum + count;count = count +1; //same as count++

} while (count <=1000);

• Using for:

// Variable Declaration & Initializationint sum =0;

// Processingfor (int count =0; count <= 100; count++) {

sum = sum +count;}

Page 9: 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

Introducing Methods

returnvaluetype modifier methodName 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; }

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

Page 10: 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

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;

}

}

Page 11: 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

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);

}

}

Page 12: 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

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!”);}

Page 13: 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

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);

}}

Page 14: 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

Your Turn…

• How do you write a program that prints:

“I am the coolest programmer”

twenty times on the screen

Page 15: 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

Declaring Array Variables

• Option A:– Syntax:datatype[] arrayname;

– Example:int[] myList;

• Option B:– Syntax:datatype arrayname[];

– Example:int myList[];

Page 16: 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

Creating Arrays

– Syntax:

arrayName = new datatype[arraySize];

– Example:

myList = new int[10];

Page 17: 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

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];

Page 18: 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

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};

Page 19: 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

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;}

Page 20: 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

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.

Page 21: 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

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 pre-written and are provided as part of the Java Application Programming Interfaces (APIs).– See http://java.sun.com/j2se/1.3/docs/api/index.html

• Other classes you must write yourself.

Page 22: 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

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.

Page 23: 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 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 Peter’s 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.

Page 24: 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

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.

Page 25: 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

Class Declaration

class Circle { public double radius = 1.0;

/** * This method calculates the area of the circle. * @return the area of the circle */

public double findArea() { return radius*radius*3.14159; }}

Data attribute

Method

Page 26: 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

Declaring Object Variables

• Syntax:

ClassName objectName;

• Example:

Circle myCircle;

Page 27: 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

Creating Objects

• Syntax:

objectName = new ClassName();

• Example:

myCircle = new Circle();

Page 28: 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

Declaring/Creating Objects in a Single Step

• Syntax:

ClassName objectName = new ClassName();

• Example:

Circle myCircle = new Circle();

Page 29: 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

Accessing Objects

• Referencing the object’s data:– Syntax:objectName.data

– Example:myCircle.radius

• Referencing the object’s method (sending a message): – Syntax:objectName.method(…)

– Example:myCircle.findArea()

Page 30: 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

Constructors

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

• Syntax:

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

}

• Example:

Circle(double r) { radius = r;}

Page 31: 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

Constructors

• 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);

Page 32: 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

Modifiers

By default, the class, variable, or data can beaccessed by any class in the same package.

• publicThe class, data, or method is visible to any class in any package.

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

Page 33: 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

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;

}

}

Page 34: 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

Packages

• 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)java.io Classes that do input and outputjava.net Classes for networkingjava.awt Classes for creating Graphical Interfacesjava.util General Utility Classes

– So, if I want a class that does file input, I look in the input/output (io) package!

Page 35: 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

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:

import java.io.PrintStream;

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

import java.io.*;

This means “any class”

Page 36: 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

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 java.io 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.)

Page 37: 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

System.out

• 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 don’t know where this output comes from!– We don’t need to know – we just need to know where it

goes to (i.e. the screen).

Page 38: 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

Handling User Input

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

System.in

• 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 doesn’t wait for the program to ask for the next character in the stream).

Page 39: 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

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 System.in within an InputStreamReader, we

write:

new InputStreamReader(System.in)

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

new BufferedReader(new InputStreamReader(System.in))

• 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!

Page 40: 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

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(System.in)); 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;

}

Page 41: 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

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 course.com

Page 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

More Help - Websites

• http://java.sun.com– Loads of free tutorials– Java Documentation for all Java classes

• http://java.sun.com/jdc42– Free registration– Tech support, training, articles, resources, links

• http://www.developer.com– Java directory page– Thousands of applets and resources– http://www.gamelan.com– All-around Java resource– References, games, downloads, talk to experts...