chapter 2 - william paterson university  · web viewc:\program files\java\jdk1.8.0_25\bin (where...

337
Introduction to Java Programming Language Introduction Java is an imperative-based object-oriented programming language introduced by Sun Microsystems (which is now a subsidiary of Oracle) in 1995. Its syntax is derived from C and C++ but it has a simpler object model and fewer low low-level facilities. It was first created for developing software for embedded consumer electronic, such as toasters, microwave ovens, and interactive TV systems. But today, it is mostly used to develop software for networking, mobile devices, multimedia, games, web-based content and enterprise software. Java applications are typically compiled to an intermediate representation called bytecode that can run (be interpreted) on any Java Virtual Machine (JVM) regardless of computer architecture. In order to speed up the execution of java bytecode, Just-in-Time compilers are provided to translate the bytecode of a method into machine language when it is called for the first time during the execution of the program. You need to install the Java Runtime Environment (JRE) on your computer in order to execute java applications. It consists of the Java Virtual Machine (JVM), the Java core classes, and the supporting Java class libraries also known as the Java APIs (Applications Program Interfaces). You need a Java development environment or an integrated development environment (IDE) in order to create, compile, and execute Java applications. The latest version of the Java development environ provided by Sun © 2011 Gilbert Ndjatou Page 1

Upload: others

Post on 24-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Chapter 2

Introduction to Java Programming Language

Introduction

· Java is an imperative-based object-oriented programming language introduced by Sun Microsystems (which is now a subsidiary of Oracle) in 1995.

· Its syntax is derived from C and C++ but it has a simpler object model and fewer low low-level facilities.

· It was first created for developing software for embedded consumer electronic, such as toasters, microwave ovens, and interactive TV systems. But today, it is mostly used to develop software for networking, mobile devices, multimedia, games, web-based content and enterprise software.

· Java applications are typically compiled to an intermediate representation called bytecode that can run (be interpreted) on any Java Virtual Machine (JVM) regardless of computer architecture.

· In order to speed up the execution of java bytecode, Just-in-Time compilers are provided to translate the bytecode of a method into machine language when it is called for the first time during the execution of the program.

· You need to install the Java Runtime Environment (JRE) on your computer in order to execute java applications. It consists of the Java Virtual Machine (JVM), the Java core classes, and the supporting Java class libraries also known as the Java APIs (Applications Program Interfaces).

· You need a Java development environment or an integrated development environment (IDE) in order to create, compile, and execute Java applications.

· The latest version of the Java development environ provided by Sun Microsystems is Java SE Development Kit 8 (JDK8) that can be downloaded from the web site java.sun.com/javase/downloads/.

· IDEs provide tools that support the software development process, including editors, and debuggers. Popular IDEs include Eclipse (www.eclipse.org) and Netbeans (www.netbeans.org).

Elements of Java Programming Language

Comments

· Comments are the same as in C++.

Examples

/*-- Program to add two integer values --*/

// read the values

Identifiers

A. Rules for writing valid identifiers:

1. In Java, a letter denoted by L is defined as: ‘a’ to ‘z’, ‘A’ to ‘Z’, the underscore character ‘_’ or any Unicode character that denotes a letter in a language.

2. A digit denoted by D is defined as ‘0’ to ‘9’ or any Unicode character that denotes a digit in a language.

3. An identifier is defined as:(L | $)(L | D | $)*

4. However, by convention, user-defined identifiers do not start with the dollar sign ‘$’ or the underscore ‘_’ and the dollar sign ‘$’ is never used for user-defined identifiers.

5. C++ conventions for identifiers are also used in Java: use of the underscore character as a connector or start the second word with an uppercase letter. Examples: gross_pay, grossPay.

6. An identifier cannot be a Java Keyword. Java keywords are provided in Appendix 1.

7. Uppercase and lowercase letters are different.

Constant Data

· There are six types of constant data in Java:

· Boolean constants

· character constants,

· integer constants,

· floating-point constants,

· strings constants, and

· Special constants

Boolean Constants

· Boolean constants are the same as in C++:true and false.

· However, 0 is not false and anything else is not true as in C++.

Character Constants

· A character constant is either a single printable Unicode character enclosed between single quotes, or an escape sequence enclosed between single quotes.

Examples of printable characters:'A', '$', '8', ‘ ’ (space bar), 'z'.

Examples of escape sequences:'\n', '\t',

'\'', '\\', ‘\”’.

· Escape sequences are used to represent characters that you can not type from the keyboard or characters that have a meaning for the compiler such as single quote, double quote, . . ., etc.

· Unicode characters that you cannot type from the keyboard may be specified using a Unicode escape sequence in the form: \uXXXXwhere XXXX represents the hexadecimal code of that character.

Examples

‘\u00EA’ forê

and ‘\u00A5’

for ¥

Integer Constants

· Integer constants are the same as in C++: positive or negative whole numbers.

· An integer constant may be specified in one of the following bases:

· Decimal

Example:26

· Octal (base 8)

Example:032(the number 26 in octal)

· Hexadecimal (base 16)

Example:0x1A(the number 26 in hexadecimal)

Floating-point constants

· Floating-point constants are the same as in C++:

· They may either be written in decimal notation or exponential notation.

· They may be specified with the ‘f’ or ‘F’ suffix for the 32-bit value or the ‘d’ or ‘D’ suffix for the 64-bit value which is the default.

Examples

123.4

1.234e+2D

123.4f

String constants

· A string constant is a sequence of zero or more Unicode characters (including escape sequences) enclosed between double quotes.

Examples

“\nJohn Doe”

“Enter a value:\t”

“T\u00EAte”(Tête)

Special Constants

· There are two special constants:

· null can be used as the value for any reference type (but not primitive type) variable.

· A class literal (constant) is formed by taking a type name and appending “.class” to it. For example, String.class.

Variables, Basic Data Types, and Type Binding

· Name of a variable:is an identifier.

· Address of a variable:is not accessible in a program.

· In Java, the number of bytes reserved for a memory location depends on the data type of the corresponding variable, and not on the machine on which you will be running the Java program.

· Basic data types:Java basic data types with their range of values are provided in the following table:

Data Type

Type of Data

Range of Values

Size

boolean

Boolean value

true, false

char

A single character

Unicode character representations: ‘\u0000’ – ‘\uffff’

2 byte

byte

integers

-27 (-128) to 27 – 1 (127)

1 bytes

short

integers

-215 (-32,768) to 215 – 1 (32,767)

2 bytes

int

integers

-231 (-2,147,483,648) to 231 – 1 (2,147,483,647)

4 bytes

long

integers

-263 (-9,223,372,036,854,775,808) to 263 – 1 (9,223,372,036,854,775,807)

8 bytes

float

Floating point decimals

Negative range: -3.4028235E+38 to -1.4E-45

Positive range: 1.4E-45 to 3.4028235E+38

4 bytes

double

Floating point decimals

Negative range: -1.7976931348623157E+308 to -4.9E-324

Positive range: 4.9E-324 to 1.7976931348623157E+308

8 bytes

· The precisions of a floating point data types are provided as follows:

Data Types

Precision

float

7 digits

double

15 digits

Type Binding:

(static type binding with explicit declarations of variables).

· In Java, a variable must be declared before it can be used.

· The declaration statement is the same as in C++.

Examples

intnum,

// to hold the first value

number,// to hold the second value

sum;

// to hold their sum

Note

There is a Java class named type-wrapper class for each of the basic data types above. This class has the same name as the basic data type, but starts with an uppercase letter: Byte, Short, Integer, Long, Float, and Double.

Arithmetic Expressions

· The rules for writing and evaluating valid arithmetic expressions are the same as in C++. However, unlike in C++, the order of operands evalution in Java is left-to-right.

· Java also allows mixed-mode expressions as in C++: the following table shows the Java arithmetic operators and how the data type of the result is obtained from those of the operands.

Operation

Operator

Example

Promotion Rule

Addition

+

A + B

1. Operands with data type byte or short are converted to int.

2. If either operand is of type double, then the other operand is converted to double.

3. Otherwise, if either operand is of type float, then the other operand is converted to float.

4. Otherwise, if either operand is of type long, then the other operand is converted to long.

5. Otherwise, both operands are converted to int.

Subtraction

-

A – B

Multiplication

*

A * B

Division

/

A / B

Modulus (Remainder)

%

A % B

Negation

-

-A

Assignment Statement

· Its syntax is the same as in C++:

=;

Examples

char letter;

int num1, result;

double dnum;

letter = ‘A’;

num1 = 25;

dnum = 4.25;

result = num1 * 3;

// the new value of variable result is 75

Assignment conversion Rules

· Java allows you to make certain assignment conversions by assigning a value of one type to a variable in another type as follows:

byte→short→int→long→float→double

Example

byte bnum = 97;

int inum = 123;

long lnum;

double dnum;

lnum = bnum;

dnum = inum;

· Conversions from one type to the right of an arrow above to another type to the left of the arrow are done by means of casts. However, there may be a loss of information in the conversion.

Example

double dnum = 9.997;

int inum = (int) dnum;

// the value of inum is: 9

Compound Assignments and the Assignment Operator

· Compound assignments are specified in the same way as in C++ as follows:

= ;

Which is equivalent to the regular assignment:

=;

Examples

Compound Assignments

Equivalent Simple Assignments

counter += 5;

counter = counter + 5;

power *= value;

power = power * value;

total -= value;

total = total - value;

remain %= 8;

remain = remain % 8;

result /= num - 25

result = result / (num - 25);

number *= -1;

number = -number;

· In Java, the assignment is an operator with right-to-left associativity.

Example

num1 = num2 = number = 5;

//num1 = 5

num2 = 5

number = 5

Initial value of a Variable

· The initial value of a variable with a basic data type can be specified when it is declared in the same way as in C++.

Examples

int num1 = 25,

num2,

sum = 0;

char letter , grade = 'A';

Naming Constants

· In Java, you use the keyword final in the declaration of a variable to indicate that its initial value cannot be modified as follows:

final = ;

Example

final double PI = 3.14;

final int MAXVALUE = 150;

· final variables correspond to const variables in C++. They are in general specified in upper case.

Increment and Decrement Operators

· The increment and the decrement operators are the same as in C++.

Example

int inum1 = 12, inum2 = 50;

double dnum = 2.54;

inum1++;

inum2 = - - inum1 * 10 ;

++dnum;

Logical Expressions

· A logical expression (or condition) are specified and evaluated in the same way as in C++.

· A simple condition has the following syntax:

Relational Operators

C/C++ Symbol

Meaning

<

is less than

>

is greater than

= =

is equal to

<=

is less than or equal to

>=

is greater than or equal to

!=

is not equal to

· A compound condition is built from simple conditions and logical operators.

Logical Operators

C++ Symbol

Meaning

Evaluation

&&

AND

&& is true if and only if both conditions are true

||

OR

|| is true if and only if at least one of the two conditions is true

!

NOT

! is true if and only if is false

· In C++, 0 is false and anything else is true. But this is not the case in Java. So, the C++ condition !num (which is equivalent to num = = 0) is not valid in Java.

Precedence of Java Operators

Operator

Order of Evaluation

Precedence

!

Unary –

right to left

7

*

/

%

left to right

6

+

-

left to right

5

<

<=

>

<=

left to right

4

==

!=

left to right

3

&&

left to right

2

||

left to right

1

Conditional Expressions

· A conditional expression has the following syntax:

? :

· With the meaning: if is true, the value of the expression is the value of otherwise, it is the value of .

Example:

average = (count = = 0) ? 0 : sum / count;

· A conditional expression can be used in a program where any other expression can be used.

Variable Initialization and Expressions

· In Java, a variable can be initialized when it is declared with an expression that only contains variables with assigned values.

Example:

int num1 = 7,

num2 = num1 + 3;

Class String

· The Java programming language does not have a basic data type to store and manipulate character strings.

· However, the standard Java library contains a predefined class called String (from the package java.lang) that may be used to create and manipulate character strings.

· A String object (as any other object in Java) is created by using the new operator and a class constructor.

For example: String name = new String(“John Doe”);

· But you can declare a String object that references a string constant as follows:

String

=

;

Example

String greeting = “Hello world!”;

· You can also use the assignment statement to store a character string into a String variable.

Example

String address;

address = “300 Pompton Road, Wayne, NJ 07470”;

Concatenation Operator

· In Java, the + operator can be used to join (concatenate) two strings together or a string to any other value.

Examples

int num = 105;

String head = “Hello”;

String tail = “ world!”;

String greeting1 = head + tail;

// the value of variable greeting1 is: Hello world!

String greeting2 = head + 2009;// the value of variable greeting2 is: Hello2009

String rating = “PG” + 13;

//the value of the variable rating is: PG13

String message = “num =” + num;// the value of the variable message is: num = 105

· You can also use the + operator in the compound assignment.

Examples

String greeting = “Hello”

// the value of variable greeting is: Hello

greeting+ = “ world”;

// the value of variable greeting is: Hello world!

Testing Strings for Equality

· In Java, you do not use the = = operator to test for Strings equality as in C++.

· You use instead the equals( ) or the equalsIgnoreCase( ) methods to do it as follows:

StringVar1.equals(StingVar2)

returns true if strings StingVar1 and StringVar2 are identical.

StringVar1.equalsIgnoreCase(StingVar2)returns true if strings StingVar1 and StringVar2 are identical except for the uppercase/lowercase letter distinction.

Examples

String greeting = “Hello”;

String message = “Thanks”;

greeting.equals(“Hello”)

returns true

greeting.equals(message)

returns false

“Thanks”.equals(message)

returns true

greeting.equals(“HELLO”)

returns false

greeting.equalsIgnoreCase(“HELLO”)

returns true

String Length

· The length( ) method returns the number of character contained in a String object.

Example

String message = “Thank you”;

int n = message.length( );

// the value of variable n is: 9

Converting Strings to their Numerical Values

· Strings of digits can be converted into their numerical values by using the following methods:

Byte. parseByte( s )

Converts string s to a byte

Short.parseShort( s )

Converts string s to a short

Integer.parseInt( s )

Converts string s to an integer (int)

Long.parseLong( s )

Converts string s to a long integer ( long )

Float.parseFloat( s )

Converts string s to a single precision floating point (float)

Double.parseDouble( s )

Converts string s to a double precision floating point (double)

Example

String argument1 = “123”,

argument2 = “123.45”;

int inum = Integer.parseInt( argument1 );

// inum = 123

double dnum = Double.parseDouble( argument2 );

// dnum = 123.45

Converting Numbers to Strings

· Sometimes you may want to convert a number to a string because you need to operate on its value in string form.

· You can convert a number to a string in one of the following ways:

1. Use the String concatenation operator:

Example

int inum = 123;

double dnum = 12.5;

String st1 = “” + inum;

String st2 = “” + dnum;

2. By using the String.valueOf( ) method:

Example

int inum = 123;

double dnum = 12.5;

String st1 = String.valueOf( inum );

String st2 = String.valueOf( dnum );

3. By using the toString( ) class methods (example: String st1 = Integer.toString( 123); ).

Standard Input

· Input statements are not provided in the Java language.

· However, input from the standard input device may be performed in a Java program by using objects of the class Scanner.

· The standard input device (which by default is the keyboard) is represented in a Java program by the object System.in.

· You use objects of the class Scanner to perform standard input as follows:

1. Write the following import statement before any class of your program:

import java.util.Scanner;

2. Declare an object of the class Scanner and initialize it with the object System.in as follows:

Scanner = new Scanner( System.in );

Example:

Scanner input = new Scanner( System.in );

3. Use the following instance methods to perform input:

Method

What it does

Example

next( )

Input next word (sequence of characters)

String name = input.next( );

nextByte( )

Input next byte

byte num = input.nextByte( );

nextDouble( )

Input next double precision value

double dnum = input.nextDouble( );

nextFloat( )

Input next single precision value

float fnum = input.nextFloat( );

nextInt( )

Input next integer value

int inum = input.nextInt( );

nextLine( )

Input next line of text

String line = input.nextLine( );

nextLong( )

Input next long integer value

long lnum = input.nextLong( );

nextShort( )

Input next short integer value

short snum = input.nextShort( );

· Input values are separated (by default) with white spaces: spaces, tabs, carriage returns, . . ., etc.

Example

int age, hours;

double payRate;

String firstName;

firstName = input.next( );

age = input.nextInt( );

payRate = input.nextDouble( );

hours = input.nextInt( );

Input:

John 24 12.50 35

Standard Output

· Output statements are not provided in the Java language.

· However, output to the standard output device (which is by default the monitor) can be performed by using the methods println and print on object System.out.

· They have the following syntax:

System.out.println( );

System.out.print( );

Where is a string or an arithmetic expression

· print outputs the string or the value of the arithmetic expression whereas println moves the cursor to the next line in addition to output the string or the value of the arithmetic expression.

Example

int num = 105;

String head = “Hello”;

String tail = “ world!”;

System.out.println( num - 5 );

Output:

100

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

Output:

Hello World!

System.out.println( head + tail );

Output:

Hello world!

System.out.println( head + 2009 );

Output:

Hello2009

System.out.println( “PG” + 13 );

Output:

PG13

System.out.println( “num - 3 =\t” + (num – 3));

Output:

num - 3 = 102

Formatted Output

· Formatted output to the standard output device can be performed by using the printf method on object System.out.

· It has the following syntax:

System.out.printf( , );

· consists of fixed text and format specifiers.

· The fixed text in the format string is output just as it would be in a print or println method.

· Each format specifier in the is the placeholder of the value of the corresponding argument in the .

· The following table lists some format specifiers with their corresponding data formats:

Format Specifier

Data Format

Example

Output

%c

a single character in lowercase

System.out.printf( “%c”, ‘a’ );

a

%C

a single character in uppercase

System.out.printf( “%C”, ‘a’ );

A

%s

a string of characters in lowercase

System.out.printf( “%s”, “John” );

john

%S

a string of characters in uppercase

System.out.printf( “%S”, “John” );

JOHN

%d

Decimal integer in base 10

System.out.printf( “%d”, 125 );

125

%o

Decimal integer in base 8

System.out.printf( “%o”, 125 );

175

%x or %X

Decimal integer in base 16

System.out.printf( “%X”, 125 );

7D

%f

Floating point in decimal format

System.out.printf( “%f”, 12.5 );

12.5

%e or %E

Floating point in exponential format

System.out.printf( “%E”, 12.5 );

1.25E+1

%g or %G

Floating point in either floating point format or exponential format based on the magnitude of the value

System.out.printf( “%G”, 12.5 );

12.5

Examples

It is assumed that the variables are defined and initialized as follows:

int inum = 125;

char ch = 'Z';

float fnum = 42.75;

double dnum = 347.874;

a)System.out.printf("The value of inum is:\t%d", inum);

