bahasa java sawaluddin tutor



st1\:*{behavior:url(#ieooui) }
<!– /* Font Definitions */ @font-face {font-family:Palatino; panose-1:0 0 0 0 0 0 0 0 0 0; mso-font-alt:”Book Antiqua”; mso-font-charset:0; mso-generic-font-family:auto; mso-font-format:other; mso-font-pitch:auto; mso-font-signature:3 0 0 0 1 0;} @font-face {font-family:”Monotype Sorts”; panose-1:0 0 0 0 0 0 0 0 0 0; mso-font-charset:2; mso-generic-font-family:auto; mso-font-format:other; mso-font-pitch:auto; mso-font-signature:0 0 0 0 0 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:””; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:-2; mso-list-type:simple; mso-list-template-ids:112251004;} @list l0:level1 {mso-level-start-at:0; mso-level-number-format:bullet; mso-level-text:*; mso-level-tab-stop:none; mso-level-number-position:left; margin-left:0in; text-indent:0in;} @list l0:level1 lfo1 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:10.0pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo2 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:12.0pt; font-family:”Times New Roman”;} @list l0:level1 lfo3 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:11.5pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo4 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:14.0pt; font-family:”Times New Roman”;} @list l0:level1 lfo5 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:12.0pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo6 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:14.0pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo7 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:10.5pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo8 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:9.0pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo9 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:7.5pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo10 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:12.5pt; font-family:Palatino;} @list l0:level1 lfo11 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:13.0pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo12 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:12.0pt; font-family:”Courier New”;} @list l0:level1 lfo13 {mso-level-numbering:continue; mso-level-text:•; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:8.5pt; font-family:”Times New Roman”;} @list l0:level1 lfo14 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:11.0pt; font-family:”Times New Roman”;} @list l0:level1 lfo15 {mso-level-numbering:continue; mso-level-text:; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:13.5pt; font-family:”Monotype Sorts”;} @list l0:level1 lfo16 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:10.0pt; font-family:”Times New Roman”;} @list l0:level1 lfo17 {mso-level-numbering:continue; mso-level-text:–; mso-level-tab-stop:none; mso-level-number-position:left; mso-level-legacy:yes; mso-level-legacy-indent:0in; mso-level-legacy-space:0in; margin-left:0in; text-indent:0in; mso-ansi-font-size:14.0pt; font-family:”Courier New”;} ol {margin-bottom:0in;} ul {margin-bottom:0in;} –>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:”Table Normal”;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-parent:””;
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:”Times New Roman”;
mso-ansi-language:#0400;
mso-fareast-language:#0400;
mso-bidi-language:#0400;}

Introduction to
Java Programming

Sawaluddin

Introduction

Course Objectives

Course Objectives

FUpon completing the course, you will understand

Create, compile, and run Java programs

Primitive data types

Java control flow

Methods

Arrays (for teaching Java in two semesters, this could be the end)

Object-oriented programming

Core Java classes (Swing, exception, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework)

Course Objectives, cont.

FYou will be able to

Develop programs

Write simple programs using primitive data types, control statements, methods, and arrays.

Create and use methods

Develop a GUI interface and Java applets

Write interesting projects

Establish a firm foundation on Java concepts

Programming Concepts

FProgramming in the Big Picture?

FWhat is JAVA?

Programming in the Big Picture?

F What are Computers Used For?

Word Processing   (i.e., typing up some documents and printing them)

Business Applications   (i.e., accounting, spreadsheets, presentations,…)

Engineering Applications   (i.e., scientific analysis, simulations)

Database Management   (i.e., police records, stock market, …)

Entertainment   (i.e., games, multimedia applications, …)

Manufacturing   (i.e., CAD/CAM, robotics, assembly, …)

Many more things

Who is Involved With Computers ?

FSystem/Hardware Designers (The people that design computers and related products)

FManufacturers (The people that actually build and assemble computers)

FSoftware Designers (The people that design applications to be used with the computers)

FProgrammers (The people that write computer programs to achieve working applications, games and other software packages).

FUser (The people that buy and use the software)

We are going to play the part of the Programmer in this course, although we will also be designing our programs (software) and hence we will also be the Software Designer. When we test our programs, we’ll pretend that we are the User.  Testing is an important part of programming to ensure that the User is happy with software that is not full of Bugs!

