advanced java programming cse 7345/5345/ ntu 531

Post on 19-Jan-2016

62 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Welcome Back!!!. Advanced Java Programming CSE 7345/5345/ NTU 531. Session 3. Office Hours: by appt 3:30pm-4:30pm SIC 353. Chantale Laurent-Rice. Welcome Back!!!. trice75447@aol.com. claurent@engr.smu.edu. Introduction. Chapter 4 Methods. Chapter 4 Methods. Introducing Methods - PowerPoint PPT Presentation

TRANSCRIPT

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Advanced Java Programming

CSE 7345/5345/ NTU 531Session 3

Welcome Welcome Back!!!Back!!!

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

claurent@engr.smu.educlaurent@engr.smu.edu

Chantale Laurent-

Rice

Welcome Welcome Back!!!Back!!!

trice75447@aol.comtrice75447@aol.com

Office Hours:by appt3:30pm-4:30pmSIC 353

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Introduction

• Chapter 4– Methods

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Chapter 4 Methods• Introducing Methods

– Benefits of methods, Declaring Methods, and Calling Methods

• Passing Parameters– Pass by Value

• Overloading Methods– Ambiguous Invocation

• Scope of Local Variables

• Method Abstraction

• The Math Class

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Introducing MethodsMethod Structure

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

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods• A method is essentially a set of program

statements. It forms the fundamental unit of execution in Java. Each method exists as part of a class.During the execution of a program, methods may invoke other methods in the same or a different class.  No program code can exist outside a method, and no method can exist outside a class.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Using Methods For example:

public class TheMethod{

public static void main(String[] args){

System.out.println(“First method”);}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Using Methods You can place additional methods outside the main( )

method.public class TheMethod{

public static void main(String[] args){

System.out.println("First method");OutsideMainMethod();AnotherClass.OtherOutsideMethod();

}public static void OutsideMainMethod(){

System.out.println("The outside method");

}}//Save as: TheMethod.java

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Calling a method from

another class Step 1- call it inside main( ) using the dot operator.public class TheMethod{public static void main(String[] args){System.out.println("First method");OutsideMainMethod();OtherMethod.OtherOutsideMethod();}public static void OutsideMainMethod(){System.out.println("The outside method");}}//Save as: TheMethod.java

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Calling a method from

another class • 2 steps:1- create another method outside main( )  public class AnotherClass {

public static void main(String[] args){

System.out.println("Yes!");OtherOutsideMethod();

} public static void OtherOutsideMethod() {

System.out.println("Hello I am here");}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods that require a single argument• Arguments are communication from you to a method.

 • When Java passes an argument into a method call, it

is actually a copy of the argument that gets passed. • For example: • 1- double radians = 1.2345;• 2- System.out.println("Sine of " + radians +

" = " + Math.sin(radians));

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods that require a single argument

• The variable radians contains a pattern of bits that represents the number 1.2345.

• On line 2, a copy of this bit pattern is passed into the Java Virtual Machine's method-calling apparatus.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods that require a single argument

• When an argument is passed into a method, changes to the argument value by the method do not affect the original data.

• For example:• 1- public void bumper(int

bumpMe)• 2- bumpMe += 15;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Line 2 modifies a copy of the

parameter passed by the caller. • For example:• 1- int xx = 12345;• 2- bumper(xx);• 3- System.out.println("Now xx is " + xx);•  • On line 2, the caller's xx is copied; the copy is

passed into the bumper( ) method and incremented by 15.

• Since the original xx is untouched, line 3 will report that xx is still 12345.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

All methods are passed by value.

• All methods are passed by value. This means that copies of the arguments are provided to a method.

 • Any changes to those copies are not

visible outside the method.

• This situation changes when an array or object is passed as an argument.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

call-by-value argument passing

• In this case the entire array or object is not actually copied.

• Instead, only a copy of the reference is provided.

• Therefore, any changes to the array or object are visible outside the method.

• However, the reference itself is passed by value.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

call-by-value argument passing

• Method a( ) accepts three arguments:

• an int• an int array• an object reference

The value of these arguments are displayed before and after the method call.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

call-by-value argument passing

• The key points to note are:

• The change to the first argument is not visible to the main( ) method.

• The changes to the array and object are visible to the main( ) method.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example:public class CallByValue{

public static void main(String[] args){

// Initializes variablesint i = 5;int j[] = { 1, 2, 3, 4, };StringBuffer sb = new StringBuffer("abcd");

 // Display variablesdisplay(i, j, sb);

 // call methoda(i, j, sb);

 //Display variables againdisplay(i, j, sb);

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example (con’t)public static void a(int i, int j[], StringBuffer sb){

i = 7;j[0] =11;sb.append("fghi");

}public static void display(int i, int j[], StringBuffer sb){

System.out.println(i);for (int index = 0; index < j.length; index++)

System.out.print(j[index] + " ");System.out.println(" ");System.out.println(sb);

}} 

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example// TestMax.java: demonstrate using the max method public class TestMax {

/** Main method */ public static void main(String[] args) {

int i = 5; int j = 2; int k = max(i, j); System.out.println("The maximum between " + i + " and " + j + " is " + k);

} /** Return the max between two numbers */ public static int max(int num1, int num2) {

int result; if (num1 > num2)

result = num1; else result = num2; return result; }

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Output

• Output• 5• 1 2 3 4 • abdce• 5• 11 2 3 4• abcdefghij

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Calling Methods, cont.

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

pass i pass j

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Calling Methods, cont.

The main method i: j: k:

The max method num1: num2: result:

pass 5

5

2

5

5

2

5

pass 2 parameters

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

CAUTIONA return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }

To fix this problem, delete if (n<0) in the code.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Passing Parameters

public static void nPrintln(String message, int n) {

for (int i = 0; i < n; i++) System.out.println(message);}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods that return Values.

The return type for a method can be used in the Java

 • The return type for a method can be

any type used in the Java programming language, which includes the primitive (or scalar) types int, double, char, and so on, as well as class type (including class types you create).

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods that return valuespublic class GettingARaise{

public static void main(String[] args){

double mySalary = 200.00;

System.out.println("Demonstrating some raises");

predictRaise(mySalary);System.out.println("Demonstrating my salary " +

mySalary);predictRaise(400.00);predictRaiseGivenIncrease(600, 800);

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Methods that return values public static void predictRaise(double moneyAmount) {

double newAmount;newAmount = moneyAmount * 1.10;System.out.println("With raise salary is " +

newAmount);}

public static void predictRaiseGivenIncrease(double moneyAmount, double percentRate){

double newAmount;newAmount = moneyAmount * (1 + percentRate);System.out.println("With raise predicted given salary is

" + newAmount);}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Method Overloaded

• Java allows you to declare several methods in a class with the same name, as long as each method has a set of parameters that is unique.

• This is called method overloading.

• The following application contains three forms of the move() method.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Examplepublic class MethodOverloaded{

double x;double y;double z;

MethodOverloaded(double x){

this(x, 0, 0) }

MethodOverloaded(double x, double y){

this(x, y, 0);}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example….contMethodOverloaded(double x, double y, double z){

this.x = x;this.y = y;this.z = z;

}

// This first move form translates the point along the x-axis.

void move(double x){

this.x = x;}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example… cont// This second form updates the x and y

coordinatesvoid move(double x, double y){

this.x = x;this.y = y;

}// This last form modifies all coordinatesvoid move(double x, double y, double z){

this.x = x;this.y = y;this.z = z;

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Examplepublic class OverloadMethods1{

public static void main(String[] args){

Point3D p = new Point3D(1.1, 3.4, -2.8);p.move(5);System.out.println("p.x = " + p.x);System.out.println("p.y = " + p.y);System.out.println("p.z = " + p.z);

p.move(6, 6);System.out.println("p.x = " + p.x);System.out.println("p.y = " + p.y);System.out.println("p.z = " + p.z);

p.move(7, 7, 7);System.out.println("p.x = " + p.x);System.out.println("p.y = " + p.y);System.out.println("p.z = " + p.z);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Call by Value/Reference

• All methods are passed by value. This means that copies of the arguments are provided to a method.

• Any changes to those copies are not visible outside the method.

• This is easy to understand for simple types.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Call by Value/Reference • The situation changes when an array or

object is passed as an argument. • In this case the entire array or object is

not actually copied. • Instead, only a copy of the reference is

provided. • Therefore, any changes to the array or

object are visible outside the method. • However, the reference itself is passed

by value.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Call by Value/Reference

• As a point of interest, arguments are passed on the stack.

• They are pushed on the stacked when a method is called and popped off the stack when it returns.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Examplepublic class CallByValue{

public static void main(String[] args){

// Initialize variables

int i =5;int j[ ] ={1, 2, 3, 4 };StringBuffer sb = new StringBuffer("abdce");

 // Display variablesdisplay(i, j, sb);

// Call methoda(i, j, sb);

// Display variables againdisplay(i, j, sb);}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example…contpublic static void a(int i, int j[ ], StringBuffer sb)

{i = 7;j[0] = 11;sb.append("fghi");

public static void display(int i, int j[ ], StringBuffer sb){

System.out.println(i);for (int index = 0; index < j.length; index++)

System.out.print(j[index] + " " );System.out.println("");System.out.println(sb);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Chapt 5One-Dimensional Array

• A one-Dimensional array is a list of variables of the same type that are accessed through a common name.

• An individual variable in the array is called array element.

• Arrays form a convenient way to handle groups of related data.

• For example, you might use an array to hold the average daily temperature over a 30-day period.

• Using an array to represent this data allows you to easily manipulate it.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

One-Dimensional Array• To create an array, you need to perform two steps:• 1. declare the array and• type varName[ ];• ex: int ia[ ];• This creates a variable named ia that refers to an

integer array. But it does not actually create storage for the array.

•  • 2. allocate space for its elements.• varName = new type[size];• Here, varName is the name of the array, type is a valid

Java type, and size specifies the number of elements in the array. You can see that the new operator is used here to allocate memory for the array.

• ex: is = new int[10];• This creates an integer array with 10 elements that

may be accessed via ia.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example…cont

public static void display(int x[ ]){

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

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example• These two steps may be combined into one Java

statement as shown here:type varName = new type[size];for example:int ia = new int[10];

ia[0]ia[1]ia[2]ia[3]ia[4]ia[5]ia[6]ia[7]ia[8]

ia[9]

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Examplepublic class ArrayArgument{

public static void main(String[ ] args){

// Initialize vaviablesint x[ ] = { 11, 12, 13, 14, 15};

// Display variablesdisplay(x);

 //Call methodchange(x);

}

public static void change(int x[ ]){

int y[ ] = { 21, 22, 23, 24, 25);x = y;

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Structure of one-dimensional array• The figure above represents the structure of

a one-dimensional array that has ten elements.

• Once an array has been created, an individual element is accessed by indexing the array. This is done by specifying the number of the desired element inside square brackects.

• Array indexed begin at zero.• This mean that if you want to access the first

element in an array, use the zero for the index.

• For example, •  • ia[2] = 10;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Structure One-Dimensional array

• This assigns the value 10 to the third element of ia.

• Remember, array indexes begins at zero, so ia[2] refers to the third element.

•  • In Java, the number of elements in an

array may be obtained via the following expression:

•  • varName.length.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Pass by value of an array

• The following program illustrates that references to arrays are passed by value.

• An int array named x is created in the main( ) method and passed as an argument to the change( ) method.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Pass-by value to an array

• The change( ) method modifies it copy of the argument.

• However, this modification is not visible to the caller. The display( ) method is called immediately before and after the change( ) method is invoked.

• As expected, its output is the same in both cases.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Arrays of objects

• The steps to accomplish this are the same for arrays of simple types.1. Declare the array and2. Allocate space for the array elements.

• The elements can then be initialized.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example:This example shows how to create an array of five

strings. public class StringArray{

public static void main(String[] args){

String array[] = new String[5];array[0] = "String 0";array[1] = "String 1";array[2] = "String 2";array[4] = "String 4";System.out.println(array.length);System.out.println(array[0];System.out.println(array[1];System.out.println(array[2];System.out.println(array[3];System.out.println(array[4];

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Array String con’t

• Notice that the array at index 3 was not explicitly initialized to reference an object.

• Therefore, it is equal to null as seen in the output.

• The null indicates that the variable does not currently refer to any object.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

This example creates an array of five strings,

calculates their average size, and display the value. public class StringAverage{

public static void main(String[] args){

String array[] = new String[5];array[0] = "Short string";array[1] = "A much longer string";array[2] = "This is a complete sentence";array[3] = "Token";array[4] = "This is the longest element in the " + array";int total = array[0].length();total = total + array[1].length();total = total + array[2].length();total = total + array[3].length();total = total + array[4].length();System.out.println("The average string size is " + total/5);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Arrays command-line args

• This method takes one argument that is an array of String objects. These objects represent any arguments that may have been entered by the user on the command line.

• The number of command -line arguments is obtained via the expression args.length. This is an int type. The individual arguments are accessed as args[0], args[1], args[2], and so forth.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

• public class CommandLineArgument{

public static void main(String[] args){System.out.println("argslength = " args.length);System.out.println("args[0] = " + args[0]);System.out.println("args[1] = " + args[1]);System.out.println("args[2] = " + args[2]);}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Invoking command-line args

• You may invoke this application from the command line as follows:

 • java CommandLineArguments 1 2

abcde

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Command-Line arguments that converts to integers

• public class Add2Integer{

public static void main(String[] args){

// Get first integerint i = Integer.parseInt(args[0]);

 //Get the second integerint j = Integer.parseInt(args[1]);

 //Display their sumint sum = i + j;System.out.print("Sum is " + sum);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Invoking command-line args

• You may invoke this application from the command line as follows:

• java Add2integers 1 2

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Copy an array to another array

•This illustrates the use of the arraycopy( ) method.

•Five elements are copied from array1 to array2. The ten elements in array 2 are then displayed

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example• public class ArrayCopy

{public static void main(String[] args){

int array1[] = { 0, 1, 2, 3, 4};int array2[] = { 0, 0, 0, 0, 0};System.arraycopy(array1, 0, array2, 0, 5);System.out.print("array2: ");System.out.print(array2[0] + " ");System.out.print(array2[0] + " ");System.out.print(array2[0] + " ");System.out.print(array2[0] + " ");System.out.print(array2[0] + " ");System.out.print(array2[0] + " ");System.out.println(array2(5);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

This example creates an array of five strings, calculates their average size, and display the

value. public class StringAverage{

public static void main(String[] args){String array[] = new String[5];array[0] = "Short string";array[1] = "A much longer string";array[2] = "This is a complete sentence";array[3] = "Token";array[4] = "This is the longest element in the " + “array";int total = array[0].length();total = total + array[1].length();total = total + array[2].length();total = total + array[3].length();total = total + array[4].length();System.out.println("The average string size is " + total/5); }}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example con’ttotal = total + array[3].length();total = total + array[4].length();System.out.println("The total string size is " + total);System.out.println("The average string size is " + total/5); System.out.println("The array1 length size is "

+ array[0].length());}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The Length of Arrays• Once an array is created, its size is fixed. It

cannot be changed. You can find its size using

arrayVariable.length

For example,myList.length returns 10

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

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

• Declaring, creating, initializing in one step:double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one statement.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Declaring, creating, initializing Using the Shorthand Notation

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

This shorthand notation is equivalent to the following statements:double[] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

CAUTIONUsing the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong:double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Copying ArraysUsing a loop:

int[] sourceArray = {2, 3, 1, 5, 10};

int[] targetArray = new int[sourceArray.length];

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

targetArray[i] = sourceArray[i];

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Multidimensional ArraysDeclaring Variables of Multidimensional Arrays and Creating Multidimensional Arrays

int[][] matrix = new int[10][10]; orint matrix[][] = new int[10][10];matrix[0][0] = 3;

for (int i=0; i<matrix.length; i++) for (int j=0; j<matrix[i].length; j++) { matrix[i][j] = (int)(Math.random()*1000); }

double[][] x;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Multidimensional Array Illustration

0 1 2 3 4

0

7

0 1 2 3 4

1 2 3 4

0 1 2 3 4 matrix[2][1] = 7;

matrix = new int[5][5];

3

7

0 1 2

0 1 2

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

1

2

3

4

5

6

8

9

10

11

12

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Declaring, Creating, and Initializing Using Shorthand Notations

You can also use a shorthand notation to declare, create and initialize a two-dimensional array. For example,

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

This is equivalent to the following statements: int[][] array = new int[4][3];array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Lengths of Multidimensional Arrays

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

array.lengtharray[0].lengtharray[1].lengtharray[2].length

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Ragged ArraysEach row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example,

int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5}};

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Read / Work With (Course Links)

• Liang, Nutshell Chapter 6-8• Life Cycle of Applets• List Of Basic Tags• Try It Editor

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Using ClassesChapter 6

• A Class is a template from which objects are created.

• That is, objects are instances of a class.

• The mechanism to create a new object is called instantiation.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Question....

• What does it mean by "instances of a class"?

• Give examples.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Question....

• How do you instantiated?

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

A class may contain three types of items:

• 1. variable• 2. methods• 3. constructors

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

A class may contain three types of items:

• Variables- represent its state.• Methods- provide the logic that

constitutes the behavior defined by a class.

• Constructors- initialize the state of a new instance

of a class.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

A simplified form of a class declaration is shown below:

• public className• {• // instance variable declarations• type1 varName1 = value1;• type2 varName2 = value2;• ....• typeN varNameN = valueN;

• // constructors• clasName(cparams1)• {• // body of constructor• }•

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

A simplified form of a class (con’t)clasName(cparams2)

{// body of constructor

}

clasName(cparamsN){

// body of constructor}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

A simplified form of a class (con’t)// Methods

rtype1 mthName1(mparams1){

// body of method }

rtype2 mthName2(mparams2){

// body of method } rtypeN mthNameN(mparamsN)

{// body of method

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class

• The keyword class indicates that a class names clsName is being declared.

• This name must follow the Java naming conventions for identifiers.

• The instance variables named varName1 through varNameN are included using the normal variable declaration syntax.

• Each variable must be assigned a type shown as type1 through typeN and may be initialized to a value as shown as value1 through valueN.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Class (con’t)• The initialization is optional.

• Constructors always have the same name as the class. They do not have return values. Their optional parameter lists are cparams1 through cparamsN.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating Simple classes

• // cannot have a class with public• public class TheCLass• {• double x;• double y;• double z;• }

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Creating Simple classespublic class TheCLassExample{

public static void main(String[] args){

TheCLassExample p = new TheCLassExample();

p.y = 3.4;p.z = -2.8;System.out.println("p.x = " + p.x);System.out.println("p.y = " + p.y);System.out.println("p.z = " + p.z);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Adding….

• // Correct way• class TheClassExample• {• double x;• double y;• double z;• }

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Adding...public class TheClassExample{

public static void main(String[] args){

TheClassExample p = new TheClassExample();

// point p1p1.x = 1.1;p1.y = 3.4;p1.z = -2.8;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Adding...// point p2

p2.x = 100.1;p2.y = 303.4;p2.z = -202.8;System.out.println("p.x = " + p.x);System.out.println("p.z = " + p.z);System.out.println("p.x = " + p.x);System.out.println("p.y = " + p.y);System.out.println("p.z = " + p.z);

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Read / Work With (Course Links)

• Liang, Nutshell Chapter 6-7• Life Cycle of Applets• List Of Basic Tags• Try It Editor

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Chapter 7 The StringBuffer Class

• There is no way to change the character sequence encapsulated by String object after it is created.

• The StringBuffer class also encapsulates a sequence of characters.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Its constructor has the following forms:

• /* This form of the constructor initializes the buffer size to 16 character*/

StringBuffer( )

• /*This form explicitly sets the buffer capacity to size characters*/

StringBuffer(int size)  • /*This form initializes the buffer with the contents of s

and also reserves another 16 characters for expansion*/

StringBuffer String s)

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Create StringBuffer objects

• This example creates StringBuffer objects by using the three form of constructors and displays their current capacity and sizes.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Examplepublic class StringBufferExample{

public static void main(String[] args){

StringBuffer sb1 = new StringBuffer( );StringBuffer sb2 = new StringBuffer(30 );StringBuffer sb3 = new StringBuffer("abcde" );

 System.out.println("sb1.capacity = " + sb1.capacity( ));

System.out.println("sb2.capacity = " + sb2.capacity( ));

System.out.println("sb3.capacity = " + sb3.capacity( )); 

System.out.println("sb3.length = " + sb3.length( ));}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Input/output selection

• Introducing Java's Control Statements • The if Statement • The if statement is one of Java's selection statements

(sometimes called conditional statements). Its operation is government by one of the outcome of a conditional test that evaluates to either true or false. Simply put, selection statements make decisions based upon the outcome of some condition.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

If Statement

• if(expr)statement• Here, expr is any expression that evaluates to a boolean

value. If the expression evaluates as true, the statement will be executed. Otherwise, the statement is bypassed, and the line of code following the if is executed.

• The statement that follows an if is usually referred to as the target if the if statement.

 • The expression inside if typically compares one value with

another by using a relational operator. (See page 144 of your book)

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

• if (10 > 9)System.out.println("true");

  

public class IfDemo{

public static void main(String[] args){

if (args.length = = 0)System.out.println("You must have

command line argument");}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Remember

• Remember, a number is not a boolean. Therefore, it is not valid to have an if statement such as the following:

 if (count + 1)

System.out.println("Not Zero"); Such a line generates a compiler error.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

If-else statement

public class IfDemo{

public static void main(String[] args){

if (args.length = = 0)System.out.println("You must have

command line argument");else System.out.prinltn(“not good”);}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The for statement

• The for loop is one of Java's three loop statements. It allows one or more statements to be repeated and is considered by many Java programmers to be its most flexible loop.

• Although the for loop allows a large number of variations, we will examine only its most common form.

 • The for loop is used to repeat a statement or block of

statements a specified number of times. its general form for repeating a single statement is as followed:

• for(initialization; test; increment) statement;

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The for loop

• The initialization section typically gives an initial value to the variable that controls the loop. This variable is usually referred to as the loop-control variable. The initialization section is executed only once, before the loop begins.

 

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The for Statement

• The test section of the loop typically tests the loop-control variable against a target value. If the test evaluates true, the loop repeats. If it is false, the loop stops, and the program execution picks up with the next line of code that follows the loop. The test is performed at the start or top of the loop each time the loop is repeated.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The for loop

• The increment section of the for is executed at the bottom of the loop. That is, the increment portion is executed after the statement or block that forms its body has been executed. The purpose of the increment portion is typically to increase (or decrease) the loop-control variable by a certain amount.

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Example

• public class ForLoop{

public static void main(String[] args){

for (int num = 1; num < 11; num = num + 1)

System.out.print(num + " ");System.out.println("terminating");

}}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The Increment operators

• public class ForLoop{

public static void main(String[] args){

for (int num = 1; num < 11; num ++)System.out.print(num + " ");

System.out.println("terminating");}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

The decrement operators

• public class ForLoop{

public static void main(String[] args){

for (int num = 1; num < 11; num --)System.out.print(num + " ");

System.out.println("terminating");}

}

Liang, Oreilly, Herbert Schildt, Joseph O’Neil

Read / Work With (Course Links)

• Liang, Nutshell Chapter 8-9• Life Cycle of Applets• List Of Basic Tags• Try It Editor

top related