Output

|The value of inum is:125_

b)System.out.printf("\nI have chosen the number:\t%d and the value of ch is:\t%c", 47, ch);

Output

|I have chosen the number:47 and the value of ch is:z_

c)System.out.printf("\nThe value of fnum is:\t%f \n and that of dnum is:%f", fnum, dnum);

Output

|The value of fnum is:42.750000

|and that of dnum is:347.874000_

d)System.out.printf("\n12 + 23 =\t%d", 35);

Output

|12 + 23 =35_

e)System.out.printf("\nThe value of ch is:\t%c", ch);

System.out.printf(" and that of inum is:\t%d", inum);

Output

|The value of ch is:Z and that of inum is:125_

f)System.out.printf("\n%d%c%f", dnum, ch, fnum);

Output

|125Z42.750000_

ExamplesArithmetic Expressions as Arguments to printf( ) Method

It is assumed that the variables are defined and initialized as follows:

int num1 = 12,

num2 = 4;

a)System.out.printf("The sum of %d and %d is:\t%d" , num1, num2, num1 + num2);

Output

|The sum of 12 and 4 is: 16_

b)System.out.printf("\nnum1 + num2 =\t%d", num1 + num2);

Output

|num1 + num2 = 16_

c)System.out.printf("\n%d + %d =\t%d" , num1, num2, num1 + num2);