What is program?

FA program is traditionally known as

a sequence of instructions that can be executed by a computer to solve some problem.

Here, we will learn to write our own programs to solve some very simple problems.
There are different styles (types) of programming:

procedural (structured)

logical (specifying constraints and conditions)

object-oriented

What is Object Oriented Programming ?

FObject Oriented programming is

a method of programming that allows a programmer to build a more natural model of a “real world” problem within the computer.

based on the creation of objects which often represent their real world equivalent, but not always.

FFor example, consider the following programming scenario and try to come up with some objects that might be used in an object oriented program.  Also, try to think of what operations might be needed to interact with the objects.  That is, what information do we need to know about the objects and how do we get the information ?

Example: An Automated Bank Teller Machine (ATM)

Important Issues When Developing Software:

FThere are several important issues when developing any type of computer software.  Any “good” software MUST adhere to these standards:

FC orrectness – Make sure that your program does what it is supposed to do.

FR obustness – Make sure that the program does not crash.  Exhaustive testing helps prevent this.

FI nterface Usability – Make sure that the interface is easy to use and intuitive.

FS implicity – Keep the code as simple as possible, while still meeting requirements.  Modifications are often required and hence code maintenance is a big issue.

FP resentation and Documentation – Make sure that software is thoroughly documented for maintenance purposes.  (Don’t forget about the TA’s that need to mark your assignments)

FE fficiency – Make sure that the software is time and space efficient.

What Is Java?

FHistory

FCharacteristics of Java

FJAVA is:

An programming language from SUN Microsystems.

Object-Oriented

Interpreted

History

FJames Gosling and Sun Microsystems

FOak

FJava, May 20, 1995, Sun World

FHotJava

The first Java-enabled Web browser

FJDK Evolutions

FJ2SE, J2ME, and J2EE (not mentioned in the book, but could discuss here optionally)

Characteristics of Java

FJava is simple

FJava is object-oriented

FJava is distributed

FJava is interpreted

FJava is robust

FJava is secure

FJava is architecture-neutral

FJava is portable

FJava’s performance

FJava is multithreaded

FJava is dynamic

JDK Versions

FJDK 1.02 (1995)

FJDK 1.1 (1996)

FJava 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)

FJava 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)

FJava 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)

JDK Editions

FJava Standard Edition (J2SE)

J2SE can be used to develop client-side standalone applications or applets.

FJava Enterprise Edition (J2EE)

J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages.

FJava Micro Edition (J2ME).

J2ME can be used to develop applications for mobile devices such as cell phones.

This courses uses J2SE to introduce Java programming.

Java IDE Tools

FForte by Sun MicroSystems

FBorland JBuilder

FMicrosoft Visual J++

FWebGain Café

FIBM Visual Age for Java

FJCreator,

FEtc

FWhen programming in JAVA, you will usually use the following building blocks:

Fclasses from the JAVA class libraries

Fclasses you create yourself

Fclasses that other people make available to you

FMost of the classes that you make will be using other classes by creating and using objects belonging to that class.

FUsing the JAVA class libraries whenever possible is a good idea since

the classes are carefully written and are efficient.

it would be silly to write code that is already available to you.

Getting Started with Java Programming

FA Simple Java Application

FCompiling Programs

FExecuting Applications

A Simple Application

Example 1.1

//This application program prints Welcome

//to Java!

public class Welcome {

public static void main(String[] args) {

System.out.println(“Welcome to Java!”);

}

}

Creating and Compiling Programs

FOn command line

javac file.java

Executing Applications

FOn command line

java classname

Example

javac Welcome.java

java Welcome

output:…

Compiling and Running a Program

Anatomy of a Java Program

FComments

FPackage

FReserved words

FModifiers

FStatements

FBlocks

FClasses

FMethods

FThe main method

Comments

In Java, comments are preceded by two slashes (//) in a line, or enclosed between /* and */ in one or multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */.

Package

The second line in the program (package chapter1;) specifies a package name, chapter1, for the class Welcome. Forte compiles the source code in Welcome.java, generates Welcome.class, and stores Welcome.class in the chapter1 folder.

Reserved Words

Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Other reserved words in Example 1.1 are public, static, and void. Their use will be introduced later in the courses.

Modifiers

Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other programs. A private datum or method cannot be accessed by other programs. Modifiers are discussed in Chapter 6, “Objects and Classes.”

Statements

A statement represents an action or a sequence of actions. The statement System.out.println(“Welcome to Java!”) in the program in Example 1.1 is a statement to display the greeting “Welcome to Java!” Every statement in Java ends with a semicolon (;).

Blocks

Classes

The class is the essential Java construct. A class is a template or blueprint for objects. To program in Java, you must understand classes and be able to write and use them. The mystery of the class will continue to be unveiled throughout this book. For now, though, understand that a program is defined by using one or more classes.

Methods

What is System.out.println? It is a method: a collection of statements that performs a sequence of operations to display a message on the console. It can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed within parentheses. In this case, the argument is “Welcome to Java!” You can call the same println method with a different argument to print a different message.

main Method

The main method provides the control of program flow. The Java interpreter executes the application by invoking the main method.

The main method looks like this:

public static void main(String[] args) {

// Statements;

}

Displaying Text in a Message Dialog Box

you can use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.”

The showMessageDialog Method

JOptionPane.showMessageDialog(null, “Welcome to Java!”,”Example 1.2″, JOptionPane.INFORMATION_MESSAGE));

The exit Method

Use Exit to terminate the program and stop all threads.

NOTE: When your program starts, a thread is spawned to run the program. When the showMessageDialog is invoked, a separate thread is spawned to run this method. The thread is not terminated even you close the dialog box. To terminate the thread, you have to invoke the exit method.

SLIDE 2

Primitive Data Types and Operations

FIntroduce Programming with an Example

Identifiers, Variables, and Constants

FPrimitive Data Types

byte, short, int, long, float, double, char, boolean

FExpressions

FOperators, Precedence, Associativity, Operand Evaluation Order: ++, –, *, /, %, +=, -=, *=, /=, %=, ^, &, |, +, -,

FGetting Input from Input Dialog Boxes

FCase Studies (Computing Mortgage, and Computing Changes)

FStyle and Documentation Guidelines

FSyntax Errors, Runtime Errors, and Logic Errors

Introducing Programming with an Example

Example 2.1 Computing the Area of a Circle

This program computes the area of the circle.

Identifiers

FAn identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).

FAn identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.

FAn identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words).

FAn identifier cannot be true, false, or
null.

FAn identifier can be of any length.

Variables

// Compute the first area

radius = 1.0;

area = radius*radius*3.14159;

System.out.println(“The area is “ + area + ” for radius “+radius);

// Compute the second area

radius = 2.0;

area = radius*radius*3.14159;

System.out.println(“The area is “ + area + ” for radius “+radius);

Declaring Variables

int x; // Declare x to be an

// integer variable;

double radius; // Declare radius to

// be a double variable;

char a; // Declare a to be a

// character variable;

Assignment Statements

x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;

a = ‘A’; // Assign ‘A’ to a;

Declaring and Initializing
in One Step

Fint x = 1;

Fdouble d = 1.4;

Ffloat f = 1.4;

Is this statement correct?

Constants

final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;

final int SIZE = 3;

Numerical Data Types

byte 8 bits

short 16 bits

int 32 bits

long 64 bits

float 32 bits

double 64 bits

Operators

+, -, *, /, and %

5/2 yields an integer 2.

5.0/2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

NOTE

Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,

System.out.println(1 – 0.1 – 0.1 – 0.1 – 0.1 – 0.1);

displays 0.5000000000000001, not 0.5, and

System.out.println(1.0 – 0.9);

displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.

Number Literals

A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements:

int i = 34;

long l = 1000000;

double d = 5.0;

Integer Literals

An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type.

An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one).

Floating-Point Literals

Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.

Scientific Notation

Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase.

Arithmetic Expressions

Shortcut Assignment Operators

Increment and
Decrement Operators

Increment and
Decrement Operators, cont.

Increment and
Decrement Operators, cont.

Assignment Expressions and Assignment Statements

Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements:

variable op= expression; // Where op is +, -, *, /, or %

++variable;

variable++;

–variable;