Output

|12 + 4 = 16_

d)System.out.printf("\n12 + 23 =\t%d", 12 + 23);

Output

|12 + 23 = 35_

e)System.out.printf("\n%d + %d =\t%d", 12 , 23 , 12 + 23);

Output

|12 + 23 = 35_

Specifying the Field Width and the Number of Digits after the Decimal Point

· A format specifier may also include optional formatting information such as the number of spaces to use to display a value (field width) or the number of digits to be displayed after the decimal point of a floating point value.

· You specify a field width with a decimal value between the % symbol and the format specifier.

· If the field width is larger than the data being printed, the data is right justified in the field (by default); if you want the data to be left justified, precede the field width with the minus sign.

· The number of digits to be displayed after a decimal point in a floating point value is specified in the same way as the field width, but it must be preceded with the decimal point.

Examples

Given the following definitions of variables:

int inum = 125;

char ch = 'z';

float fnum = 42.75;

double dnum = 347.874;

a)System.out.printf("\nI have chosen the number:%4d and the value of ch is:\t%C", 47, ch);

Output

|I have chosen the number:_ _47 and the value of ch is:Z_

b)System.out.printf("\nThe value of fnum is:%7.1f \n and that of dnum is:%.2E", fnum, dnum);

Output

|The value of fnum is:_ _ _42.8

|and that of dnum is:3.48E+2

c)System.out.printf("\n%10S\nt%-10S", “PRICE”, “PRICE”);

Output

|_ _ _ _ _ PRICE

|PRICE_ _ _ _ _

Creating Format Strings

· Using the String.format( ) static method, you can create a formatted string that you can reuse, as opposed to a one-time print statement.

Example

Given the declaration of variables provided in the example above, instead of the output statement in example a) we can write:

String st = String.format( "\nI have chosen the number:%4d and the value of ch is:\t%C", 47, ch);

System.out.println( st );

Control Structures

· Java has the same control structures as C++:

1. Two way selection:implemented using the if-else structure as in C++.

2. One way selection:implemented using the if structure as in C++.

3. Counter –controlled iteration:

there is no counting loops in Java. However, counting loops are simulated by using the while-loop or the for-loop in the same way as in C++.

4. Logically controlled iteration:

implemented using the while-loop or the for-loop as in C++.

5. Multiple way selections:implemented using if-else structures or the switch structure as in C++.

Java Program

· A Java program consists of one or more source files.

· The file name of a source file must be a valid Java identifier with the filename extension .java.

ExamplesLab0.java

GradeProcessing.java

PayRollProc.java

SampleProg.java

· A Java source file consists of one or more classes.

· A class is used to encapsulate data (variables) and methods (functions) and is in general defined as follows:

class

{

}

is a valid Java identifier. But by convention, its initial letter is capitalized.

is either public or is omitted.

· A class with access specifier public is visible in any other source module.

· When the access specifier is omitted, the class is visible only within its own package (named group of related classes).

· One class in every source module must have the access specifier public. The name of this class must be the name of that source module.

· A public class of every program must contain method main with the following syntax:

public static void main( String [ ] args )

{

}

Where args is an array of Strings to be initialized with command line arguments.

Example P1

/*--------------------------------------Program1 -------------------------------------*/

public class Program1

{

public static void main( String [ ] args )

{

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

System.out.println(“Java, here we come”);

}

}

Notes:

· The name of the source file that contains this class must be: Program1.java.

· The execution of a Java program starts with the first executable statement in method main.

· The statements of any other method are executed only if that method is called by main or a method that is called by main.

Compiling and Executing a Java Program

· You compile a java source file as follows:

Javac

Example

You compile the source file of example P1 as follows:

javac Program1.java

· The Java compiler will create the bytecodes for this class and store it in a new file named Program1.class (in the same directory).

· You use the Java interpreter to run a bytecode file as follows:

java

Example

The bytecode Program1.class of the program in example P1 is executed as follows:

java Program1

· Input redirection: you can ask the operating system to get the input of your program from a file instead of the keyboard by first entering all the input data of your program in that file and then specifying that file when you execute your program as follows:

java <

Example

For the bytecode Program.class to get its input from the file program.dat execute it as follows:

java Program < program.dat

· Output Redirection: you can ask the operating system to send the output of your program to file instead of the monitor by using the output redirection as follows:

java >

Example

For the bytecode Program.class to send its output to the file program.out, execute it as follows:

java Program > program.out

For the bytecode Program.class to get its input from the file program.dat and to send its output to the file program.out, execute it as follows:

java Program < program.dat > program.out

Lab Procedure

A. Follow this procedure if you are using a laptop or a computer at home with Windows 7

1. First find out the version number of your Java Development Kit as follows:

a. Click the Start button, and then click All Programs, then Accessories, and then Command Prompt to open the Command Prompt window.

b. Type the command: DIR C:\“Program Files\Java” ( to list the content of the Java directory. Your version of the JDK will be listed with its version number (for example: jdk1.8.0_25). Note that if you have downloaded the 32-bit version of JDK, you should type the command: DIR C:\“Program Files (x86)\Java” (

2. Update the PATH Environment variable to include the pathname:

C:\Program Files\Java\jdk1.8.0_25\bin (where 1.8.0_25 is the version number of JDK)

orC:\Program Files (x86)\Java\jdk1.8.0_25\bin (if you have a 32-bit version of JDK).

You update the PATH environment variable as follows:

a. Click Start, then Control Panel, then System and Security, then System.

b. Click Advanced System Settings, then Environment Variable.

c. Select Path in System Variables and then click Edit.

d. Use the right-arrow key to move the cursor to the end of the displayed string.

e. Type a semicolon followed by the pathname that you want to add.

f. Click OK.

3. Perform the following steps before you can compile and execute your Java programs:

a. Use Notepad or any other editor to type your Java program source files and save them in your flash drive (make sure that your flash drive is in drive E and type the name of the source files in double quotes: e.g. “Lab0.java”).

b. Click the Start button, and then click All Programs, then Accessories, and then Command Prompt to open the Command Prompt window.

c. Type E: (

to change to the drive that contains your flash drive.

B. Follow this procedure if you are using a laptop or a computer at home with Windows 10

3. First find out the version number of your Java Development Kit as follows:

c. Click on the Start Menu (Windows icon), then click Windows Systems, and then Command Prompt to open the Command Prompt window.

d. Type the command: DIR C:\“Program Files\Java” ( to list the content of the Java directory. Your version of the JDK will be listed with its version number (for example: jdk1.8.0_181). Note that if you have downloaded the 32-bit version of JDK, you should type the command: DIR C:\“Program Files (x86)\Java” (

4. Update the PATH Environment variable to include the pathname:

C:\Program Files\Java\jdk1.8.0_181\bin (where 1.8.0_181 is the version number of JDK)

orC:\Program Files (x86)\Java\jdk1.8.0_181\bin (if you have a 32-bit version of JDK).

You update the PATH environment variable as follows:

g. Click the Start Menu (Windows icon), then click Windows Systems then Control Panel, then System and Security, then System.

h. Click Advanced System Settings, then Environment Variable.

i. Select Path in System Variables and then click Edit.

j. Double click on the last line in the left pane.

k. Type the pathname that you want to add.

l. Click OK.

m. Click OK.

4. Perform the following steps before you can compile and execute your Java programs:

d. Use Notepad or any other editor to type your Java program source files and save them in your flash drive (make sure that your flash drive is in drive E and type the name of the source files in double quotes: e.g. “Lab0.java”).

e. Click on the Start Menu (Windows icon), then click Windows Systems, and then Command Prompt to open the Command Prompt window.

e. Type E: (

to change to the drive that contains your flash drive.

Java Methods

· Java methods have the same syntax as C++ functions; but they are defined in the class in which they belong: there are no function prototypes in Java.

· A Java method may be specified as a class (static) method or an instance method.

· Class methods and instance methods differ in the way they are called in a Java program.

· Variables and methods defined in a Java class also have access specifiers.

· The access specifiers with their access levels are provided as follows:

specifier

Can be accessed in:

Class

Package

Subclass

Everywhere

public

Yes

Yes

Yes

Yes

protected

Yes

Yes

Yes

No

No specifier

Yes

Yes

No

No

private

Yes

No

No

No

· The general syntax of a class (static) method follows:

static ( )

{

}

· The general syntax of an instance method follows:

( )

{

}

Where

is either private, public or is not specified

is either void or the data type of the value returned by the function

is a list of zero or more value parameters.

· Parameters are specified in the same way that they are specified in C++, except that there are no reference parameters in Java: Java allows only value parameters.

· In addition to values of the basic data types boolean, char, byte, short, int, long, float, and double, Java methods can also return arrays, strings, and objects.

Defining and Calling a Class (static) Method

· You call a class (static) method in any other method (class or instance) in the class in which it is defined in the same way that you call a user-defined function in C++.

Example P2

The following program reads two integer values and computes their product by calling the class method int computeProd1(int num1, int num2).

/*-------------------------------------------------------Program2 --------------------------------------------*/

/* Read two integer values, compute their product

*/

import java.util.Scanner;

public class Program2

{

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*---------------------------Compute and print their product--------------------------------*/

int product = computeProd1( first, second );

System.out.println( “Their product is:\t” + product );

}

/*---------------------------------------Class Method computeProd( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

static int computeProd1( int num1, int num2)

{

return( num1 * num2);

}

}

Defining and Calling an Instance Method

· You call an instance method in a class (static) method as follows:

· First define and initialize a reference variable with the location of an object of the class of the instance method.

· Follow that variable with the dot (.) which is followed by the method name to call it.

· You define and initialize a reference variable with the location of an object in one of the following ways:

a. = new ( );

b. ;

= new ( );

Example P3

The following program reads two integer values and computes their product by calling the instance method int computeProd2(int num1, int num2).

/*-------------------------------------------------------Program3 --------------------------------------------*/

/* Read two integer values, compute their product

*/

import java.util.Scanner;

public class Program3

{

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*---------------------------Compute and print their product--------------------------------*/

Program3 objRef = new Program3( );

int product = objRef.computeProd2( first, second );

System.out.println( “Their product is:\t” + product );

}

/*---------------------------------------Instance Method computeProd( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

int computeProd2( int num1, int num2)

{

return( num1 * num2);

}

}

· You call an instance method in another instance method from the same class in the same way that you call a user-defined function in C++.

Example P4

The following program reads two integer values and computes their average by calling the instance method int computeAvg(int num1, int num2) which also calls the instance method int computeSum(int num1, int num2).

/*-------------------------------------------------------Program4 --------------------------------------------*/

/* Read two integer values, compute their product

*/

import java.util.Scanner;

public class Program4

{

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*---------------------------Compute and print their product--------------------------------*/

Program4 objRef = new Program4( );

int average = objRef.computeAvg( first, second );

System.out.println( “Their average is:\t” + average );

}

/*---------------------------------------Instance Method computeAvg( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

int computeAvg( int num1, int num2)

{

int total = computeSum( num1, num2);

return( total / 2);

}

/*---------------------------------------Instance Method computeSum( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

int computeSum( int num1, int num2)

{

return( num1 + num2 );

}

}

· You can call a class (static) method in an instance method.

Example P5

The following program reads two integer values and computes their average by calling the instance method int computeAvg(int num1, int num2) which also calls the class method int computeSum(int num1, int num2).

/*-------------------------------------------------------Program5 --------------------------------------------*/

/* Read two integer values, compute their product

*/

import java.util.Scanner;

public class Program5

{

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*---------------------------Compute and print their product--------------------------------*/

Program5 objRef = new Program5( );

int average = objRef.computeAvg( first, second );

System.out.println( “Their average is:\t” + average );

}

/*---------------------------------------Instance Method computeAvg( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

int computeAvg( int num1, int num2)

{

int total = computeSum( num1, num2);

return( total / 2);

}

/*---------------------------------------Class Method computeSum( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

static int computeSum( int num1, int num2)

{

return( num1 + num2 );

}

}

Class variables

· A class variable (static field) is any variable declared with the static modifier. It is the same as a static member variable in C++.

· It is used as a C++ global variable and is accessed by both instance and class methods.

· It is in general defined as follows:

static ;

Where

is either private, public or is not specified

· A class variable may also have an initial value or be a final variable.

Example P6

The following program reads two integer values and computes the quotient and the remainder in the division of the first value by the second by calling the class method void computeQuotRem(int num1, int num2).

Note that since arguments are not passed by reference in Java, two class variables are needed to get the quotient and the remainder from function computeQuotRem( ).

/*-------------------------------------------------------Program6 --------------------------------------------*/

/* Read two integer values and compute the quotient and the remainder in the division

of the first value by the second

*/

import java.util.Scanner;

public class Program6

{

static int quotient;

// to hold the quotient

static int remain;

// to hold the remainder

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*-------------------Compute and print the quotient and the remainder-------------------*/

if( second == 0 )

System.out.println( “Division by zero is not allowed!”);

else

{

computeQuotRem( first, second );

System.out.println(“The quotient is:\t” + quotient );

System.out.println(“The remainder is:\t” + remain );

}

}

/*--------------------------------------Class Metod computeQuotRem( )--------------------------------------*/

/* compute the quotient and the remainder in the division of the first argument by the second

*/

static void computeQuotRem( int num1, int num2)

{

quotient = num1 / num2;

remain = num1 % num2;

}

}

Method (Name) Overloading

· Two or more Java methods may have the same name, as long as there is a way to distinguish them based on their parameters: this feature is known as method name overloading.

· The compiler determines the right version of the method to call from a set of overloaded methods by inspecting the arguments specified in the function call.

· The program in example P7 illustrates the use of method name overloading in a source module.

Example P7

Method Name Overloading

/*----------------------------------------------------Porgram7 ------------------------------------------------------*/

/*Compute the average of two integer values, the average of three integer values

and the average of two double precision floating-point values.

*/

import java.util.Scanner;

public class Program7

{

int main()

{

int result1,

// the average of two integer values

result2;

// the average of three integer values

double result3;//the average of two floating-point values

result1 = ComputeAverage(4, 5);

// calling first method

result2 = ComputeAverage(5, 4, 6);// calling second method

result3 = ComputeAverage(4.0, 5.0);// calling third method

System.out.println( “result1=\t” + result1 );

System.out.println( “result2=\t” + result2 );

System.out.println( “result3=\t” + result3 );

return 0;

}

static int ComputeAverage(int value1, int value2)

{

return (value1 + value2) / 2;

}

static int ComputeAverage(int value1, int value2, int value3)

{

return (value1 + value2 + value3) / 3;

}

static double ComputeAverage(double value1, double value2)

{

return (value1 + value2) / 2;

}

}

OUTPUT

result1=4

result2=5

result3=4.5

Exercise I1

Part1.Write a java program that consists of a class named ExerciseI1Part1 with the method main that does the following:

a. Read the first name, last name, ID number, the pay rate, and the number of hours worked by an employee.

b. Compute the gross pay (hours time the pay rate)

c. Compute the tax deduction (20% of the gross pay)

d. Compute the net pay (gross pay minus tax deduction).

e. Print the results using formatted output as follows:

Name:

Mark, peter

Hours:

35

Pay Rate:

$10.0

Gross Pay:

$350.00

Tax Deduction:

$70.00

Net Pay:

$280.00

Part2.Write a java program that consists of a class named ExerciseI1Part2 with the method main, the class (static) method double computeNetPay(double gross), and the class (static) method double computeTax( double gross).

· Method computeTax( double gross) receives the gross pay of an employee and computes his tax deduction (20% of the gross pay).

· Method computeNetPay(double gross) receives the gross pay of an employee, computes his tax deduction by calling the method computeTax( double gross), and then computes and returns his net pay.

· the method main does the following:

a. Read the first name, last name, ID number, the pay rate, and the number of hours worked by an employee.

b. Compute the gross pay (hours time the pay rate).

c. Compute the tax deduction by calling the method computeTax( double gross).

d. Compute the net pay by calling the method computeNetPay(double gross).

e. Print the results using formatted output as in part 1.

Part3.Write a java program that consists of a class named ExerciseI1Part3 with the method main, the instance method double computeNetPay(double gross), and the class (static) method double computeTax( double gross).

· Method computeTax( double gross) receives the gross pay of an employee and computes his tax deduction (20% of the gross pay).

· Method computeNetPay(double gross) receives the gross pay of an employee, computes his tax deduction by calling the method computeTax( double gross), and then computes and returns his net pay.

· the method main does the following:

a. Read the first name, last name, ID number, the pay rate, and the number of hours worked by an employee.

b. Compute the gross pay (hours time the pay rate).

c. Compute the tax deduction by calling the method computeTax( double gross).

d. Compute the net pay by calling the method computeNetPay(double gross).

e. Print the results using formatted output as in part 1.

Part4.Write a java program that consists of a class named ExerciseI1Part4 with the method main, the instance method double computeNetPay(double gross), and the instance method double computeTax( double gross).

· Method computeTax( double gross) receives the gross pay of an employee and computes his tax deduction (20% of the gross pay).

· Method computeNetPay(double gross) receives the gross pay of an employee, computes his tax deduction by calling the method computeTax( double gross), and then computes and returns his net pay.

· the method main does the following:

a. Read the first name, last name, ID number, the pay rate, and the number of hours worked by an employee.

b. Compute the gross pay (hours time the pay rate).

c. Compute the tax deduction by calling the method computeTax( double gross).

d. Compute the net pay by calling the method computeNetPay(double gross).

e. Print the results using formatted output as in part 1.

Part5.Write a java program that consists of a class named ExerciseI1Part5 with the class (static) variables tax and netPay, the method main, and the instance method void computeTaxNetPay(double gross).

· Method computeTaxNetPay(double gross) receives the gross pay of an employee, computes his tax deduction (which is 20% of the gross pay) and the net pay that are returned to method main by using the class variables tax and netPay.

· The method main does the following:

a. Read the first name, last name, ID number, the pay rate, and the number of hours worked by an employee.

b. Compute the gross pay (hours time the pay rate)

c. Compute the tax deduction and the net pay by calling the method computeTaxNetPay(double gross).

d. Print the results using formatted output as as in part 1.

One-Dimensional Arrays

· In Java, a one-dimensional array variable is a reference variable: it is an explicit/implicit heap dynamic variable.

· A one-dimensional array variable is declared as follows:

[ ] ;

Where is either a basic data type or a class name.

Examples

int [ ]studentIdList;

double [ ] studentScoreList;

char [ ] letterGrades;

String [ ] names;

· You allocate and bind memory locations to a one-dimensional array variable by using the new operator as follows:

= new [ ];

Examples

studentIdList = new int [ 10 ];

// allocate an array of 10 integer elements

studentScoreList = new double[20];// allocate an array of 20 double precision elements

names = new String [ 50 ];

// allocate an array of 50 String elements

· You can also allocate and bind memory locations to a one-dimensional array variable in a declaration statement as follows:

[ ] = new [ ];

Example

int [ ] studentIdList = new int [ 10 ];

// allocate an array of 10 integer elements

· A one-dimensional array can also be initialized when it is declared as follows:

[ ] = { };

Example

int [ ] firstPrimes = { 2, 3, 5, 7, 11, 13, 17, 19 };

String [ ] firstNames = { “John”, “Mark”, “Paterson”, Joe”, “Peter”, “Pat”, “Allan” };

· The size (number of elements) of an array is accessed by using the length member variable.

Example

int size1 = firstPrimes.length;

// size1 is set to 8

int size2 = firstNames.length;

// size2 is set to 7

Accessing and Processing the Elements of a one-Dimensional Array

· The elements of a one-dimensional array are accessed and processed in Java in the same way that they are accessed and processed in C++.

Example

/*----- code segment to compute the sum of the elements of the array first Primes---*/

int total = 0;

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

total + = firstPrimes [ i ];

Copying Arrays

· The method arraycopy of the class System is provided in the standard Java library to copy the elements of a one-dimensional array into another one of the same data type. It is specified as followed:

System.arraycopy ( , , , , );

Where

is the array to copy from

is the starting index to copy from

is the array to copy to

is the starting index to copy to

is the number of element to copy

Example

char [ ] copyFrom = { ‘d’, ‘e’, ‘c’, ‘a’, ‘f’, ‘f’, ‘e’, ‘i’, ‘n’, ‘a’, ‘t’, ‘e’, ‘d’ };

char [ ] copyTo = new char [ 7 ];

System.arraycopy( copyFrom, 2, copyTo, 0, 7 );

// set array copyTo as follows: copyTo[0] = ‘c’, copyTo[1] = ‘a’, copyTo[2] = ‘f’,

// copyTp[3] = f’, copyTo[4] = ‘e’, copyTo[5] = ‘i’, and copyTo[6] = ‘n’

· An array variable behaves like a C++ pointer variable. So, if you assign one array variable to another one using the assignment operator, both variables will refer to the array allocated for the assigned variable.

Example

char [ ] copyFrom = { ‘d’, ‘e’, ‘c’, ‘a’, ‘f’, ‘f’, ‘e’, ‘i’, ‘n’, ‘a’, ‘t’, ‘e’, ‘d’ };

char [ ] copyTo;

copyTo = copyFrom;

// The above array now has two names: copyTo and copyFrom

// copyTo[i] and copyFrom[i] are interchangeable in any expression.

The statement:

copyTo[i] = ‘a’;

has the same effect as

copyFrom[i] = ‘a’;

We have the following memory representation after the assignment operation is performed:

d

e

c

a

f

f

e

i

n

a

t

e

d

copyFrom

copyTo

Enhanced for Statement

· The enhanced for statement iterates through the elements of an array (one-by-one starting with the first element) without using a counter.

· It syntax is as follows:

for( : )

Where:

is the name of the array

is a data type that is consistent with the data type of the elements in the array.

represents successive elements of the array in the body of the loop from the first to the last.

Examples

/*----- code segment to compute the sum of the elements of the array firstPrimes ---*/

int total = 0;

for ( int element : firstPrimes )

total + = element;

System.out.println(“The sum of the first Primes is:\t” + total );

/*----- code segment to print the names in the array firstNames ---*/

for ( String element : firstNames )

System.out.println( element );

· The enhanced for statement can only be used to access the values of the elements on an array: it cannot be used to modify the values of the elements of an array. The following code segment will generate an error:

/*----- invalid code segment to read values into an array ---*/

int [ ] list = new int [ 10 ];

for ( int element : list )

element = input.nextInt( );

Arrays as Parameters of Methods

· In Java, the parameter that corresponds to an array is specified in a method header as follows:

[ ]

· And a one-dimensional array is passed to a method by reference by passing the name of the array.

Example 1

/*------------------------------- Method arraySum --------------------------------------*/

/* receives as argument an array of integer values and computes and returns

the sum of its members */

static int arraySum( int [ ] list )

{

int total = 0;

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

total + = list[i];

return ( total );

}

· Given the following definition of array valuesList:

int [ ] valuesList1 = { 21, 25, 32, 45, 15, 8, 13, 35, 1, 17 };

· This function is called as follows:

/*--------------- compute and print the sum of the elements of array valuesList1 ----------*/

int sum;

sum = arraySum( valuesList1 );

System.out.println( “The sum of the elements is:\t” + sum );

Example 2

/*-------------------------------------- Method array5Incr --------------------------------------*/

/* receives as argument an array of integer values and adds 5 to each of its members */

static void array5Incr( int [ ] list )

{

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

list[i] + = 5;

}

· Given the following definition of array valuesList:

int [ ] valuesList1 = { 21, 25, 32, 45, 15, 8, 13, 35, 1, 17 };

· This function is called as follows:

/*-------------------------- Add 5 to each element of array valuesList2 -----------------------*/

Array5Incr( valuesList1 );

Arrays as Returned Types of Methods

· In Java, a method can return a one-dimensional array variable.

· The return type of a method that returns a one-dimensional array variable is specified as:

[ ]

Where is the data type of the one-dimensional array variable that the function will returns.

Example

/*------------------------------------------- Method addAarrays ----------------------------------------------*/

/* receives as arguments two arrays of integer values with the same size, adds their corresponding elements, and stores the result in the corresponding element of a third array that it then returns*/

static int [ ] addArrays( int [ ] list1, int[ ] list2 )

{

int size = list1.length;

int [ ] temp = new int [size];

for ( int i = 0; i < size; i ++ )

temp[i] = list1[i] + list2[i];

return ( temp );

}

· Given the following definitions of arrays valuesList1, valuesList2, and valuesList3:

int [ ] valuesList1 = { 21, 25, 32, 45, 15, 8, 13, 35, 1, 17 },

valuesList2 = { 12, 52, 23, 54, 51, 8, 31, 53, 1, 71 },

valuesList3;

· This function is called as follows:

/*-Add corresponding elements of arrays valuesList1 and valuesList2 and store the result in the corresponding element of array valuesList3 ----------------------------------------------------------------------------------------------*/

valuesList3 = addArrays( valuesList1, valuesList2 );

Exercise I2

Write a java program that consists of a class named ExerciseI2 with the following:

· The class variable: static Scanner scan;

· the method main,

· the class (static) method double [ ] readTestScores( int size ),

· The instance method char getLetterGrade(double score),

· The class (static) method void printComment(char grade), and

· The instance method void printTestResults(double [ ] testList).

1. Method readTestScores( int size ) receives a positive integer value n as argument, read (using the Scanner object scan) n test scores into an array and then returns that array.

2. Method getLetterGrade(double score) receives a student’s score as a value parameter, determines the corresponding letter grades, and returns it to the calling method. The letter grade is determined as follows:

if:

score >= 90

A

80 <= score < 90B

70 <= score < 80C

60 <= score < 70D

score < 60

F

3. Method printComment(char grade) receives a student’s letter grade as a value parameter and prints the corresponding comment. The comment is determined as follows:

A

very good

B

good

C

satisfactory

D

need improvement

F

poor

4. Method printTestResults(double [ ] testList) receives an array of test scores and prints a table with three columns consisting a test score in the first column, the corresponding letter grade in the second column and the corresponding comment in the third column as follows:

Test Score

Letter Grade

Comment

The letter grade is determined by calling the method getLetterGrade( ) and the comment is determined by calling the method printComment( ).

5. Method main( ) first initializes the Scanner object scan with the standard input object, then read the number of test scores, and then calls method readTestScores( )to read the test scores into an array, and then printTestResults( ) to print the table.

Two-Dimensional Arrays

· Similarly to one-dimensional arrays, a two-dimensional array variable is a reference variable: it is an explicit/implicit heap dynamic variable.

· It is declared as follows:

[ ][ ] ;

Where is either a basic data type or a class name.

Examples

int [ ][ ]studentScores;

double [ ][ ] totalSales;

char [ ][ ] document;

String [ ][ ] namesTable;

· You allocate memory locations for a two-dimensional array variable by using the new operator as follows:

= new [ ][ ];

Examples

studentScores = new int [10][ 5 ];// allocate an integer array of 10 rows and 5 columns

totalSales = new double [ 15][10];// allocate a double precision array of 15 rows and 10 columns

document = new char [25][80];// allocate an character array of 25 rows and 80 columns

namesTable = new String [10 ][5];

· You can also allocate memory locations for a two-dimensional array variable in a declaration statement as follows:

[ ][ ] = new [ ][ ];

Example

int [ ][ ] studentScores = new int [10][ 5 ]; // allocate an integer array of 10 rows and 5 columns

· A two-dimensional array can also be initialized when it is declared as follows:

[ ][ ] = { { } };

Example

int [ ][ ] labScores = { { 8, 9, 7, 8, 10 },

{ 9, 8, 8, 8, 7 },

{ 8, 7, 9, 9, 10 }

};

String [ ][ ] students = { {“John”, “Mark”, “Paterson” },

{ “Joe”, “Peter”, “Pat” },

{ “Dave”, “Bonnie”, “Pat” },

{ “Allan”, “Amy”, “Ellen” }

};

· When you create a two-dimensional array, the number of elements in a row does not have to be the same for all the rows.

Example

int [ ] [ ] pascalTriangle5 = { { 1 },

{ 1, 1 },

{ 1, 2, 1 },

{ 1, 3, 3, 1},

{ 1, 4, 6, 4, 1 },

{ 1, 5, 10, 10, 5, 1} };

Note that each row i (0 <= i <= 5) of the above pascalTriangle5 array has i +1 columns.

· As in C++, a two-dimensional array in Java is in fact a one-dimensional array of one-dimensional arrays that are its rows.

· When you allocate memory locations for a two-dimensional array, extra memory locations are allocated for the one-dimensional array whose elements reference the rows of the two-dimensional array.

Example

The allocation of the memory locations for the array: int [ ][ ] table = new int [ 5 ][ 4 ]; follows:

table

table [0]

table [1]

table [2]

table [3]

table [4]

table[0] is a one-dimensional array with four elements:

table[0][0], table[0][1], table[0][2], and table[0][3].

table[1] is a one-dimensional array with four elements:

table[1][0], table[1][1], table[1][2], and table[1][3].

table[2] is a one-dimensional array with four elements:

table[2][0], table[2][1], table[2][2], and table[2][3].

table[3] is a one-dimensional array with four elements:

table[3][0], table[3][1], table[3][2], and table[3][3].

Table[4] is a one-dimensional array with four elements:

table[4][0], table[4][1], table[4][2], and table[4][3].

Accessing and Processing the Elements of a two-Dimensional Array

· You access and process the elements of a two-dimensional array in Java in the same way that the elements of a two-dimensional array are accessed and processed in C++.

Example

Given the following two-dimensional array that holds 5 lab scores of 7 students:

int [ ][ ] labScores = { { 8, 9, 7, 8, 10 },

{ 9, 8, 8, 8, 7 },

{ 8, 7, 9, 9, 10 }

{ 9, 10, 6, 8, 8 },

{ 8, 8, 8, 7, 9 },

{ 9, 9, 9, 9, 9 },

{ 9, 8, 8, 8, 9 }

};

The following code segment computes the average lab score of each student and the next one computes the average lab score of each lab:

/*---------- code segment to compute the average lab score of each student -----*/

int total;

for ( int st = 0; st < labScores.length; st ++ )

{

total = 0;

for( int lct = 0; lct < labScores[ st ].length; lct ++ )

total + = labScores[st] [lct];

System.out.println( “Average score of student:\t” + (st +1) + “ is:\t” + (total / lct) );

}

/*---------- code segment to compute the average lab score of each lab assignment -----*/

int total;

for ( int lct = 0; lct < 5; lct ++ )

{

total = 0;

for( int st = 0; st < 7; st ++ )

total + = labScores[st] [lct];

System.out.println( “Average score of lab:\t” + (lct +1) + “ is:\t” + (total / 7) );

}

The code segment to compute the average lab score of each student can be rewritten using the enhanced for statement as follows:

/*---------- code segment to compute the average lab score of each student -----*/

int total,

student = 1;

for ( int [ ] scoreList : labScores )

// process the array row-by-row

{

total = 0;

for( int score : scoreList )

// add all the test scores of the current student

total + = score;

System.out.println( “Average score of student:\t” + ( student ) +“ is:\t” + (total / scoreList.length ) );

student ++ ;

}

· A two-dimensional array variable can be assigned to another two-dimensional array variable with the same data type. But as with one-dimensional array variables, both variables will refer to the same array.

Two-Dimensional Arrays and Methods

· In Java, a two-dimensional array is passed and processed in a method in the same way that a two-dimensional array is passed and processed in a function in C++, except that you do not have to specify the number of columns in the array with the parameter and you do not have to pass the number of rows as a parameter.

· Note that if the two-dimensional array is processed row by row, you do not need to pass the number of columns in each row to the method.

· The argument that corresponds to a two-dimensional array in a method call is the name of a two-dimensional array as in a function call in C++.

· In Java, a method can return a two-dimensional array variable which is not the case for a function in C++.

Example

The method that follows receives a two-dimensional array as parameter, and then computes and prints the sum of each of its rows. Note that all rows do not need to have the same number of columns.

static void computeRowSum( int [ ][ ] table )

{

int sum;

for( int row = 0 ; row < table.length ; row ++ )

{

int col;

for( sum=0, col = 0 ; col < table[row].length ; col ++ )

sum += table[row][col];

System.out.println( sum );

}

}

This method is called in method main as follows:

public static void main( String [ ] args )

{

int [ ][ ] valuesTable = { {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5,6,7} };

computeTable( valuesTable );

}

Executing a Program with a Command Line Arguments

· The general syntax of the command to execute a Java program is as follows:

java arg0 arg1 arg2 . . . argn

Where arg0, arg1, . . . argn are the command line arguments.

· the parameters of method main are set as follows:

args[0] is set to arg0,

args[1] is set to arg1,

. . .

Args[n]is set to argn

Example P8

using a command line arguments

Given the following command line to execute program Program8:

java Program8 Banana 25 3.74

We have the following settings of the array args:

args[0]

Banana

args[1]

25

args[2]

3.74

/*----------------------------------------------- Program8 ----------------------------------------------*/

/* Using command line arguments

*/

public class Program8

{

public static void main( String [ ] args )

{

int quantity;

// to hold the quantity of the product

double uprice;

// to hold its unit price

/*---- stop the execution if the user did not type three arguments in the command line---*/

if( args.length != 3 )

{

System.out.println( “This program is terminated!”);

System.out.println(“Because you did not enter the proper number of arguments”);

return;

}

/*----------convert strings for the quantity and the unit price to their values ------------------*/

quantity = Integer.parseInt( args[1] );

uprice = Double.parseDouble( args[2] );

/*------------------Compute and print the price of the product -----------------------------------*/

System.out.println( “The price of the” + args[0] +” is:\t” + ( quantity * uprice ));

}

}

Hands-On I1

Type and execute the program in Example P8.

Source Modules with Two or More Classes

· A Java program source module may contain two or more classes.

· In a source module with two or more classes, a class (static) variable or a class (static) method defined in one class can be specified in another class by preceding its name with the name of the class in which it is defined followed by a period.

· When a source file contains two or more classes, the Java compiler creates a bytecode file for each of the classes in that source file: the bytecode file of a class has the same name as that class with the filename extension .class.

· You execute a program by executing the bytecode file of the class that contains the method main.

Example P9

Program with two classes (each one with class methods) in a source file

/*------------------------------------------------------- Program9 -----------------------------------------------------------*/

/* Read two integer values, compute their product, and the quotient and the remainder in the division

of the first value by the second

*/

import java.util.Scanner;

public class Program9

{

static int quotient;

// to hold the quotient

static int remain;

// to hold the remainder

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*---------------------------Compute and print their product--------------------------------*/

System.out.println(“Their product is:\t” + Program9Methods.computeProd( first, second ) );

/*-------------------Compute and print the quotient and the remainder-------------------*/

if( second == 0 )

System.out.println( “Division by zero is not allowed!”);

else

{

Program9 Methods.computeQuotRem( first, second );

System.out.println(“The quotient is:\t” + quotient );

System.out.println(“The remainder is:\t” + remain );

}

}

}/*---- end of class Program9------*/

class Program9Methods

{

/*---------------------------------------Method computeProd( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

static int computeProd( int num1, int num2)

{

return num1 * num2;

}

/*---------------------------------------Method computeQuotRem( )--------------------------------------*/

/* compute the quotient and the remainder in the division of the first argument by the second

*/

static void computeQuotRem( int num1, int num2)

{

Program9.quotient = num1 / num2;

Program9.remain = num1 % num2;

}

}

· You call an instance method in a class (static) method or an instance method from another class as follows:

· First define and instantiate a reference variable with an object of the class that contains the instance method.

· Follow that variable by a dot (.) which is followed by the name of that method to call it.

Example P10

Program with two classes (one with instance methods) in a source file

/*------------------------------------------ Program10.java file ---------------------------------------------------*/

/* Read two integer values, compute their product, and the quotient and the remainder in the division

of the first value by the second

*/

import java.util.Scanner;

public class Program10

{

static int quotient;

// to hold the quotient

static int remain;

// to hold the remainder

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

Program10Methods objectRef = new Program10Methods ( );

/*---------------------------Compute and print their product--------------------------------*/

System.out.println(“Their product is:\t” + objectRef.computeProd( first, second ) );

/*-------------------Compute and print the quotient and the remainder-------------------*/

if( second == 0 )

System.out.println( “Division by zero is not allowed!”);

else

{

objectRef.computeQuotRem( first, second );

System.out.println(“The quotient is:\t” + quotient );

System.out.println(“The remainder is:\t” + remain );

}

}

}/*---- end of class Program10------*/

/*-------------------------------------- class Program10Methods ------- ------------------------------------------*/

/* Contains the instance methods called in method main in class Program10

*/

class Program10Methods

{

/*---------------------------------------Method computeProd( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

int computeProd( int num1, int num2)

{

return num1 * num2;

}

/*---------------------------------------Method computeQuotRem( )--------------------------------------*/

/* compute the quotient and the remainder in the division of the first argument by the second

*/

int computeQuotRem( int num1, int num2)

{

Program10.quotient = num1 / num2;

Program10.remain = num1 % num2;

}

} /*---- end of class Program10Methods------*/

Exercise I3

Rewrite the java program that you wrote in Exercise I2 with two classes as follows:

The class named ExerciseI3 holds the following:

· The class variable: static Scanner scan;

· the method main.

The class named ExerciseI3Methods holds the following methods:

· the class (static) method double [ ] readTestScores( int size ),

· The instance method char getLetterGrade(double score),

· The class (static) method void printComment(char grade), and

· The instance method void printTestResults(double [ ] testList).

Programs with two or more Source Files

· A Java program may consists of two or more source files.

· The bytecode file of each class of the program is created by compiling each source file.

· However, a source file that contains a class that is referenced in another one that is already compiled will also be compiled automatically.

· For example, the source file Program11Methods.java of Example P11 below will be automatically compiled after you issue the command to compile the source file Program11.java.

Example P11

Program with two or more source files

/*------------------------------------------ Program11.java file ---------------------------------------------------*/

/* Read two integer values, compute their product, and the quotient and the remainder in the division

of the first value by the second

*/

import java.util.Scanner;

public class Program11

{

static int quotient;

// to hold the quotient

static int remain;

// to hold the remainder

public static void main( String [ ] args )

{

Scanner input = new Scanner( System.in );// for standard input

int first,

// to hold the first value

second;

// to hold the second

/*-------------------------------read the two values -------------------------------*/

first = input.nextInt( );

second = input.nextInt( );

/*---------------------------Compute and print their product--------------------------------*/

System.out.println(“Their product is:\t” + Program11Methods.computeProd( first, second ) );

/*-------------------Compute and print the quotient and the remainder-------------------*/

if( second == 0 )

System.out.println( “Division by zero is not allowed!”);

else

{

Program11Methods.computeQuotRem( first, second );

System.out.println(“The quotient is:\t” + quotient );

System.out.println(“The remainder is:\t” + remain );

}

}

}/*---- end of class Program11------*/

/*-------------------------------------- Program11Methods.java file ------------------------------------------*/

/* Contains the class methods called in the source file Program11

*/

public class Program11Methods

{

/*---------------------------------------Method computeProd( )--------------------------------------*/

/* compute the product of two integer values and returns it

*/

static int computeProd( int num1, int num2)

{

return num1 * num2;

}

/*---------------------------------------Method computeQuotRem( )--------------------------------------*/

/* compute the quotient and the remainder in the division of the first argument by the second

*/

static int computeQuotRem( int num1, int num2)

{

Program11.quotient = num1 / num2;

Program11.remain = num1 % num2;

}

} /*---- end of class Program11Methods ------*/

Exercise I4

Rewrite the java program that you wrote in Exercise I3 with two source files as follows:

· The first source file holds the class named ExerciseI4 that holds the following:

· The class variable: static Scanner scan;

· the method main.

The second source file holds the class named ExerciseI4Methods that holds the following methods:

· the class (static) method double [ ] readTestScores( int size ),

· The instance method char getLetterGrade(double score),

· The class (static) method void printComment(char grade), and

· The instance method void printTestResults(double [ ] testList).

Packages and the import Statement

· A package is a named collection of related classes.

· Packages are used to organize classes so that they can be reused in future programs without access to their source codes.

· Java predefined classes that are collectively referred to as Java class library, or the Java Application Programming Interface (Java API) are grouped into packages. A subset of Java API packages is provided in the table that follows:

Package

Description

Java.applet

Contains a class and several interfaces required to create java applets.

Java.awt

Contains the classes and the interfaces required to create and manipulate GUIs in early versions of java.

Java.awt.event

Contains classes and interfaces that enable events handling for GUI components in both java.awt and javax.swing packages.

Java.awt.geom

Contains classes and interfaces for working with java’s advanced two-dimensional graphics capabilities.

Java.io

Contains classes and interfaces that enable programs to do data I/O.

Java.lang

Contains classes and interfaces that are required in many java programs.

Java.net

Contains classes and interfaces that enable programs to communicate via computer networks like the internet.

Java.sql

Contains classes and interfaces for working with databases.

Java.util

Contains classes and interfaces that enable such actions as date and time manipulations, random-number processing, and processing of large amounts of data.

Java.util.concurrent

Contains utility classes and interfaces for implementing programs that perform multiple tasks in parallel.

Java.media

Contains classes and interfaces for working with java’s multimedia capabilities.

Java.swing

Contains classes and interfaces for working with java’s Swing GUI components that provide support for portable GUIs.

Javax.swing.event

Contains classes and interfaces that enable event handling for GUI components in package javax.swing.

Javax.xml.ws

Contains classes and interfaces for working with web services in java.

· To each Java package is associated a directory or folder that contains the bytecode file of each of the classes in that package.

· Classes in the java.lang package are automatically included in every Java program.

· However, in order to use any of the classes in the Java API, you must do one of the following things:

a. Use the entire path with the class name.

b. Import the class.

c. Import the package of which the class you are using is a part.

· The syntax of the import statement to include a class in a program is specified as follows:

import ;

Example:

import java.util.Scanner;

Will include the class Scanner (from the package java.util) in the program.

· The syntax of the import statement to include all the classes in a package in a program is specified as follows:

import .*;

Example:

import java.util.*;

Will include all the classes in the package java.util in the program.

· You must place the import statement before any executable statement in a program.

· There is no disadvantage for including extra classes in a program:

The object of the import statement is simply to notify the compiler that you will be using the variables and methods that are in the included classes.

Example

· The class Scanner of the Java API package java.util contains useful methods to deal with input in a program.

· The object input of the class Scanner (on which input will be performed) can be instantiated in one of the following ways:

1. Instantiate the object using the entire path with the class name:

java.util.Scanner input = new java.util.Scanner( System.in );

2. First import the class Scanner in your program:

import java.util.Scanner;

Then instantiate the object as follows:

Scanner input = new Scanner( System.in );

3. First import all the classes in the package java.util in your program: import java.util.*;

Then instantiate the object as follows:

Scanner input = new Scanner( System.in );

Creating and Using Packages

· By using a package, you can create a class that other programmers can use in their applications, but without having access to its source code.

· The following are the steps for defining and placing a class in a package:

1. Declare the class as a public class: a class that is not public can be used only by other classes in the same package.

2. Choose a unique package name.

3. Add the package statement to the source file that contains the class.

4. Compile the class source file: the corresponding bytecode file will be placed in the package directory/folder.

· Because Java applications are used on the internet, Sun Microsystems (Oracle) has defined a convention for giving a unique name to packages in which you use your internet domain in reverse