variable–;

Numeric Type Conversion

Consider the following statements:

byte i = 100;

long k = i*3+4;

double d = i*3.1+k/2;

int x = k; //(Wrong)

long k = x; //(fine,implicit casting)

Type Casting

Fdouble

Ffloat

Flong

Fint

Fshort

Fbyte

Type Casting, cont.

Implicit casting

double d = 3; (type widening)

Explicit casting

int i = (int)3.0; (type narrowing)

What is wrong? int x = 5/2.0;

Character Data Type

char letter = ‘A’; (ASCII)

char numChar = ‘4’; (ASCII)

char letter = ‘\u0041’; (Unicode)

char numChar = ‘\u0034’; (Unicode)

Special characters

char tab = ‘\t’;

Unicode Format

Appendix B: ASCII Character Set

ASCII Character Set, cont.

Casting between char and Numeric Types

The boolean Type and Operators

boolean lightsOn = true;

boolean lightsOn = false;

boolean b = (1 > 2);

F&& (and) (1 < x) && (x < 100)

F|| (or) (lightsOn) || (isDayTime)

F! (not) !(isStopped)

Comparison Operators

Boolean Operators

Truth Table for Operator !

Truth Table for Operator &&

Truth Table for Operator ||

Truth Table for Operator ^

The & and | Operators

&&: conditional AND operator

&: unconditional AND operator

||: conditional OR operator

|: unconditional OR operator

exp1 && exp2

(1 < x) && (x < 100)

(1 < x) & (x < 100)

The & and | Operators

If x is 1, what is x after this expression?

(x > 1) & (x++ < 10)

If x is 1, what is x after this expression?

(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?

(1 == x) || (10 > x++)?

Operator Precedence

How to evaluate

3 + 4 * 4 > 5 * (4 + 3) – ++i

Operator Precedence

Fvar++, var–

F+, – (Unary plus and minus), ++var,–var

F(type) Casting

F! (Not)

F*, /, % (Multiplication, division, and modulus)

F+, – (Binary addition and subtraction)

F<, <=, >, >= (Comparison)

F==, !=; (Equality)

F& (Unconditional AND)

F^ (Exclusive OR)

F| (Unconditional OR)

F&& (Conditional AND) Short-circuit AND

F|| (Conditional OR) Short-circuit OR

F=, +=, -=, *=, /=, %= (Assignment operator)

Operator Associativity

When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative.

a – b + c – d is equivalent to  ((a – b) + c) – d

Assignment operators are right-associative. Therefore, the expression

a = b += c = 5 is equivalent to a = (b += (c = 5))

Operand Evaluation Order

The precedence and associativity rules specify the order of the operators, but do not specify the order in which the operands of a binary operator are evaluated. Operands are evaluated from left to right in Java.

The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated.

Operand Evaluation Order, cont.

If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code, because a is evaluated to 0 before ++a is evaluated to 1.

int a = 0;

int x = a + (++a);

But x becomes 2 in the following code, because ++a is evaluated to 1, then a is evaluated to 1.

int a = 0;

int x = ++a + a;

Getting Input from Input Dialog Boxes

String string = JOptionPane.showInputDialog(

null, “Prompt Message”, “Dialog Title”,

JOptionPane.QUESTION_MESSAGE));

where x is a string for the prompting message and y is a string for the title of the input dialog box.

Convertting Strings to Integers

The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number.

To convert a string into an int value, you can use the static parseInt method in the Integer class as follows:

int intValue = Integer.parseInt(intString);

where intString is a numeric string such as “123”.

Convertting Strings to Doubles

To convert a string into a double value, you can use the static parseDouble method in the Double class as follows:

double doubleValue =Double.parseDouble(doubleString);

where doubleString is a numeric string such as “123.45”.

Example 2.2
Entering Input from Dialog Boxes

Example 2.3
Computing Mortgages

Example 2.4
Computing Changes

Programming Style and Documentation

FAppropriate Comments

FNaming Conventions

FProper Indentation and Spacing Lines

FBlock Styles

Appropriate Comments

Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses.

Include your name, class section, instruction, date, and a brief description at the beginning of the program.

Naming Conventions

FChoose meaningful and descriptive names.

FVariables and method names:

Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.

Naming Conventions, cont.

FClass names:

Capitalize the first letter of each word in the name. For example, the class name ComputeArea.

FConstants:

Capitalize all letters in constants. For example, the constant PI.

Proper Indentation and Spacing

FIndentation

Indent two spaces.

FSpacing

Use blank line to separate segments of the code.

Block Styles

Use end-of-line style for braces.

Programming Errors

FSyntax Errors

Detected by the compiler

FRuntime Errors

Causes the program to abort

FLogic Errors

Produces incorrect result

Compilation Errors

public class ShowSyntaxErrors {

public static void main(String[] args) {

i = 30;

System.out.println(i+4);

}

}

Runtime Errors

public class ShowRuntimeErrors {

public static void main(String[] args) {

int i = 1 / 0;

}

}

Logic Errors

public class ShowLogicErrors {

// Determine if a number is between 1 and 100 inclusively

public static void main(String[] args) {

// Prompt the user to enter a number

String input = JOptionPane.showInputDialog(null,

“Please enter an integer:”,

“ShowLogicErrors”, JOptionPane.QUESTION_MESSAGE);

int number = Integer.parseInt(input);

// Display the result

System.out.println(“The number is between 1 and 100, ” +

“inclusively? ” + ((1 < number) && (number < 100)));

System.exit(0);

}

}

SLIDE 3

Control Statements

Selection Statements

if Statements

if (booleanExpression) {

statement(s);

}

Example:

if ((i > 0) && (i < 10)) {

System.out.println(“i is an ” +

“integer between 0 and 10”);

}

Caution

Adding a semicolon at the end of an if clause is a common mistake.

if (radius >= 0);

{

area = radius*radius*PI;

System.out.println(

“The area for the circle of radius ” +

radius + ” is ” + area);

}

This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.

This error often occurs when you use the next-line block style.

The if…else Statement

if (booleanExpression) {

statement(s)-for-the-true-case;

}

else {

statement(s)-for-the-false-case;

}

if…else Example

if (radius >= 0) {

area = radius*radius*PI;

System.out.println(“The area for the “

+ “circle of radius ” + radius +

” is ” + area);

}

else {

System.out.println(“Negative input”);

}

Multiple Alternative if Statements

if (score >= 90)

grade = ‘A’;

else

if (score >= 80)

grade = ‘B’;

else

if (score >= 70)

grade = ‘C’;

else

if (score >= 60)

grade = ‘D’;

else

grade = ‘F’;

Note

The else clause matches the most recent if clause in the same block. For example, the following statement

int i = 1; int j = 2; int k = 3;

if (i > j)

if (i > k)

System.out.println(“A”);

else

System.out.println(“B”);

is equivalent to

int i = 1; int j = 2; int k = 3;

if (i > j)

if (i > k)

System.out.println(“A”);

else

System.out.println(“B”);

Note, cont.

Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces:

int i = 1;

int j = 2;

int k = 3;

if (i > j) {

if (i > k)

System.out.println(“A”);

}

else

System.out.println(“B”);

This statement prints B.

Nested if Statements

Example 3.1 Using Nested if Statements

This program reads in number of years and loan amount and computes the monthly payment and total payment. The interest rate is determined by number of years.

switch Statements

switch (year) {

case 7: annualInterestRate = 7.25;

break;

case 15: annualInterestRate = 8.50;

break;

case 30: annualInterestRate = 9.0;

break;

default: System.out.println(

“Wrong number of years, enter 7, 15, or 30”);

}

switch Statement Flow Chart

switch Statement Rules

The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.


The value1, …, and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. (The case statements are executed in sequential order.)

The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.

switch Statement Rules, cont.

The default case, which is optional, can be used to perform actions when none of the specified cases is true.

·      

The order of the cases (including the default case) does not matter. However, it is a good programming style to follow the logical sequence of the cases and place the default case at the end.

Caution

Do not forget to use a break statement when one is needed. For example, the following code always displays Wrong number of years regardless of what numOfYears is. Suppose the numOfYears is 15. The statement annualInterestRate = 8.50 is executed, then the statement annualInterestRate = 9.0, and finally the statement System.out.println(“Wrong number of years”).

switch (numOfYears) {

case 7: annualInterestRate = 7.25;

case 15: annualInterestRate = 8.50;

case 30: annualInterestRate = 9.0;

default: System.out.println(“Wrong number of years”);

}

Conditional Operator

if (x > 0) y = 1

else y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;

Ternary operator

Binary operator

Unary operator

Conditional Operator

if (num % 2 == 0)

System.out.println(num + “is even”);

else

System.out.println(num + “is odd”);

System.out.println(

(num % 2 == 0)? num + “is even” :

num + “is odd”);

Conditional Operator, cont.

(booleanExp) ? exp1 : exp2

Repetitions

while Loop Flow Chart

while Loop Flow Chart, cont.

Example 3.2: Using while Loops

TestWhile.java

Caution

Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0.

// data should be zero

double data = Math.pow(Math.sqrt(2), 2) – 2;

if (data == 0)

System.out.println(“data is zero”);

else

System.out.println(“data is not zero”);

do-while Loop

for Loops

for (initial-action; loop-continuation-condition; action-after-each-iteration) {

//loop body;

}

int i = 0;

while (i < 100) {

System.out.println(“Welcome to Java! ” + i);

i++;

}

Example:

int i;

for (i = 0; i < 100; i++) {

System.out.println(“Welcome to Java! ” + i);

}

for Loop Flow Chart

for Loop Example

for Loop Examples

Which Loop to Use?

Caution

Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:

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

{

System.out.println(“i is ” + i);

}

Caution, cont.

Similarly, the following loop is also wrong:

int i=0;

while (i<10);

{

System.out.println(“i is ” + i);

i++;

}

In the case of the do loop, the following semicolon is needed to end the loop.

int i=0;

do {

System.out.println(“i is ” + i);

i++;

} while (i<10);

The break Keyword

The continue Keyword

Using break and continue

Example 3.7
Finding the Sales Amount

Example 3.8
Displaying a Pyramid of Numbers

Example 3.9
Displaying Prime Numbers

SLIDE 4

Kuliah 4 – Methods

FIntroducing Methods

Benefits of methods, Declaring Methods, and Calling Methods

FPassing Parameters

Pass by Value

FOverloading Methods

Ambiguous Invocation

FScope of Local Variables

FMethod Abstraction

FThe Math Class

FCase Studies

FRecursion (Optional)

Introducing Methods

Introducing Methods, cont.

Declaring Methods

public static int max(int num1, int num2) {

if (num1 > num2)

return num1;

else

return num2;

}

Calling Methods

public class MaxBilangan {

pubic static int max(int num1, int num2) {

if (num1 > num2)

return num1;

else

return num2;

}

public static void main(String args[]) {

int i = 5, j = 2 ;

int k =max(i,j) ;

System.out.println(“The maximum “ + i + “ and “ + j

“ is “ + k ) ;

}

}

Calling Methods, cont.

Calling Methods, cont.

CAUTION

A 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.

Passing Parameters

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

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

System.out.println(message);

}

Pass by Value

public class passbyValue {

public static void swap(int n1, int n2) {

int temp ;

temp = n1 ;

n1 = n2 ;

n2 = temp ;

System.out.println(“Nilai n1 dan n2 dalam method “

+ “n1 = “+ n1 + ” dan n2 = “+ n2);

}

public static void main(String args[]){

int n1 = 9, n2 = 5 ;

swap(n1,n2);

System.out.println(“Nilai n1 dan n2 diluar method “

+ “n1 = “+ n1 + ” dan n2 = “+ n2)

}

}

Pass by Value, cont.

Overloading Methods

Example 4.3 Overloading the max Method

public static double max(double num1, double num2) {

if (num1 > num2)

return num1;

else

return num2;

}

Ambiguous Invocation

Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

Ambiguous Invocation

public class AmbiguousOverloading {

public static void main(String[] args) {

System.out.println(max(1, 2));

}

public static double max(int num1, double num2) {

if (num1 > num2)

return num1;

else

return num2;

}

public static double max(double num1, int num2) {

if (num1 > num2)

return num1;

else

return num2;

}

}

Scope of Local Variables

A local variable: a variable defined inside a method.

Scope: the part of the program where the variable can be referenced.

The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.

Scope of Local Variables, cont.

You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. Thus, the following code is correct.

Scope of Local Variables, cont.

Scope of Local Variables, cont.

Method Abstraction

You can think of the method body as a black box that contains the detailed implementation for the method.

Benefits of Methods

The Math Class

FClass constants:

PI

E

FClass methods:

Trigonometric Methods

Exponent Methods

Rounding Methods

min, max, abs, and random Methods

Trigonometric Methods

Fsin(double a)

Fcos(double a)

Ftan(double a)

Facos(double a)

Fasin(double a)

Fatan(double a)

Exponent Methods

Fexp(double a)

Returns e raised to the power of a.

Flog(double a)

Returns the natural logarithm of a.

Fpow(double a, double b)

Returns a raised to the power of b.

Fsqrt(double a)

Returns the square root of a.

Rounding Methods

Fdouble ceil(double x)

x rounded up to its nearest integer. This integer is returned as a double value.

Fdouble floor(double x)

x is rounded down to its nearest integer. This integer is returned as a double value.

Fdouble rint(double x)

x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.

Fint round(float x)

Return (int)Math.floor(x+0.5).

Flong round(double x)

Return (long)Math.floor(x+0.5).

min, max, abs, and random

Fmax(a, b)and min(a, b)

Returns the maximum or minimum of two parameters.

Fabs(a)

Returns the absolute value of the parameter.

Frandom()

Returns a random double value
in the range [0.0, 1.0).

Example 4.4 Computing Mean and Standard Deviation

Generate 10 random numbers and compute the mean and standard deviation

Example 4.5 Obtaining Random Characters

Write the methods for generating random characters. The program uses these methods to generate 175 random characters between ‘!’ and ‘~’ and displays 25 characters per line. To find out the characters between ‘!’ and ‘~’, see Appendix B, “The ASCII Character Set.”

Example 4.5 Obtaining Random Characters, cont.

Case Studies

Example 4.6 Displaying Calendars

The program reads in the month and year and displays the calendar for a given month of the year.

Design Diagram

Recursion (Optional)

Example 4.7 Computing Factorial

factorial(0) = 1;

factorial(n) = n*factorial(n-1);

Example 4.7 Computing Factorial, cont.

Example 4.7 Computing Factorial, cont.

Fibonacci Numbers

Example 4.8 Computing Finonacci Numbers

0 1 1 2 3 5 8 13 21 34 55 89…

f0 f1

fib(2) = fib(0) + fib(1);

Fibonacci Numbers, cont

Fibonnaci Numbers, cont.

Towers of Hanoi

Example 4.9 Solving the Towers of Hanoi Problem

Solve the towers of Hanoi problem.

Towers of Hanoi, cont.

SLIDE 5

Kuliah 5 – Arrays

FIntroducing Arrays

FDeclaring Array Variables, Creating Arrays, and Initializing Arrays

FPassing Arrays to Methods

FCopying Arrays

FMultidimensional Arrays

FSearch and Sorting Methods

Introducing Arrays

Declaring Array Variables

Fdatatype[] arrayname;

Example:

double[] myList;

Fdatatype arrayname[];

Example:

double myList[];

Creating Arrays

arrayName = new datatype[arraySize];

Example:

myList = new double[10];

myList[0] references the first element in the array.

myList[9] references the last element in the array.

Declaring and Creating
in One Step

Fdatatype[] arrayname = new

datatype[arraySize];

double[] myList = new double[10];

Fdatatype arrayname[] = new
datatype[arraySize];

double myList[] = new double[10];

The Length of Arrays

FOnce 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

Initializing Arrays

FUsing a loop:

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

myList[i] = i;

FDeclaring, creating, initializing in one step:

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

This shorthand syntax must be in one statement.

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;

CAUTION

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

Example 5.1
Testing Arrays

FObjective: The program receives 6 numbers from the keyboard, finds the largest number and counts the occurrence of the largest number entered from the keyboard.

Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4.

Example 5.2
Assigning Grades

FObjective: read student scores (int) from the keyboard, get the best score, and then assign grades based on the following scheme:

Grade is A if score is >= best–10;

Grade is B if score is >= best–20;

Grade is C if score is >= best–30;

Grade is D if score is >= best–40;

Grade is F otherwise.

Passing Arrays to Methods

Java uses pass by value to pass parameters to a method. There are important differences between passing a value of variables of primitive data types and passing arrays.

F For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method.

F For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.

Example 5.3
Passing Arrays as Arguments

FObjective: Demonstrate differences of passing primitive data type variables and array variables.

Example 5.3, cont.

Example 5.4 Computing Deviation Using Arrays

Example 5.5
Counting Occurrence of Each Letter

FGenerate 100 lowercase letters randomly and assign to an array of characters.

FCount the occurrence of each letter in the array.

FFind the mean and standard deviation of the counts.

Example 5.6
Copying Arrays

In this example, you will see that a simple assignment cannot copy arrays in the following program. The program simply creates two arrays and attempts to copy one to the other, using an assignment statement.

Copying Arrays

Copying Arrays

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

The arraycopy Utility

arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);

Example:

System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Multidimensional Arrays

Declaring Variables of Multidimensional Arrays and Creating Multidimensional Arrays

int[][] matrix = new int[10][10];

or

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

Multidimensional Array Illustration

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;

Lengths of Multidimensional Arrays

int[][] array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9},

{10, 11, 12}

};

array.length

array[0].length

array[1].length

array[2].length

Ragged Arrays

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

};

Example 5.7
Adding and Multiplying Two Matrices

FObjective: Use two-dimensional arrays to create two matrices, and then add and multiply the two matrices.

Example 5.7 (cont) Adding and Multiplying Two Matrices

Example 5.8
Grading Multiple-Choice Test

FObjective: write a program that grades multiple-choice test.

Example 5.9
Calculating Total Scores

FObjective: write a program that calculates the total score for students in a class. Suppose the scores are stored in a three-dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts–the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i’s student on the j’s exam. Your program displays the total score for each student, .

Searching Arrays

Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching, like sorting, is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search.

Linear Search

The linear search approach compares the key element, key, with each element in the array list[]. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.

Example 5.10
Testing Linear Search

FObjective: Implement and test the linear search method by creating an array of 10 elements of int type randomly and then display this array. Prompt the user to enter a key for testing the linear search.

Binary Search

For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order.

e.g. 2 4 7 10 11 45 50 59 60 66 69 70 79

The binary search first compares the key with the element in the middle of the array. Consider the following three cases:

Binary Search, cont.

·  If the key is less than the middle element, you only need to search the key in the first half of the array.

·  If the key is equal to the middle element, the search ends with a match.

·  If the key is greater than the middle element, you only need to search the key in the second half of the array.

Binary Search, cont.

Example 5.11
Testing Binary Search

FObjective: Implement and test the binary search method. The program first creates an array of 10 elements of int type. It displays this array and then prompts the user to enter a key for testing binary search.

Example 5.12
Using Arrays in Sorting

FObjective: Use the selectionSort method to write a program that will sort a list of double floating-point numbers.

int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

Sort it to produce 1, 2, 4, 5, 6, 8, 9

2, 9, 5, 4, 8, 1, 6

Example 5.12: (Cont) Using Arrays in Sorting

int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

Find the largest element in myList and swap it with the last element in myList.

2, 9, 5, 4, 8, 1, 6 => 2, 6, 5, 4, 8, 1, 9 (size = 7)

2, 6, 5, 4, 8, 1 => 2, 6, 5, 4, 1, 8 (size = 6)

2, 6, 5, 4, 1 => 2, 1, 5, 4, 6 (size = 5)

2, 1, 5, 4 => 2, 1, 4, 5

2, 1, 4 => 2, 1, 4,

2, 1 => 1, 2

Sort it to produce 1, 2, 4, 5, 6, 8, 9

Exercise 5.5: Bubble Sort

int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted

Pass 1: 2, 5, 4, 8, 1, 6, 9

Pass 2: 2, 4, 5, 1, 6, 8, 9

Pass 3: 2, 4, 1, 5, 6, 8, 9

Pass 4: 2, 1, 4, 5, 6, 8, 9

Pass 5: 1, 2, 4, 5, 6, 8, 9

Pass 6: 1, 2, 4, 5, 6, 8, 9

Tinggalkan Balasan

Please log in using one of these methods to post your comment:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s