diktat java console

311
Java Programming (Console) Hands on Lab September 2011 For the latest information, please see bluejack.binus.ac.id

Upload: agus-riady-thedyus

Post on 16-Oct-2014

139 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Diktat Java Console

Java Programming (Console)

Hands on Lab

September 2011

For the latest information, please see bluejack.binus.ac.id

Page 2: Diktat Java Console

i | P a g e

Information in this document, including URL and other Internet Web site references, is

subject to change without notice. This document supports a preliminary release of software

that may be changed substantially prior to final commercial release, and is the proprietary

information of Binus University.

This document is for informational purposes only. BINUS UNIVERSITY MAKES NO

WARRANTIES, EITHER EXPRESS OR IMPLIED, AS TO THE INFORMATION IN THIS

DOCUMENT.

The entire risk of the use or the results from the use of this document remains with the

user. Complying with all applicable copyright laws is the responsibility of the user. Without

limiting the rights under copyright, no part of this document may be reproduced, stored in

or introduced into a retrieval system, or transmitted in any form or by any means

(electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without

the express written permission of Binus University.

Binus University may have patents, patent applications, trademarks, copyrights, or other

intellectual property rights covering subject matter in this document. Except as expressly

provided in any written license agreement from Binus University, the furnishing of this

document does not give you any license to these patents, trademarks, copyrights, or other

intellectual property.

Unless otherwise noted, the example companies, organizations, products, domain names, e-

mail addresses, logos, people, places and events depicted herein are fictitious, and no

association with any real company, organization, product, domain name, email address,

logo, person, place or event is intended or should be inferred.

© 2011 Binus University. All rights reserved.

The names of actual companies and products mentioned herein may be the trademarks of

their respective owners.

Page 3: Diktat Java Console

ii | P a g e

Table of Contents

OVERVIEW ..................................................................................................... iii Chapter 01 ...................................................................................................... 1 Introduction to Java Programming ...................................................................... 1 Chapter 02 .................................................................................................... 13 Data Type and I/O.......................................................................................... 13 Chapter 03 .................................................................................................... 34 Arithmetic Operation ...................................................................................... 34 Chapter 04 .................................................................................................... 42 Selection Statement ....................................................................................... 42 Chapter 05 .................................................................................................... 53 Iteration Statement, Jump Operator ................................................................. 53 Chapter 06 .................................................................................................... 62 Exception Handling ......................................................................................... 62 Chapter 07 .................................................................................................... 71 Array ............................................................................................................ 71 Chapter 08 .................................................................................................... 91 Methods ........................................................................................................ 91 Chapter 09 .................................................................................................. 107 Recursion .................................................................................................... 107 Chapter 10 .................................................................................................. 121 Sorting ....................................................................................................... 121 Chapter 11 .................................................................................................. 133 Utility ......................................................................................................... 133 Chapter 12 .................................................................................................. 145 Introduction to OOP Concept ......................................................................... 145 Chapter 13 .................................................................................................. 148 Class and Object .......................................................................................... 148 Chapter 14 .................................................................................................. 156 Encapsulation .............................................................................................. 156 Chapter 15 .................................................................................................. 174 Inheritance .................................................................................................. 174 Chapter 16 .................................................................................................. 196 Polymorphism .............................................................................................. 196 Chapter 17 .................................................................................................. 222 Abstract and Interface .................................................................................. 222 Chapter 18 .................................................................................................. 240 Package ...................................................................................................... 240 Chapter 19 .................................................................................................. 259 Basic Class in Java ....................................................................................... 259 Chapter 20 .................................................................................................. 271 Data Structure in Java .................................................................................. 271 Chapter 21 .................................................................................................. 282 File ............................................................................................................. 282 Chapter 22 .................................................................................................. 295 Thread ........................................................................................................ 295 Chapter 23 .................................................................................................. 301 Generic ....................................................................................................... 301

Page 4: Diktat Java Console

iii | P a g e

OVERVIEW

Chapter 01

• Introduction to Java Programming

Chapter 02

• Data Type and I/O

Chapter 03

• Arithmetic Operation

Chapter 04

• Selection Statement

Chapter 05

• Iteration Statement, Jump Operator

Chapter 06

Exception Handling

Chapter 07

• Array : One Dimentional Array, Two Dimentional Array and Ragged Array

Chapter 08

• Methods

Chapter 09

• Recursion

Page 5: Diktat Java Console

iv | P a g e

Chapter 10

• Sorting : Using Bubble Sort, Selection Sort, Insertion Sort, and Merge Sort

Chapter 11

• Utility : Using Execution Delay, Java Random C, Currency, Calendar, and Timer Class

Chapter 12

• Introduction to OOP Concept

Chapter 13

• Class and Object

Chapter 14

• Encapsulation

Chapter 15

• Inheritance

Chapter 16

• Polymorphism

Chapter 17

• Abstract and Interface

Chapter 18

• Package

Page 6: Diktat Java Console

v | P a g e

SYSTEM REQUIREMENT

Hardware:

o Minimum:

1.6 GHz CPU, 192 MB RAM, 1024x768 display, 5400 RPM hard disk

o Recommended:

2.2 GHz, 384 MB, 1280x1024 display, 7200 RPM or higher.

o On Windows Vista:

2.4 GHz CPU, 768 MB RAM

Software:

o Textpad 5

o Eclipse

o 1.3 GB of available disk space for the full install

Page 7: Diktat Java Console

1 | P a g e

Chapter 01

Introduction to Java Programming

Page 8: Diktat Java Console

2 | P a g e

Introduction to Java IDE and Java Editor [Eclipse and Netbeans]

An integrated development environment (IDE) (also known as integrated

design environment or integrated debugging environment) is a software

application that provides comprehensive facilities to computer programmers for software

development. An IDE normally consists of:

a source code editor

a compiler and/or an interpreter

build automation tools

a debugger

Sometimes a version control system and various tools are integrated to simplify

the construction of a GUI. Many modern IDEs also have a class browser, an object

inspector, and a class hierarchydiagram, for use with object-oriented software

development. There are many Java IDE such as Dr.Java,BlueJ,NetBeans, IntelliJ IDEA,

Eclipse,Oracle JDeveloper, XinoxJCreator.

NetBeans refers to both a platform framework for Java desktop applications,

and an integrated development environment (IDE) for developing with Java, JavaScript,

PHP, Python, Ruby, Groovy, C, C++, Scala, Clojure, and others.

The NetBeans IDE is written in Java and can run anywhere a JVM is installed,

including Windows, Mac OS, Linux, and Solaris. A JDK is required for Java development

functionality, but is not required for development in other programming languages.

The NetBeans Platform allows applications to be developed from a set of modular

software components called modules. Applications based on the NetBeans platform

(including the NetBeans IDE) can be extended by third party developers.

Eclipse is a multi-language software development environment comprising an

integrated development environment (IDE) and an extensible plug-in system. It is

written mostly in Java and can be used to develop applications in Java and, by means of

various plug-ins, other programming languages including Ada, C, C++, COBOL, Perl,

PHP, Python, Ruby (including Ruby on Rails framework), Scala, Clojure, and Scheme.

The IDE is often called Eclipse ADT for Ada, Eclipse CDT for C/C++, Eclipse JDT for Java,

and Eclipse PDT for PHP.

Page 9: Diktat Java Console

3 | P a g e

Introduction to Java Language

Java is a programming language originally developed by James Gosling at Sun

Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as

a core component of Sun Microsystems' Java platform. The language derives much of its

syntax from C and C++ but has a simpler object model and fewer low-level facilities.

Java applications are typically compiled to bytecode (class file) thatcan run on any

Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-

purpose, concurrent, class-based, object-oriented language that is specifically designed

to have as few implementation dependencies as possible. It is intended to let application

developers "write once, run anywhere".

Java is currently one of the most popular programming languages in use, and is

widely used from application software to web applications.

The original and reference implementation Java compilers, virtual machines, and

class libraries were developed by Sun from 1995. As of May 2007, in compliance with

the specifications of the Java Community Process, Sun relicensed most of its Java

technologies under the GNU General Public License. Others have also developed

alternative implementations of these Sun technologies, such as the GNU Compiler for

Java, GNU Classpath, and Dalvik.

One characteristic of Java is portability, which means that computer programs

written in the Java language must run similarly on any supported hardware/operating-

system platform. This is achieved by compiling the Java language code to an

intermediate representation called Java bytecode, instead of directly to platform-specific

machine code. Java bytecode instructions are analogous to machine code, but are

intended to be interpreted by a virtual machine (VM) written specifically for the host

Page 10: Diktat Java Console

4 | P a g e

hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their

own machine for standalone Java applications, or in a Web browser for Java applets.

Standardized libraries provide a generic way to access host-specific features such

as graphics, threading, and networking.

A major benefit of using bytecode is porting. However, the overhead of

interpretation means that interpreted programs almost always run more slowly than

programs compiled to native executables would. Just-in-Time compilers were introduced

from an early stage that compilebytecodes to machine code during runtime.

Advantages of JAVA

1. JAVA offers a number of advantages to developers.

2. Java is simple: Java was designed to be easy to use and is therefore easy to

write, compile, debug, and learn than other programming languages. The reason

that why Java is much simpler than C++ is because Java uses automatic memory

allocation and garbage collection where else C++ requires the programmer to

allocate memory and to collect garbage.

3. Java is object-oriented: Java is object-oriented because programming in Java is

centered on creating objects, manipulating objects, and making objects work

together. This allows you to create modular programs and reusable code.

4. Java is platform-independent: One of the most significant advantages of Java is

its ability to move easily from one computer system to another.

5. The ability to run the same program on many different systems is crucial to

World Wide Web software, and Java succeeds at this by being platform-

independent at both the source and binary levels.

6. Java is distributed: Distributed computing involves several computers on a

network working together. Java is designed to make distributed computing easy

with the networking capability that is inherently integrated into it.

7. Writing network programs in Java is like sending and receiving data to and from

a file. For example, the diagram below shows three programs running on three

different systems, communicating with each other to perform a joint task.

8. Java is interpreted: An interpreter is needed in order to run Java programs. The

programs are compiled into Java Virtual Machine code called bytecode.

9. The bytecode is machine independent and is able to run on any machine that has

a Java interpreter. With Java, the program need only be compiled once, and the

bytecode generated by the Java compiler can run on any platform.

Page 11: Diktat Java Console

5 | P a g e

10. Java is secure: Java is one of the first programming languages to consider

security as part of its design. The Java language, compiler, interpreter, and

runtime environment were each developed with security in mind.

11. Java is robust: Robust means reliable and no programming language can really

assure reliability. Java puts a lot of emphasis on early checking for possible

errors, as Java compilers are able to detect many problems that would first show

up during execution time in other languages.

12. Java is multithreaded: Multithreaded is the capability for a program to perform

several tasks simultaneously within a program. In Java, multithreaded

programming has been smoothly integrated into it, while in other languages,

operating system-specific procedures have to be called in order to enable

multithreading. Multithreading is a necessity in visual and network programming.

Disadvantages of JAVA

1. Performance: Java can be perceived as significantly slower and more memory-

consuming than natively compiled languages such as C or C++.

2. Look and feel: The default look and feel of GUI applications written in Java using

the Swing toolkit is very different from native applications. It is possible to

specify a different look and feel through the pluggable look and feel system of

Swing.

3. Single-paradigm language: Java is predominantly a single-paradigm language.

However, with the addition of static imports in Java 5.0 the procedural paradigm

is better accommodated than in earlier versions of Java.

Compile, Run & Debug

Compile,Run and Debug in Java we can use Java Compiler.A Java compiler is a

compiler for the Java programming language. The most common form of output from a

Java compiler areJava class files containing platform-neutral Java bytecode. There exist

also compilers emitting optimized native machine code for a particular

hardware/operating system combination.

Most Java-to-bytecode compilers, likes being a well-known exception, do virtually

no optimization, leaving this until runtime to be done by the JREThe Java Virtual

Page 12: Diktat Java Console

6 | P a g e

Machine (JVM) loads the class files and either interprets the bytecode or just-in-time

compiles it to machine code and then possibly optimizes it using dynamic compilation.

The very first Java compiler developed by Sun Microsystems was written in C

using some libraries from C++.

To compile and run Java programs on your computer, you need to have a

working installation of the Java Development Kit (JDK) from Sun Microsystems. The JDK

includes command-line commands to compile and run Java programs.

Java program normally go through five phases. These are:

Compile Edit Load Verify Execute

Java Bytecode

JVM

Any Computer

Page 13: Diktat Java Console

7 | P a g e

Creating a Java Application

After learning the theory about Java Language, let’s start learning how to make a

simple Java Application by creating the classic ―Hello World‖ Program.

First, open up your editor and write these line of codes in your editor.

publicclass Main {

publicstaticvoid main(String[] args) {

System.out.println("Hello World!");

}

}

As you can see in the code above, Java code mainly has two main parts :

1. The public class parts, this is called Class Definition, because Java is an

Object Oriented Programming Language all Java Program is builtfrom a class.

2. The public static void main parts, this is the main() method where all Java

program is being invoked, all code in main() method will be executed first when

your program runs.

You will see on the code above, the Syntax we use to print something to our

console window is the System.out.println("Hello World!");this code will print ―Hello

World!‖ in your console window!

1. Exercise

Q: What is JVM used for?

A: Java Virtual Machine (JVM) is used for enabling a set of computer software

programs and data structures to use a virtual machine model for the execution of other

computer programs and scripts.

Q: Mention five primary goals in the creation of the Java language!

A:

1. It should be "simple, object-oriented, and familiar".

2. It should be "robust and secure".

3. It should be "architecture neutral and portable".

4. It should execute with "high performance".

5. It should be "interpreted, threaded, and dynamic".

Page 14: Diktat Java Console

8 | P a g e

Q :What releases of Java technology are currently available? What do they

contain?

A: The Java programming language is currently shipping from Sun Microsystems, Inc. as

the Java 2 SDK and Java 2 Runtime Environment. All Sun releases of the Java 2 Platform

software are available from the Java 2 Platform software home page

(http://java.sun.com/j2se/).

Each release of the Java 2 SDK, Standard Edition contains:

Java Compiler

Java Virtual Machine*

Java Class Libraries

Java AppletViewer

Java Debugger and other tools

Documentation (in a separate download bundle)

Q : Write simple program to print ―Hello World‖ to the console window!

A :

A. Task 01 - Create Java Project in Eclipse Editor

in this tutorial we will use Eclipse as our Java editor, this task show you how to

run Eclipse and make your first Java Project

i. Run Eclipse from Start Menu

Page 15: Diktat Java Console

9 | P a g e

ii. On the Eclipse Menu, Open File New Project

iii. On Project Window, choose Java Project and click Next

Page 16: Diktat Java Console

10 | P a g e

iv. Enter name of project,click Next and Finish

v. On tree panel on the left side window, expand your Project folder

Page 17: Diktat Java Console

11 | P a g e

vi. Right click on the srcfolder on your Project tree and create New Class

vii. Enter the Name of your Java Class on the field below

Page 18: Diktat Java Console

12 | P a g e

viii. Then press Finish

B. Task 02 – Write your first code to on your new class

publicclass Main {

publicstaticvoid main(String[] args) {

System.out.println("Hello World");

}

}

As we explained above, the Java program consist of two main parts, the Class

Definition and the main() method. The Class Definition is needed in all of Java

Program, and the main() method is required because all Java program is invoked from

this program.

The System.out.println("Hello World");is used to print a text to your

console window, more about this syntax will be covered on the next Chapter.

C. Task 03 – Run your first Java Application

After we write our first Java Code, the next step to make our program run is to

Compile our code so it will be a bytecode that will be running on the JVM.

In Eclipse use [CTRL] + [F11] Key to run your Java Project, and you will see the

Output of your code. Congratulations on making your very first Java Program!

Output :

Page 19: Diktat Java Console

13 | P a g e

Chapter 02

Data Type and I/O

Page 20: Diktat Java Console

14 | P a g e

Constants & Variables

The term variable is used because the data stored in a variable can vary. In other

words, you can change the value of a variable. In Java, you use the assignment operator

= to assign a variable to a particular value. For example, the following statements

declare an integer x and assign it the value 12.

int x;

x = 12;

Note that a variable can assign a value at the time it is declared. The previous

two statements could have been replaced with the following single statement:

int x = 12;

Java is strict about letting you assign variables only to values that match the

variable’s data type. If x is an int, you cannot assign it to other data types unless you

use the cast operator. For example, the following statements declare x as an int and

then attempt to assign x to a floating-point value.

int x;

double d = 3.5;

x = d; //This does not compile!

x = (int)d; //This does compile since I used the cast operator.

The final keyword is used in Java to declare a variable as a constant. Afinal in

Java cannot be changed after it is assigned a value. Consider the following statements,

some of which compile and some of which don’t.

final doublePI = 3.14159;

PI = -5.0; //Does not compile!

finalint x;//A blank final

x = 12; //ok

x = 100 //Does not compile!

The variable PI is declared final and initialized to 3.14159, so attempting to

change it to –5.0 is not valid. The variable x is declared final, but is not initialized. This

can be done in Java, and x is referred to as a blank final. Assigning it to 12 at a later

time is valid, but it cannot be changed after it is assigned. Trying to change it to 100 is

invalid and causes a compile error.

Page 21: Diktat Java Console

15 | P a g e

Data Type

After learning about variable to store our data, we will learn about Data Type,

every variable must have a type which defines what values that variable can hold. The

variable type can be one of three things:

1. Primitive Data Type

2. Name of a Class or Abstract Data Type

3. An Array

In general Data Type is divided in 2, the Primitive Data Type and Abstract

Data Type and we will talk about Array in later chapter.

Page 22: Diktat Java Console

16 | P a g e

Primitive Data Type

In the table above is a list of the primitive data types in Java. The primitive types

are the building blocks for more complicated types. Like its predecessor languages C and

C++ and what we me mentioned above,Java requires all variables to have a type before

they can be used in a program. For this reason,Java is referred to as a strongly typed

language.

In C and C++ programs, programmers frequently had to write separate versions

of programs to support different computer platforms, because the primitive data types

were not guaranteed to be identical from computer to computer. For example, an int

value on one machine might be represented by 16 bits (2 bytes) of memory, while an

int value on another machine might be represented by 32 bits (4 bytes) of memory. In

Java, int values are always 32 bits (4 bytes).

Page 23: Diktat Java Console

17 | P a g e

Each data type in the list above is listed with its size in bits (there are eight bits

to a byte)and its range of values (the data range they can hold). Because the designers

of Java want it to be maximally portable, they chose to use internationally recognized

standards for both character formats (Unicode) and floating-point numbers (IEEE 754).

When instance variables of the primitive data types are declared in a class, they

areautomatically assigned default values unless specified otherwise by the

programmer.Instance variables of types char, byte, short, int, long, float and double

are all given the value 0 by default. Variables of type boolean are given the value false

by default.

Abstract Data Type

What is an abstract data type? Consider the built-in type int. What comes to

mind is the notion of an integer in mathematics, but int on a computer is not precisely

what an integer is in mathematics. In particular, computer int are normally quite limited

in size.

For example, inton a 32-bit machine is limited approximately to the range –2

billion to +2 billion. If the result of a calculation falls outside this range, an error occurs

and the machine responds in some machine-dependent manner, including the possibility

of ―quietly‖producing an incorrect result. Mathematical integers do not have this

problem. So the notion of a computer int is really only an approximation to the notion of

a real-world integer. The same is true with float.

The point is that even the built-in data types provided with programming

languages like Java are really only approximations or models of real-world concepts and

behaviors.

We have taken intfor granted until this point, but now you have a new

perspective to consider. Types like int, float, char and others are all examples of

abstract data types. They are essentially ways of representing real-world notions to

some satisfactory level ofprecision within a computer system.

Java has four integer types: byte, short, int, and long. Use the type that is

most appropriate for your needs. Java has two floating-point types: float and double.

The double type is twice as big as float. So, the double is known as double precision,

float as single precision. The double type is more accurate than the float type.

The float and double types are called floating-point because they are stored in

scientific notation. Number such as 50.534 is stored as 5.0534e+1, its decimal point is

floated to a new position.

Page 24: Diktat Java Console

18 | P a g e

An abstract data type actually captures two notions, namely a data

representation and the operations that are allowed on that data. For example, the notion

of intdefines addition,subtraction, multiplication, division and modulus operations in

Java, but division by zero is undefined.

Another example is the notion of negative integers whose operations and data

representation are clear, but the operation of taking the square root of a negativeinteger

is undefined. In Java, the programmer uses classes to implement abstract data types.

Java has a small set of primitive types. ADTs extend the base programming language.

Assignment Statement and Expression

A statement is the simplest thing you can do in Java; a statement forms a single

Java operation. All the following are simple Java statements:

inti = 1;

importjava.awt.Font;

System.out.println(“This motorcycle is a “+ color + “ “ + make);

m.engineState = true;

Statements sometimes return values—for example, when you add two numbers

together or test to see whether one value is equal to another. Or when you called a

method to round some floating number, the method will return the rounded number,

and that’s what we called as return values.

The most important thing to remember about Java statements is that every

statement ends with a semicolon. Forget the semicolon and your Java program won’t

compile.Java also has compound statements, or blocks, which can be placed wherever a

single statement can. Block statements are surrounded by braces ({}).

Conversion (Type Casting)

The cast operator can be used to cast primitive data types. For example, suppose

that you have a double that you want to store in a float. Even if the double fits easily in

the float, the compiler still requires you to use the cast operator:

double pi = 3.14159;

float a = pi; //Does not compile!

float b = (float) pi; //Works fine

Page 25: Diktat Java Console

19 | P a g e

You might think the compiler should be smart enough to realize that 3.14159 fits

into a float, so no casting is necessary; however, it is important to realize that the

compiler only knows data types. When you assign a 64-bit double to a 32-bit float, the

compiler only sees a larger piece of data being stored in a smaller piece. Because data

could be lost, the cast operator tells the compiler you know what you are doing, and any

loss of data is acceptable.

ASCII

The American Standard Code for Information Interchange (ASCII) is a

character-encoding scheme based on the ordering of the English alphabet. ASCII codes

represent text incomputers, communications equipment, and other devices that use

text. Most modern character-encoding schemes are based on ASCII, though they

support many more characters than did ASCII.

This is an example of ASCII Table :

Page 26: Diktat Java Console

20 | P a g e

Naming Convention

A naming convention is a rule to follow as you decide what to name your

identifiers (e.g. class, package, variable, method, etc).

Why Use Naming Conventions?

Different Java programmers can have different styles and approaches to the way

they program. By using standard Java naming conventions they make their code easier

to read for themselves and for other programmers. Readability of Java code is important

because it means less time is spent trying to figure out what the code does, leaving

more time to fix or modify it.

To illustrate the point it's worth mentioning that most software companies will

have a document that outlines the naming conventions they want their programmers to

follow. A new programmer who becomes familiar with those rules will be able to

understand code written by a programmer who might have left the company many years

before hand.

Standard Java Naming Conventions

The below list outlines the standard Java naming conventions for each type:

Identifier:For naming variables, constants, methods, classes, and packages.

Descriptive identifiers make programs easy to read.

A sequence of characters that consists of letters, digits,

underscores (_), and dollar signs ($).

Must start with a letter, an underscore (_), or a dollar sign

($). It can’t start with a digit.

Can’t be a reserved word (keyword), true, false, or null.

Can be of any length.

Case sensitive, area, Area, and AREA are all different

identifiers.

Suggested to not name identifiers with the $ character

(although possible). The $ character should be used only in

mechanically generated source code.

Classes: Names should be in CamelCase. Try to use nouns because a class

is normally representing something in the real world:

class Customer

class Account

Interfaces: Names should be in CamelCase. They tend to have a name that

describes an operation that a class can do:

interface Comparable

Page 27: Diktat Java Console

21 | P a g e

interface Enumerable

Note that some programmers like to distinguish interfaces by beginning the name with

an "I":

interface IComparable

interface IEnumerable

Methods: Names should be in mixed case. Use verbs to describe what the

method does:

void calculateTax()

String getSurname()

Variables: Used to store values to be used later in a program. Their values

can be changed. Names should be in mixed case. The names should represent

what the value of the variable represents:

StringfirstName

intorderNumber

Only use very short names when the variables are short lived, such as in for

loops:

for(inti=0; i<20;i++)

{

//i only lives in here

}

Constants: Permanent data that nevers changes. Names should be in

uppercase.

static final int DEFAULT_WIDTH

static final int MAX_HEIGHT

Imports

The imports directive tells the compiler where to look for the class definitions

when it comes upon a class that it cannot find in the default java.lang package. So, for

example,the import statements:

import mypack.*;

import mypack.extrapack.*;

import java.applet.*;

indicate that classes can be found in the mypack and mypack.extrapackpackages and

also that the Applet class can be found in the java.applet package.

Asteriks (*) in import mypack.*referstoalltypesthatexistin thepackagebutdoes

notincludea packagethat is inthepackage.

If you want include only one class in the package, you can also type import

mypack.MyClassstatement.

Page 28: Diktat Java Console

22 | P a g e

Output

To print a text on Console Window in Java, you can use

System.out.printf(),System.out.print() or System.out.println() method.

println() is used to print a String and then add anewline at the end of the

sentences. Example:

The output will be:

print() is used to print a Stringwithout adding anewline at the end of the

sentences. Example:

The output will be:

In Java if you wantto print a String using user defined format,you can use

printf() or format().printf() or format() allows the programmer to specify

textual representations of data using two parameters:

a format String, or "template" and

anargument list, or a vector of data to be formatted according to the

template.

Page 29: Diktat Java Console

23 | P a g e

The general syntax of a format specifier is:

%[flags][width][.precision][argsize]typechar

Flags

Flags are single characters that indicate exceptions to the conversion type's

default behavior. A format-specifier may have multiple flags, but some flags are

mutually exclusive. Multiple flags can appear in any order. The following table lists the

formatting flags supported by Java's printf classes:

Page 30: Diktat Java Console

24 | P a g e

flag Meaning conversion types

applicable

'-' Result is left-aligned in the field. This flag is meaningless if no mandatory field width is specified.

%d, %u, %o, %x, %X, %z[n],

%Z[n], %f, %e, %E, %g, %G, %s,

%c, %p '^' Result is centered in the field. This flag is meaningless if no mandatory field width is specified.

'+' Non-negative values begin with a plus character ('+').

%d, %f

' ' Non-negative values begin with a space character (' '). This flag is only useful for signed conversion results (%d and %f).

'#'

Argument is represented in an "alternate form." This depends on the conversion type:

%o Non-negative octal values are prepended with a zero ('0').

%x, %X

Hexadecimal values are prepended with the prefix "0x" or "0X".

%e,

%E, %f

The integer portion of the result always ends with a decimal point ('.'), even if the fractional portion is zero.

%g, %G

The fractional portion always appears, even if it is zero.

%c If the character is special or unprintable, it is output in an escaped form. The output can be surrounded by single quotes to form a syntactically valid Java character literal.

There is no alternate form for %s, %d, %u, %z[n], and %Z[n]

Precision specifier

An optional "precision-specifier" may be included in a format-specifier to indicate

the precision with which to convert the data. The meaning of the word "precision"

depends on the type of conversion being performed:

conversion type meaning of "precision"

default value

(if omitted)

%d, %o, %u, %x, %X,

%z[n], %Z[n]

(integer conversions)

minimum number of digits. The converted value will be prepended with zeros if necessary. Note that if the precision is 0 and the value is zero, nothing will be printed, or the entire field will be nothing but padding.

1

%f, %e, %E, %g, %G

(real conversions)

number of fractional digits after the decimal point. The converted value will be rounded if necessary.

6

%s (strings) the maximum number of characters. If the string is too long, it will be truncated.

infinity

Page 31: Diktat Java Console

25 | P a g e

If no precision is specified, the default precision will be used. Precision cannot be

specified for conversion types other than those listed above.

Width specifier

An optional "width specifier," if present, indicates the field with, or the minimum

number of characters in the output that the formatted argument will span. If the string

representation of the value does not fill the minimum length, the field will be left-padded

with spaces. If the converted value exceeds the minimum length, however, the

converted result will not be truncated.

Example: If the format specifier is "%6d", and the supplied int argument is 52, then the output will be " 52" (four spaces on the left).

If no width is specified, then there is no minimum size for the converted result.

The field will be only as large as necessary to display the result.

Conversion type character

Typechar is a single character identifying the conversion type. The supported

conversion types are listed below, along with their meanings, and the corresponding

arguments expected in the argument vector:

type character input String result

%d signed

int signed decimal integer

%u unsigned int

unsigned decimal integer

%o unsigned int

unsigned octal integer

%x, %X unsigned

int

unsigned hexadecimal integer, lowercase or

uppercase

%z[n], %Z[n] unsigned

int

unsigned integer base n, with n coded in

decimal; include square brackets

%f float real number, standard notation

%e, %E float real number, scientific notation (lowercase or

uppercase exponent marker)

Page 32: Diktat Java Console

26 | P a g e

%g, %G float

same format as %f or %e, depending on the

value. Scientific notation is used only if the

exponent is greater than the precision or less

than -4.

%s String String

%c char character

%p Object object identity hash code (i.e., pointer value), in

unsigned hexadecimal

additional format specifiers that do not result in argument

conversions

%\n (none) platform-independent line separator

%n (null) counts characters

Example: long n = 461012;

System.out.format("%d%n", n); // --> "461012"

System.out.format("%08d%n", n); // --> "00461012"

System.out.format("%+8d%n", n); // --> " +461012"

System.out.format("%,8d%n", n); // --> " 461,012"

System.out.format("%+,8d%n%n", n); // --> "+461,012"

double pi = Math.PI;

System.out.format("%f%n", pi); // --> "3.141593"

System.out.format("%.3f%n", pi); // --> "3.142"

System.out.format("%10.3f%n", pi); // --> " 3.142"

System.out.format("%-10.3f%n", pi); // --> "3.142"

Escape Sequences

A character preceded by a backslash (\) is an escape sequence and has special

meaning to the compiler. The following table shows the Java escape sequences:

Escape Sequences

Escape

Sequence Description

\t Insert a tab in the text at this point.

\b Insert a backspace in the text at this point.

\n Insert a newline in the text at this point.

\r Insert a carriage return in the text at this point.

Page 33: Diktat Java Console

27 | P a g e

\f Insert a formfeed in the text at this point.

\' Insert a single quote character in the text at this point.

\" Insert a double quote character in the text at this point.

\\ Insert a backslash character in the text at this point.

When an escape sequence is encountered in a print statement, the compiler

interprets it accordingly. For example, if you want to put quotes within quotes you must

use the escape sequence, \", on the interior quotes. To print the sentence:

She said "Hello!" to me.

you would write:

System.out.println("She said \"Hello!\" to me.");

Input

To get user input, use the BufferedReader and InputStreamReader

The InputStreamReader class reads the user's input.

The BufferedReader class buffers the user's input to make it work more efficiently.

Page 34: Diktat Java Console

28 | P a g e

Page 35: Diktat Java Console

29 | P a g e

You can also use Scanner class to receive input, look at the example below:

If you want to receive input with data type int you cannot use

reader.nextLine(),

you must use reader.nextInt().Method that you can use:

nextInt()scans the next token of the input as an int.

nextFloat()scans the next token of the input as a float.

nextDouble()scans the next token of the input as a double.

nextByte()scans the next token of the input as a byte.

nextLong()scans the next token of the input as a long.

nextShort() scans the next token of the input as a short.

How did you write a program? Did you immediately begin to write the code? No.

It’s important to think before you type. Thinking enables you to generate a logical

solution for the problem without concern about how to write the code. Once you have a

Page 36: Diktat Java Console

30 | P a g e

logical solution, type the code to translate the solution into a Java program. The

translation is not unique.

4. Exercise

Please make a simple program to learn some data type in Java.

1. Asking for input using Scanner class that imported from java.util.Scanner

Data type that will be inputed:

o int

o double

o String

o boolean

o char (obtained from the type casting of int that user input)

2. Show results from each input of the above in accordance with the example below.

Print Screen of the Program when Ask User to Input Data

Page 37: Diktat Java Console

31 | P a g e

Print Screen of the Program when Show Result

a. Task 01 - Create Project Java in Eclipse

i. Run Eclipse from Start Menu

ii. Open Menu File -> New -> Project

iii. On Project Window, choose Java Project and click next

iv. Enter name of project,click next and finish

v. On tree panel on the left side window, expand Project folder

vi.Right click on src and create new class

vii. Enter the name class

viii. Then Press Finish

b. Task 02 – Using import and Declare Variable with Data Type

- Type import java.util.Scanner for input data

- Declare variable to save value and object from Scanner for receive input

Page 38: Diktat Java Console

32 | P a g e

c. Task 03 – Receive input for any kind of data type

Page 39: Diktat Java Console

33 | P a g e

d. Task 04 – Print variable using print format (Read “Formatted Output” in this

Chapter)

Page 40: Diktat Java Console

34 | P a g e

Chapter 03

Arithmetic Operation

Page 41: Diktat Java Console

35 | P a g e

Numerical Operators and Arithmetic Expression

Arithmetic expressions in Java must be written in straight-line form to facilitate

entering programs into the computer. Thus, expressions such as ―a divided by b‖ must

be written as a / b, so that all constants, variables and operators appear in a straight

line.

Parentheses are used in Java expressions in the same manner as in algebraic

expressions.

For example, to multiply a times the quantity b + c, we write

a * ( b + c )

Java applies the operators in arithmetic expressions in a precise sequence

determined by the following rules of operator precedence, which are generally the same

as those followed in algebra:

1. Operators in expressions contained within pairs of parentheses are evaluated

first. Thus, parentheses may be used to force the order of evaluation to occur in

any sequence desired by the programmer. Parentheses are at the highest level of

precedence.In cases of nested or embedded parentheses, the operators in the

inner mostpair of parentheses are applied first.

2. Multiplication, division and modulus operations are applied next. If an expression

contains several multiplication, division or modulus operations, the operators are

applied from left to right. Multiplication, division and modulus operators have the

same level of precedence.

3. Addition and subtraction operations are applied last. If an expression contains

several addition and subtraction operations, the operators are applied from left to

right. Addition and subtraction operators have the same level of precedence.

Page 42: Diktat Java Console

36 | P a g e

The rules of operator precedence enable Java to apply operators in the correct

order. When we say that operators are applied from left to right, we are referring to the

associativity of the operators. We will see that some operators associate from right to

left. The table below will summarizesthese rules of operator precedence. This table will

be expanded as additional Java operators are introduced.

Shorthand Operator

Shorthand assignment operator provides two advantages

1. needs less typing

2. java compiler handles in an efficient way

Page 43: Diktat Java Console

37 | P a g e

This is the summary of shorthand operator

Operation Operator Example Expansion

Assignment = a = 5 a = 5

Addition += a += 5 a = a + 5

Subtraction -= a -= 5 a = a - 5

Multiplication *= a *= 5 a = a * 5

Division /= a /= 5 a = a / 5

Modulus %= a %= 5 a = a % 5

Bitwise |= a |= 5 a = a | 5

inclusive OR

Bitwise ^= a ^= 5 a = a ^ 5

exclusive OR (XOR)

Bitwise <<= a <<= 5 a = a << 5

left-shift

Bitwise >>= a >>= 5 a = a >> 5

right-shift

Page 44: Diktat Java Console

38 | P a g e

Increment and Decrement Operator

Java provides the unary increment operator, ++, and the unary decrement

operator, --.A program can increment the value of a variable called c by 1 using the

increment operator, ++, rather than the expression c = c + 1 or c += 1. If an

increment or decrement operator is placed before a variable, it is referred to as the pre-

increment or pre-decrement operator, respectively. If an increment or decrement

operator is placed after a variable, it is referred to as the post-increment or post-

decrement operator, respectively.

Pre-incrementing (pre-decrementing) a variable causes the variable to be

incremented (decremented) by 1, and then the new value of the variable is used in the

expression in which it appears. Post-incrementing (post-decrementing) the variable

causes the current value of the variable to be used in the expression in which it appears,

and then the variable value is incremented (decremented) by 1.

The example code below will demonstrates the difference between the pre-

incrementing version and the post-incrementing version of the ++increment operator.

Post-incrementing the variable c causes it to be incremented after it is used in the

System.out.println method call (line 13). Pre-incrementing the variable c causes it to

be incremented before it is used in the System.out.println method call (line 20).

The program displays the value of c before and after the ++operator is used. The

decrement operator (--) works similarly.

Page 45: Diktat Java Console

39 | P a g e

4. Exercise

Please make a simple arithmetic calculation program with the following

conditions:

1. Input 2 number using class Scanner.

2. Doing some arithmetic operations with steps below :

Doing increasing operation, first number + second number.

Doing decreasing operation, first number – second number and second

number – first number.

Doing multiplication operation, first number * second number.

Doing division operation, first number / second number and second number

/ first number.

Doing modulus operation, first number % secondnumber and second

number % first number.

Print Screen of the Program when Ask to Input Number

Page 46: Diktat Java Console

40 | P a g e

Print Screen of the program when show result of arithmetic operations

a. Task 01 - Create Project Java in Eclipse

i. Run Eclipse from Start Menu

ii. Open Menu File -> New -> Project

iii. On Project Window, choose Java Project and click next

iv. Enter name of project,click next and finish

v. On tree panel on the left side window, expand Project folder

vi.Right click on src and create new class

vii. Enter the name class

viii. Then Press Finish

b. Task 02 - Doing some arithmetic operations

- Type import java.util.Scanner for input data

- Declare variable to save value and object from Scanner for receive input.

Create object from class Scanner to retrive input from user called 'in'. we will use

some method from class Scanner to get the input from user.

Page 47: Diktat Java Console

41 | P a g e

- Make some arithmetic operations

+ in here is used for connectingtext(String)withvariable

This is for addition operation

This is for Substraction operation

This is for Multiplication operation

This is for Division operation

Page 48: Diktat Java Console

42 | P a g e

Chapter 04

Selection Statement

Page 49: Diktat Java Console

43 | P a g e

Selection Control Structures and Logical Operator

A selection structure is used to choose among alternative courses of action in a

program.For example, suppose that the passing grade on an examination is 60 (out of

100). Then thepseudocode statement

If student’s grade is greater than or equal to 60.Print “Passed”

determines if the condition ―student’s grade is greater than or equal to 60‖ is true or

false.

If the condition is true, then ―Passed‖ is printed, and the next pseudocode

statement in orderis performed (remember that pseudocode is not a real programming

language.)

If thecondition is false, the Print statement is ignored, and the next pseudocode

statement in orderis performed.

Note that the second line of this selection structure is indented. Such indentation

is optional, but it is highly recommended, because it emphasizes the inherent structure

of structured programs. The Java compiler ignores white-space characters, like

blanks,tabs and newlines, used for indentation and vertical spacing. Programmers insert

these white-space characters to enhance program clarity.

The preceding pseudocodeif statement may be written in Java as

if( studentGrade>= 60 ) System.out.println( "Passed" );

Notice that the Java code corresponds closely to the pseudocode. This attribute is

aproperty of pseudocode that makes it a useful program development tool. The

statement inthe body of theifstructure outputs the character String"Passed" in the

commandwindow.

The flowchart below will illustrates the single-selection if structure. This

flowchartcontains what is perhaps the most important flowcharting symbol—the diamond

symbol,also called the decision symbol, which indicates that a decision is to be made.

The decisionsymbol contains an expression, such as a condition, that can be either true

or false.

Page 50: Diktat Java Console

44 | P a g e

Thedecision symbol has two flowlines emerging from it. One indicates the

direction to be takenwhen the expression in the symbol is true; the other indicates the

direction to be taken whenthe expression is false. A decision can be made on any

expression that evaluates to a valueof Java’s booleantype (i.e., any expression that

evaluates to true or false).

Note that the ifstructure is a single-entry/single-exit structure. We will soon

learnthat the flowcharts for the remaining control structures also contain (besides small

circlesymbols and flowlines) only rectangle symbols, to indicate the actions to be

performed, anddiamond symbols, to indicate decisions to be made. This factor is

indicative of the action/decision model of programming we have been emphasizing

throughout this chapter.

We can envision seven bins, each containing only control structures of one of the

seventypes. These control structures are empty; nothing is written in the rectangles or

in the diamonds.

The programmer’s task, then, is to assemble a program from as many of each

typeof control structure as the algorithm demands, combining the control structures in

only twopossible ways (stacking or nesting) and then filling in the actions and decisions

in a mannerappropriate for the algorithm. In this chapter we discuss the variety of ways

in whichactions and decisions may be written.

If-Else Statement

The ifselection structure performs an indicated action only when the given

conditionevaluates to true; otherwise, the action is skipped. The if/else selection

structure allowsthe programmer to specify that a different action is to be performed

Page 51: Diktat Java Console

45 | P a g e

when the conditionis true rather than when the condition is false. For example, the

pseudocode statement

If student’s grade is greater than or equal to 60

Print “Passed”

else

Print “Failed”

printsPassedif the student’s grade is greater than or equal to 60 and prints Failedif

thestudent’s grade is less than 60. In either case, after printing occurs, the next

pseudocodestatement in sequence is performed. Note that the body of the elseis also

indented.

The indentation convention you choose should be carefully applied throughout

yourprograms. It is difficult to read programs that do not use uniform spacing

conventions.The preceding pseudocodeif/elsestructure may be written in Java as

if( studentGrade>= 60 )

System.out.println("Passed" );

else

System.out.println("Failed" );

Below is the flowchart to illustrates the flow of control in an if/else

structure.Once again, note that, besides small circles and arrows, the only symbols in

the flowchartare rectangles (for actions) and a diamond (for a decision). We continue to

emphasize thisaction/decision model of computing.

Imagine again a deep bin containing as many emptydouble-selection structures

as might be needed to build a Java algorithm. The programmer’sjob is to assemble the

selection structures (by stacking and nesting) with othercontrol structures required by

the algorithm and to fill in the empty rectangles and emptydiamonds with actions and

decisions appropriate to the algorithm being implemented.

Page 52: Diktat Java Console

46 | P a g e

Switch statement

Only be used for data type byte, short, char, dan int and enum. Example :

switch (test)

{

casevalueOne:

resultOne;

break;

casevalueTwo:

resultTwo;

break;

casevalueThree:

resultThree;

break;

default: defaultresult;

}

In the switch statement, the test (a primitive type of byte, char, short, or int)

is compared with each of the case values in turn. If a match is found, the statement, or

statements after the test is executed. If no match is found, the default statement is

executed. The default is optional, so if there isn’t a match in any of the cases and default

doesn’t exist, the switch statement completes without doing anything.

Page 53: Diktat Java Console

47 | P a g e

Note that the significant limitation of the switch in Java is that the tests and

values can be only simple primitive types (and then only primitive types that are

castable to int).

You cannot use larger primitive types (long, float) or objects within a switch,

nor can you test for any relationship other than equality. This limits the usefulness of

switch to all but the simplest cases; nested ifs can work for any kind of test on any type.

Here’s a simple example of a switch statement similar to the nested if shown earlier:

switch (oper)

{

case „+‟:

addargs(arg1,arg2);

break;

case „*‟:

subargs(arg1,arg2);

break;

case „-‟:

multargs(arg1,arg2);

break;

case „/‟:

divargs(arg1,arg2);

break;

}

Note the break statement included in every line. Without the explicit break,

once a match is made, the statements for that match and also all the statements further

down in the switch are executed until a break or the end of the switch is found (and

then execution continues after the end of the switch).

In some cases, this may be exactly what you want to do, but in most cases,

you’ll want to make sure to include the break so that only the statements you want to

be executed are executed.

One handy use of falling through occurs when you want multiple values to

execute the same statements. In this instance, you can use multiple case lines with no

result, and the switch willexecute the first statements it finds. For example, in the

following switch statement, the String ―x is an even number.‖ is printed if x has

values of 2, 4, 6, or 8. All other values of x print the String ―x is an odd number.‖

Page 54: Diktat Java Console

48 | P a g e

switch (x)

{

case 2:

case 4:

case 6:

case 8:

System.out.println(“x is an even number.”);

break;

default: System.out.println(“x is an odd number.”);

}

Ternary Statement

Java has one ternary operator - Conditional Operator ?:

Generally it looks like this: condition ?op1 : op2. If condition is false, the

Statement evaluates as op2; otherwise (true), it evaluates as op1.Conditional operator

?can be grouped right-to-left.

The expression op1?op2:op3?op4:op5?op6 :op7 can be rewritten for easier

understanding like this: op1?op2:(op3?op4:(op5?op6:op7))

The conditional operator ?was introduced in many programming languages as a

shorthand replacement for the if-then-else conditional statement.

Another Example:

if (a > b) {

result = x;

}

else {

result = y;

}

This can be rewritten as the following ternary statement:

result= a > b ?x : y;

Nested Selection Statement

The if constructed in java can be nested. In other words, an if construct can be

present inside the body of another if construct.

Nested if/else structures test for multiple cases by placing if/else structures

inside if/else structures. For example, the following pseudocode statement prints A for

exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for

Page 55: Diktat Java Console

49 | P a g e

grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other

grades:

If student’s grade is greater than or equal to 90

Print “A”

else

If student’s grade is greater than or equal to 80

Print “B”

else

If student’s grade is greater than or equal to 70

Print “C”

else

If student’s grade is greater than or equal to 60

Print “D”

else

Print “F”

This pseudocode may be written in Java as

if( studentGrade>= 90 )

System.out.println("A" );

else

if( studentGrade>= 80 )

System.out.println("B" );

else

if( studentGrade>= 70 )

System.out.println("C" );

else

if( studentGrade>= 60 )

System.out.println("D" );

else

System.out.println("F" );

If studentGradeis greater than or equal to 90, the first four conditions will be

true, butonly the System.out.printlnstatement after the first test will be executed.

After thatparticular System.out.printlnis executed, the else part of the ―outer‖

if/elsestatement is skipped.

1. Exercise

Please make a program to find the grade of the student with the following conditions:

1. Input using class Scanner from java.util.Scanner.

2. The program begins by asking for five inputs below :

Page 56: Diktat Java Console

50 | P a g e

First input is student’s name in the form of String.

Second input is gender in the form of boolean, where is true = male and false =

female.

Third input is Mid Exam score with range between 0 until 100 in the form of

int.

Fourth input is Final Exam score with range between 0 until 100 in the form of

int.

Fifth input is Independent Task score with range between 0 until 100 in the

form of int.

3. Final score calculating with percentage 30 % Mid Exam, 50% Final Exam

and20% Independent Task.

4. Grade calculating is obtained from final score with the following conditions:

Grade A : final score >= 85

Grade B : 75<= final score <85

Grade C : 65<= final score <75

Grade D : 55<= final score <65

Grade E : final score <55

5. Provide message for each grade with the following provisions:

Grade A : ―Very good, Keep your grade‖

Grade B : ―Pretty good, Increase again‖

Grade C : ―Quite less,need to learn more‖

Grade D : ―Your score is not satisfy‖

Grade E : ―Learn more diligent and active‖

6. Each comment ends with Mr. for male gender, and Mrs. for female gender, plus the

name of student.

Print Screen of the Program Ask User to input Five Inputs

Print Screen of the Program after Calculating Score Result

Page 57: Diktat Java Console

51 | P a g e

v. On tree panel on the left side window, expand Project folder

c. Task 03 – Calculate Final score from 30 % Mid Exam, 50% Final Exam and 20%

Independent Task.

d. Task 04 - Grade calculating is obtained from final score

Grade A : final score >= 85

Grade B : 75<= final score <85

Grade C : 65<= final score <75

Grade D : 55<= final score <65

Page 58: Diktat Java Console

52 | P a g e

Grade E : final score <55

f. Task 06 - Print comment ends with Mr. for male gender, and Mrs. for female gender,

plus the name of student.

First I determine the comment ends with Mr or Mrs

In this selection , I use ternary operation

And then print comment ends Mr or Mrs, plus name of student

Page 59: Diktat Java Console

53 | P a g e

Chapter 05

Iteration Statement, Jump Operator

Page 60: Diktat Java Console

54 | P a g e

Repetition with While

If you can write programs using loops, you know how to program! A repetition

structure allows the programmer to specify that an action is to be repeated while some

condition remains true.

Structure for while

while( condition )

{

Statement

}

The pseudocodestatement :

While there are more items on my shopping list

Purchase next item and cross it off my list

describes the repetition that occurs during a shopping trip. The condition ―there are

moreitems on my shopping list‖ may be true or false. If it is true, then the action

―Purchase nextitem and cross it off my list‖ is performed.

This action will be performed repeatedly while the condition remains true. The

statement(s) contained in the whilerepetition structure constitute the body of the

whilestructure. The body of the whilestructure may be a single statement or a block.

Eventually, the condition will become false (when the last item on the shopping list has

been purchased and crossed off the list). At this point, the repetition terminates, and the

first pseudocode statement after the repetition structure is executed.

As an example of a whilestructure, consider a program segment designed to find

the first power of 2 larger than 1000. Suppose that the intvariable product has been

initialized to 2. When the following while structure finishes executing, product

containsthe result:

intproduct = 2;

while( product <= 1000 )

product = 2 * product;

The flowchart below will illustrates the flow of control of the preceding while

repetition structure. Once again, note that, besides small circles and arrows, the

flowchart contains only a rectangle symbol and a diamond symbol.

Page 61: Diktat Java Console

55 | P a g e

Imagine, again, a deep bin of empty while structures that may be stacked and

nested with other control structures to form a structured implementation of an

algorithm’s flow of control. The empty rectangles and diamonds are then filled in with

appropriate actions and decisions.

The flowchart clearly shows the repetition. The flowline emerging from the

rectangle wraps back to the decision, which is tested each time through the loop until

the decision eventually becomes false. At this point, the while structure is exited, and

control passes to the next statement in the program.

When the while structure is entered, product is 2. Variable product is

repeatedly multiplied by 2, taking on the values 4, 8, 16, 32, 64, 128, 256, 512 and

1024 successively.

When product becomes 1024, the condition product <= 1000 in the

whilestructure becomes false. This result terminates the repetition, with 1024 as

product’s final value. Execution continues with the next statement after the while.

[Note: If a while structure’s condition is initially false, the body statement(s) will never

be performed]

Repetition with Do-While

The do/while repetition structure is similar to the while structure. In the while

structure,the program tests the loop-continuation condition at the beginning of the loop,

before performing the body of the loop. The do/while structure tests the loop-

continuation condition after performing the body of the loop; therefore, the loop body

always executes atleast once.

Page 62: Diktat Java Console

56 | P a g e

When a do/while structure terminates, execution continues with the statement

after the while clause. Note that it is not necessary to use braces in the do/while

structure if there is only one statement in the body. However, most programmers

include the braces, to avoid confusion between the while and do/while structures. For

example,

while( condition )

normally is the first line of a whilestructure. A do/while structure with no braces

around a single-statement body appears as

do

statement

while( condition );

which can be confusing. Reader may misinterpret the last linewhile(condition );as a

while structure containing an empty statement (the semicolon by itself). Thus, toavoid

confusion, the do/while structure with one statement often is written as follows:

do{

statement

} while ( condition);

This is the flowchart for do/while repetition structure.

Page 63: Diktat Java Console

57 | P a g e

Repetition with For

The forrepetition structure handles all of the details of counter-controlled

repetition. The forstructure’s first line (including the keyword for and everything in

parentheses after for) is sometimes called the for structure header. Notice that the

forstructure ―does it all‖: It specifies each of the items needed for counter-controlled

repetition with a control variable. If there is more than one statement in the body of the

forstructures, braces ({}) are required to define the body of the loop. Look at the

picture below:

The general format of the for structure is

for( expression1; expression2; expression3 )

statement

whereexpression1names the loop’s control variable and provides its initial

value,expression2is the loop-continuation condition (containing the control variable’s

final value) and expression3modifies the value of the control variable, so that the loop

continuation condition eventually becomes false.

Make sure that the loop-continuation-condition eventually becomes false so that

the program will terminate. A common programming error involves infinite loops

because of mistake in the loop-continuation-condition. Programmers often make

mistakes to execute a loop one more or less time (known as the off-by-one error). For

example, using count <= 100 is different with count < 100.

Page 64: Diktat Java Console

58 | P a g e

Break Operation

The breakstatements alter the flow of control. The break statement,when

executed in a while, for, do/while or switch structure, causes immediate exit from

that structure. Execution continues with the first statement after the structure. Example:

for(int i = 0; i < 13; i ++){

System.out.println(i);

if(i == 7) break;

}

System.out.println("finish");

In the example if i has reached value 7 loop is automatically stop.And then the output is

0

1

2

3

4

5

6

7

Continue Operation

The continue statement proceeds with the next iteration (repetition) of the

immediately enclosing while, for or do/while structure. The labeled

continuestatement, when executed in a repetition structure (while, for or do/while),

skips the remaining statements in that structure’s body and any number of enclosing

repetition structures and proceeds with the next iteration of the enclosing labeled

repetition structure. Example:

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

if(i == 7) continue;

System.out.println(i);

}

System.out.println("finish");

In the example if i has reached value 7 the loop will skip the statement and continue the

loop

Page 65: Diktat Java Console

59 | P a g e

The output is

0

1

2

3

4

5

6

8

9

10

Label Operation

We can also add alabel keywordbeforewhile, do-while orfor statement block and

put the label that we make before after continue or break statement, this method is

calledbreak with label. Usually label is used to break a loop and start from specific point.

Example:

loop1: //label

for(int i = 0; i < 10; i++){// 1st loop

for(int j = 0; j < 10; j++){// 2nd loop

//go out from 1st loop

if(map[i][j] == 1) break loop1;

}

}

System.out.println("finish");

Some programming languages have a goto statement. The goto statement

indiscriminately transfer control to any statement in the program and executes it. This

makes your program vulnerable to errors. The break and continue statements in Java

are different from goto statements. They operate only in a loop or a switch statement.

The break statement breaks out of the loop, and the continue statement breaks out of

the current iteration in the loop.

1. Exercise

Please make a program to print Odd and Even Number:

1. The program begins by asking user to input how many number they want to print

2. Print Odd and Even Number according to how many number that user input

Page 66: Diktat Java Console

60 | P a g e

Print Screen of the Program Ask User to input count of number

Print Screen of the Program print all result

a. Task 01 - Create Project Java in Eclipse

v. On tree panel on the left side window, expand Project folder

c. Task 03 - Print Odd and Even Number according to count of number that user input

Page 67: Diktat Java Console

61 | P a g e

Initialization: It allows the variable to be initialize

Termination (or condition): It allows to check the certain condition,the condition

according to user input

Increment: It allows the how much increase the given variable.

Page 68: Diktat Java Console

62 | P a g e

Chapter 06

Exception Handling

Page 69: Diktat Java Console

63 | P a g e

Exception Handling Definition

Exception handling is provided to enable programs to catch and handle errors

rather than letting them occur and suffering the consequences. Exception handling is

designed for dealing with synchronous errors such as an attempt to divide by zero (that

occurs as the program executes the divide instruction). Exception handling is not

designed to deal with asynchronous events such as disk I/O completions, network

message arrivals, mouse clicks, keystrokes and the like; these are best handled through

other means, such as Java event listeners.

Java exception handling enables a program to catch all exceptions, all exceptions

of a certain type or all exceptions of related types. This flexibility makes programs more

robust by reducing the likelihood that programs will not process problems during

program execution.

Exception handling is used in situations in which the system can recover from the

malfunction that caused the exception. The recovery procedure is called an exception

handler. The exception handler can be defined in the method that may cause an

exception or in a calling method.

Exception handling should be used:

to process exceptional situations where a method is unable to complete its task for

reasons it cannot control

to process exceptions from program components that are not geared to handling

those exceptions directly, or

on large projects to handle exceptions in a uniform manner project wide.

Try and Catch

An exception that occurs in a try block normally is caught by an exception

handler specified by a catch block immediately following that try block as in

try{

statements that may throw an exception

}

catch(ExceptionTypeexceptionReference) {

statements to process an exception

}

Page 70: Diktat Java Console

64 | P a g e

A try block can be followed by zero or more catch blocks. If a try block executes

and no exceptions are thrown, all the exception handlers are skipped and control

resumes with the first statement after the last exception handler.

When an exception is thrown, control exits the current try block and proceeds to

an appropriate catch handler (if one exists) after that try block. It is possible that the

throw point could be in a deeply nested scope within a try block; control will still

proceed to the catch handler. It is also possible that the throw point could be in a

deeply nested method call; still, control will proceed to the catch handler.

A try block may appear to contain no error checking and include no throw

statements,but methods called from the try block may throw exceptions. Also,

statements in a try block that do not invoke methods may cause exceptions. For

example, a statement that performs array subscripting on an array object throws an

ArrayIndexOutOfBoundsExceptionif the statement specifies an invalid array

subscript. Any method call can invoke code that might throw an exception or call

another method that throws an exception.

Finally

The finally block is optional. If it is present, it is placed after the last of a try

block’scatch blocks, as follows:

try{

statements

resource-acquisition statements

}

catch( AKindOfException exception1 ) {

exception-handling statements

}

catch( AnotherKindOfException exception2 ) {

exception-handling statements

}

finally{

statements

resource-release statements

}

Java guarantees that a finally block (if one is present) will execute regardless of

whether any exception is thrown in the corresponding try block or any of its

corresponding catch blocks. Java also guarantees that a finally block (if one is present)

Page 71: Diktat Java Console

65 | P a g e

will execute if a try block exits via a return, break or continue statement. If no

exception arises in the try block, finally block is also executed.

Resource-release code is placed in a finally block. Suppose a resource is

allocated in a try block. If no exception occurs, the catch handlers are skipped and

control proceeds to the finally block, which frees the resource. Control then proceeds to

the first statement after the finally block.

If an exception occurs, the program skips the rest of the try block. If the

program catches the exception in one of the catch handlers, the program processes the

exception. Then the finally block releases the resource, and control then proceeds to

the first statement after the finally block.

If an exception that occurs in the try block cannot be caught by one of the catch

handlers, the program skips the rest of the try block and control proceeds to the finally

block, which releases the resource. Then the program passes the exception up the call

chainuntil some calling method chooses to catch it. If no method chooses to deal with it,

a non-GUI-based application terminates.

If a catch handler throws an exception, the finally block still executes. Then the

exception is passed up the call chain for a calling method to catch and handle. The

catch block may be omitted when thefinally clause is used.

Throw Statement

It is possible that the catch handler that catches an exception may decide it

cannot process the exception, or it may want to let some other catch handler handle

the exception. In this case, the handler that received the exception can rethrow the

exception with the statement:

throwexceptionReference;

whereexceptionReferenceis the parameter name for the exception in the catch handler.

Such a throw rethrows the exception to the next enclosing try block.

Even if a handler can process an exception, and regardless of whether it does any

processing on that exception, the handler still can rethrow the exception for further

processing outside the handler. A rethrown exception is detected by the next enclosing

try block and is handled by an exception handler listed after that enclosing try block.

Page 72: Diktat Java Console

66 | P a g e

A throws clause lists the exceptions that can be thrown by a method as in

intfunctionName( parameterList)

throwsExceptionType1, ExceptionType2, ExceptionType3, …

{

// method body

}

The types of exceptions that are thrown by a method are specified in the method

definition with a comma-separated list in the throws clause. A method can throw

objects of the indicated classes, or it can throw objects of their subclasses.

Some exceptions can occur at any point during the execution of the program.

Many of these exceptions can be avoided by coding properly. These are run-time

exceptions, and they derive from class RuntimeException. For example, if your

program attempts to access an out-of-range array subscript, an exception of type

ArrayIndexOutOf-BoundsException(derived from RuntimeException) occurs. Your

program clearly can avoid such a problem; hence, it is a run-time exception.

Another run-time exception occurs when your program creates an object

reference, but has not yet created an object and assigned it to the reference. Attempting

to use such a null reference causes a NullPointerExceptionto be thrown. Clearly, your

program can avoid this circumstance; hence, it is a run-time exception. Another run-

time exception is an invalid cast, which throws a ClassCastException.

Writing Own Exception Handler

In Java programming language we can write own exception handler. Sometimes

weneed our own exception handler to handle some type exception. To make own

exception handler we need inherit some class Exception.

This is example to writing own Exception Handler

// make NegativeNumberException

classNegativeNumberException extends Exception {

// No Code here

}

classDemoCreateException{

public static void main(String[] args){

//Example for using NegativeNumberException

try{

Page 73: Diktat Java Console

67 | P a g e

// We throw negative number exception

throw new NegativeNumberException();

}catch(NegativeNumberExceptionnne){

System.out.println(“Error in Negative Number”);

}

}

}

This is simple own exception handler. In the example above we not define any

code in the class handler. We can add constructor and method to describe exception that

we handle too.

More on Exception Handling

The class names Error, Exception, and RuntimeException are somewhat

confusing. All three of these classes are exception, and all of the errors discussed here

occur at runtime. The exception classes can be classified into three major types: system

errors, exceptions, and runtime exceptions.

System errors are thrown by the JVM and represented in the Error class. The

Error class describes internal system errors. Such errors rarely occur. If one does,

there is little you can do beyond notifying the user and trying to terminate the

program gracefully. Example,LinkageError: a class has some dependency on

another class, but the latter class has changed incompability after the compilation of

the former class; and VirtualMachineError: the JVM is broken or has run out of the

resources it needs in order to continue operating.

Exceptions are represented in the Exception class, which describes errors caused

by your program and by external circumstances. These errors can be caught and

handled by your program. Example, ClassNotFoundException: attempt to use a

class that doesn’t exist; and IOException: related to input/output operations, such

as invalid input, reading past the end of a file, and opening a nonexistent file.

Runtime exceptionsare represented in the RuntimeException class, which

describes programming error, such as bad casting, accessing and out-of-bounds

array, and numeric errors. Runtime exceptions are generally thrown by the JVM.

Example, ArithmeticException: dividing an integer by zero;

NullPointerException: attempt to access an object thorugh a null reference

variable; IndexOutOfBoundsException: index to an array is out of range; and

IllegalArgumentException: a method is passed an argument that is illegal or

inappropriate.

Page 74: Diktat Java Console

68 | P a g e

RuntimeException, Error, and their subclasses are know as unchecked

exceptions. All other exceptions are known as checked exceptions, meaning that the

compiler forces the programmer to check and deal with them.

1. Exercise

Please make a program to fill Guest Book

1. The program begins by asking for inputs:

- Name

Validate name’s length must be 5-15 characters!

- Age

Validate Age must be number between 17-50! (use Try-Catch concept)

- Comment

Validate that comment must be filled!

2. Print data from Guest Book.

Print Screen of the Program Ask User to input data

Print Screen of user wrong input

Page 75: Diktat Java Console

69 | P a g e

Print Screen of Data GuestBook

a. Task 01 - Create Project Java in Eclipse

i. Run Eclipse from Start Menu

ii. Open Menu File -> New -> Project

iii. On Project Window, choose Java Project and click next

iv. Enter name of project,click next and finish

v. On tree panel on the left side window, expand Project folder

vi.Right click on src and create new class

vii. Enter the name class

viii. Then Press Finish

b. Task 02 – Make and validate inputs from user

First ,you must type import java.util.Scanner as library for class Scanner

Declare variable to save value and object from Scanner for receive input

Input name

In this section you must use do while to loop if user do wrong input.

Input Age

In this section you must use do while to loop if user do wrong input.

Page 76: Diktat Java Console

70 | P a g e

Function in.nextLine() here is to get all buffer input from user like enter press.

Input Comment

In this section you must use do while to loop if user do wrong input.

c. Task 03 – Print Data Guest Book

Page 77: Diktat Java Console

71 | P a g e

Chapter 07

Array

Page 78: Diktat Java Console

72 | P a g e

Array Definition

Arrayisastructureddata typeasafixedamount(based on what isdefined)

andgivenaspecificname(as variable). In a simple word, an Array is a collection of items

which have same data type. An item in anArrayis called as elementsand

arrangedinrows.The position of an item in an array is defined by an index which

started from 0. Every arrayhas an addressadjacent/adjoiningdependentwidthdata

types.However, keep in mind,althoughits elementsarrangedinrows, the arraycan stillbe

accessedat randomin thememory.Arrayscan alsobe an array of1dimension, 2dimensions,

evenn-dimensional.

Illustration of one–dimensional array

Array Declaration and Manipulation

Arrayis declared like a variable. At the time of declaring arrays, you should make

a list of data types, followed by a pair of square brackets [], then followed by the

identifier name or you can place a pair of brackets [] after the identifier name also. In

declaring an Array, wemust allocatehow manyelementsthe array (usually we call it array

size) can holdbyusing the keyword ―new‖. For example:

// declare the data type, and identifier

int scores [];

// allocate how many elements on this array

scores = newint[100];

// this array can contain 100 elements

or it could be written with

// declaration and instantiate object

Page 79: Diktat Java Console

73 | P a g e

int scores [] = newint[100];

// this variable can contain 100 elements

The value of array that we create using above code will contains its data type

default value, as for the example above, the int data type will have default value filled

with 0.

We can also directly assign the value for each element in our array, when we

declare the array, but the array size will be same as the total elements when we first

declare the array.

For Example:

int scores [] = {1,2,3,4,5,6,7,8,9,0};

Each element in the array above will be filled with the value that we assigned,

and the size of the array will be constant 10, because we declare this array with 10

elements.

We can also duplicate array like we assigning a value to a variable using other

variable, as an example:

int scores[] = {1,2,3,4,5,6,7,8,9,0};

//to duplicate array scores to scoresDuplicate

intscoresDuplicate [] = scores;

on the above code, the scoresDuplicate variable will be hold exactly same value as the

scores variable.

Beware, the statement doesn’t copy the contents of the array by scores to

scoresDuplicate, but merely copies the reference value from scores to

scoresDuplicate. The array previously referenced by scoresDuplicate is no longer

referenced; it becomes garbage, which will be automatically collected by the JVM.

Page 80: Diktat Java Console

74 | P a g e

In Java, you can use assignment statements to copy primitive data type

variables, but not arrays. Assigning one array variable to another array variable actually

copies one reference to another and makes both variable point to the same memory

location. Thus, changing value of scores will change value of scoresDuplicate, too.

There are three ways to copy arrays:

Use a loop to copy individual elements one by one

for(inti=0; i<scores.length; i++)

scoresDuplicate[i] = scores[i];

Use the static arraycopy method in the System class

System.arraycopy(scores, 0, scoresDuplicate, 0, scores.length);

Use the clone method to copy arrays

scoresDuplicate = scores.clone();

To getthe length (or usually called by size)ofanarraywecanuse the.length after

the array name.

For Example:

int scores[] = {1,2,3,4,5,6,7,8,9,0};

int size = scores.length;

System.out.println(size);

Output:

Before the assignment intscoresDuplicate [] = scores;

scores scoresDuplicate

1,2,3,4,5,

6,7,8,9,0

?

After the assignment intscoresDuplicate [] = scores;

scores scoresDuplicate

1,2,3,4,5,

6,7,8,9,0

?

Page 81: Diktat Java Console

75 | P a g e

To access the item inside array, we must define the item position (or usually

called index) we want to access. We can add, remove or change the item inside an array

like a single value variable.

int scores[] = newint[20];

scores[0] = 17;

scores[1] = 7;

scores[2] = 10;

scores[3] = 5;

System.out.println("The First Scores: "+scores[0]);

System.out.println("The Second Scores: "+scores[1]);

System.out.println("The Third Scores: "+scores[2]);

System.out.println("The Fourth Scores: "+scores[3]);

Output:

In the example above, we’re assigning a value into scores array, 17 to index 0, 7

to the index 1, and so on. After that we will try to get the value from each index and

print it on the console window.

To print all item on the array, we can loop the array that we declared before, we

can use foreach or the common for loop. For Example:

System.out.println("this is foreach to display the content of array

scores: ");

// for-each loop

for(intvalue:scores)

{

System.out.print(value+", ");

}

System.out.println("\nthis is the common for to display the content of

array scores: ");

Page 82: Diktat Java Console

76 | P a g e

// for-loop

for(inti = 0;i <scores.length;i++)

{

System.out.print(scores[i]+", ");

}

Explanation:

In this statement, we can use foreach or the common for.

for(intvalue:scores)

In this statement, int value is used to accommodate the value of each index in

the array scores. The index is starting from 0 until n, where n is thearray length of

variable scores and the index will increase when turning to the initial statement for

itself.

System.out.print(value+", ");

This statement will display the value of the contents of the array variable

starts from 0 to length of the array.

for(inti = 0;i<scores.length;i++)

This statement is the common for inti is used for the initial value of a loop, then

i<scores.length here used for the initial loop, which means it will be repeated as much

as the length of an array, then the i++ means that the increment in each iteration is for

variable i.

System.out.print(scores[i]+", ");

This statement will display the value of the contents of the array variable

starts from 0 to length of the array.

Page 83: Diktat Java Console

77 | P a g e

Output:

Two Dimentional Array

Two dimentional array means, for every element in an array variable, also

contains an array object, something like array inside of array. The size of the array is

not always same, and can be different. The dimention for array can be more than two

dimention, it depends on our needs.

Declaration of Two Dimentional Array:

int scores[][];

scores = newint [3][4];

scores[0][0] = 5;

scores[0][1] = 20;

scores[0][2] = 1;

scores[0][3] = 11;

scores[1][0] = 4;

scores[1][1] = 7;

scores[1][2] = 67;

scores[1][3] = -9;

scores[2][0] = 9;

scores[2][1] = 0;

scores[2][2] = 45;

scores[2][3] = 3;

or

int scores[][] = {{5,20,1,11},{4,7,67,-9},{9,0,45,3}};

Ilustration of 2 dimentional array above

Page 84: Diktat Java Console

78 | P a g e

We can also loop the two dimentional array like what we do in one dimentional

array, with a little modification to our code. For Example:

publicclass Main {

publicstaticvoid main(String [] args)

{

System.out.println("this is foreach to display the content

of array scores: ");

for(int value[]:scores)

{

for(int value2 : value)

{

System.out.print(value2+" ");

}

System.out.println();

}

System.out.println("\nthis is the common for to display

the content of array scores: ");

for(inti = 0;i < 3;i++)

{

System.out.print(i+" -> ");

for(int j = 0; j < 4;j++)

{

System.out.print(scores[i][j]+" ");

}

System.out.println("");

}

}

}

Explanation:

In this statement, we can use foreach or the common for.

for(int value[]:scores)

In this statement, int value[] is used to accommodate the value of each index in

the array two dimensional scores. The index is starting from 0 until n, where n is

thearray length of variable scores and the index will increase when turning to the initial

statement for itself.

for(intvalue2:value)

Page 85: Diktat Java Console

79 | P a g e

In this statement, int value2 is used to accommodate the value of each index in

the array value. The index is starting from 0 until n, where n is thearray length of

variable value and the index will increase when turning to the initial statement for itself.

System.out.print(value2+" ");

This statement will display the value of the contents of the array variable starts

from 0 to length of the array and add a space character after each item.

for(inti = 0;i< 3;i++)

This statement is the common for inti is used for the initial value of a loop, then

i< 3 here used for the initial loop, which here means it will be repeated as much as the

length of an array, then the i++ means that the increment in each iteration is for

variable i.

for(int j = 0;j < 4;j++)

This statement is the common for and the second for in this loop sequence. int j

is used for the initial value of a loop, then j < 4 here used for the initial loop, which here

means it will be repeated as much as the length of the inner array, then the j++ means

that the increment in each iteration is for variable j.

System.out.print(scores[i][j]+" ");

This statement will display the value of the itemsin the array scores

starts from 0 until the length of the array in two dimensional, i for the first array

(scores[i][xxx]) and j for the second array (scores[xxx][j]).

Page 86: Diktat Java Console

80 | P a g e

Output:

Ragged Arrays

Each row in a two-dimensional array is itself an array. Thus the rows can have

different lengths. An array of this kind is known as a ragged array. Here is an example

of creating a ragged array.

If you don’t know the values in a ragged array in advance, but know the sizes,

say the same as before, you can create a ragged array using the syntax that follows:

int[][] triangleArray = new int[5][];

triangeArray[0] = new int[5];

triangeArray[1] = new int[4];

triangeArray[2] = new int[3];

triangeArray[3] = new int[2];

triangeArray[4] = new int[1];

The syntax new int[5][] for creating an array requires the first index to be specified.

The syntax new int[][] would be wrong.

Int [][] triangleArray = {

{1, 2, 3, 4, 5},

{2, 3, 4, 5},

{3, 4, 5},

{4, 5},

{5}

};

1 2 3 4 5

2 3 4 5

3 4 5

4 5

5

Page 87: Diktat Java Console

81 | P a g e

1. Exercise

For exercise, we will make a simple program. This program is a book store where

the user can add books to shoping cart and in the end of the transaction, the user can

buy all of the book he/she add to shoping cart. There are some list of books the user can

buy and 3 menus in this program.

There are:

1. Add to Shopping Cart

2. See Shopping Cart

3. Exit and Pay

- If the User choose Add to Shopping Cart, then:

o The user were asked to choose which book they want to buy, validate the

user input is only 1 until 5.

o After this, the user were asked to input the quantity of the book, validate

the user just can input 1 until the available book stock.

o Then, display the information of the book that user want to buy.

o If the existing stock is zero, the user can‟t buy that book, and the

program will display error message: ―The Book is no stock‖.

- If the User choose See Shopping Cart, then:

o Show all the books the user want to buy, and it’s name, quantity the user

want, total price of that books, and the grand total.

o If the user still not buy anything, the program will show error message:

―Please add book to shopping cart first‖

- If the User choose Exit and Pay, then:

o Show the grand total of the transaction and ask the user to input the

payment. Validate the payment cannot be lower than grand total.

o If the payment has change, show the change of the payment.

o The program will end.

a. Task 1: Create Project Java in Eclipse

- Run Eclipse from start Menu

- Open Menu File New Project

- Choose Java Project Fill Project Name example: ―Answer07‖

- Press Finish, and show pop up, choose ―No‖

Page 88: Diktat Java Console

82 | P a g e

b. Task 2: Create the main Class

The Main class is the primary class of our program that will be invoked first by

the compiler. And the main method will call the constructor of main class where we put

our code to make this program, and we also import java.util.Scanner to use the

Scanner class.

c. Task 3: Create variable arrays

First, we must decide how many arrays will be used. In this program we need

name, price, quantity, quantity the user want to buy and total price in for each book. So,

we make 5 arrays to store the required data above, with different name and of course

we must give it a name with characteristic and describe it’s function.

We will also make a object of Scanner class, and make variable that needed in

our program like in the code below.

Page 89: Diktat Java Console

83 | P a g e

Page 90: Diktat Java Console

84 | P a g e

d. Task 4: Create main menu

After we create all the object, array and variables we need, we will create main

menu for our program, see the code below.

Explanation:

This part of code used to print all available book to sell, the logic is to print all the

data on the corresponding arrays, so we use for loop to print all data in the array

starting from index 0 until the length of the array, and to print the data, we will use

printf to print the data using our defined format.

Page 91: Diktat Java Console

85 | P a g e

This code used to validate the user input must be between 1 and 3, and we will

surround the input statement with try-catch block to catch if there is any exception

occurred if the user input is not a number.

This code used to validate if the user input isn’t 3, then the program will loop

from the beginning until the user input 3. And if the user input 3, then the program will

be ended.

e. Task 5: Build menu number one (Add to Shopping Cart)

Before we build menu 1, we must make selection to put code menu one, two and

three. In this program, we will a use switch case structure.

Page 92: Diktat Java Console

86 | P a g e

After we make switch case, we can put code for menu 1 in case 1.

Explanation:

In this code, we stored input from the user to variable qtyTemp to add qty from

the product that user want to buy.

Page 93: Diktat Java Console

87 | P a g e

We display the product that user want to buy with the product name, quantity

and total price to be added to shopping cart.

In this code, we will add how many quantity we want to buy to the array. As we

know, the index of a array started from 0, but if the user want to buy the first item, they

will input a number ―1‖, so we will decrease the user input by 1.

After that, we will add the quantity of the book the user want to buy (qtyTemp)

to the array qtyCart (qtyCart + qtyTemp), and we must decrease the book quantity

from array qty as many as the user buy (qty - qtyTemp).

For the price, we will multiply the book price, with the quantity of the book that

user want.

For computing grand total of the price,first, we set the variable grand to 0. So

with looping for, we loop 5 times or according to the length of priceCart, and we add a

value to grandwith every price on the priceCart array.

Page 94: Diktat Java Console

88 | P a g e

f. Task 6: Build menu number two (see Shopping Cart)

We put the code for menu number two in case 2.

Explanation:

Page 95: Diktat Java Console

89 | P a g e

We will loop 5 times or as many as the length of arrays name and in this loop, we

validate, if the quantity in the shopping cart on index i is more than 0, we set the

variable flag value to 0 and we break the loop, because it means the user is already buy

some item, or if it less than zero (the user never buy any item), we set the variable flag

value to 1 and we continue the loop until the loop ends or we find the break statement.

After we validate the quantity, we will validate the flag, if it’s 0, meaning one of

item quantity the user want to buy is more than 0. So we use the loop to display

products in shopping cart. But before we display, we make a validation again, if the

quantity in shopping cart we want to display is more than 0 or not. If it yes, we display,

if not, we do not display the product. After that we display grandin the end and we

already out in loop. And if the flag is not 0, we ask the user to add a product to

shopping cart first.

Page 96: Diktat Java Console

90 | P a g e

g. Task 7: Build menu number three (Exit and Pay)

We put the code for menu number three in case 3.

Explanation:

In this code, first we will validate, is the grand total is more than 0 or not, if it is

not, we didn’t display the grand total and other data, but if the grand total is more than

0, we will display the grand total, and we ask the user to input their payment, and we

will validate the money must be more than or equals the grand total. If the money is

more than grand total, we will calculate the change for their payment. And the program

will be ended.

Page 97: Diktat Java Console

91 | P a g e

Chapter 08

Methods

Page 98: Diktat Java Console

92 | P a g e

Method Definition

The aim of method or function is to group the commands that are designated to

conduct a larger order. The main things needed in the making and declaring a method

are:

1. Modifiers - permissions that would regulate access this method, will

be discussedbelow.

2. Return value– data type to be returned by this method, void when no value is

returned.

3. Method Name -name to the method or function. This must be following a naming

convention.

4. Parameter-the declared type of data to get sent value as input for the

method.Surrounded by parentheses, (). A method can have no parameterat all.

5. The content of method-the commands to be run in the method,surrounded by {}.

One example that will be commonlyused is the main method:

public static void main(String [] args){ //content }

Explanation:

1. public static are the modifiers

2. void is the return value, in this case the method does not return a value

3. main is the method name

4. String [] args is the parameter to get sent value, in this case is an array of String

5. {/ / content} is where to put the commands to be run.

Example of declaringa method that we want to create:

publicstaticvoid function1(/*parameters*/int value)

{

//content

System.out.println("The Value is "+value);

}

Page 99: Diktat Java Console

93 | P a g e

Example of calling a method that we have created:

public static void main(String[] args) {

int score = 10;

function1(score);

}

Explanation:

function1(score) is used to call the function1method with their parameters if

available. So, if we call this method, the code inside the method will be executed.The

statement System.out.println("The Value is "+value);will be executed.

Variable Scope

In Java, there are 2 kinds of variable scope; there are global variable and local

variable. If we use global variable, every method can access this variable and can

change its value. But if we use local variable, it is just recognized in that method.We

can’t use it in other methods except we send (pass) that variable to another method.

Global Variable

public class Example

{

staticintnumber;

publicstaticvoid function()

{

number = 10;

System.out.println("The Value in Global: "+number);

}

publicstaticvoid main(String[] args) {

function();

}

}

Page 100: Diktat Java Console

94 | P a g e

Explanation:

Variable number, as a global variable, can be used in every method.We declare

variable number as a global variable and use it in method function. We fill number

with 10, and display the numbervalue. In the main method, we will call the method

function() to see the output.

Output:

Local Variable

public class Example

{

publicstaticvoid function()

{

intnumber = 10;

System.out.println("variable value in function: "+number);

}

publicstaticvoid main(String[] args) {

intnumber = 17;

function();

System.out.println("variable value in main: "+number);

}

}

Explanation:

The variable number, as a local variable, was declared inside the method

function().So, its value in method function() and method main()are different.The

two variablesnumber were declared on the separated method.

Output:

Page 101: Diktat Java Console

95 | P a g e

Passing Parameter to a Method

We can send a value to a method to be processed.The value that will be passed

between method is called as a parameter.The parameter can be a variable, array, even

an object. There are 2 ways to pass a parameter:Passing by Value and Passing by

Reference.

Passing Parameter by Value:

publicstaticvoiddisplayParam(intparams)

{

System.out.println("The Paramater Value: "+params);

}

publicstaticvoid main(String[] args)

{

intval = 7;

method(val);

}

Explanation:

Passing parameter by value means that the parameter passed only its value, not

the address or reference.We can’t change the variable val value in

displayParammethod, because we just pass its value, not its reference.

Output:

Page 102: Diktat Java Console

96 | P a g e

Passing paramater by reference:

publicstaticvoid method(int values[])

{

values[0] = 7;

}

publicstaticvoid main(String[] args) {

int scores[] = newint [5];

scores[0] = 15;

System.out.println("The value before change:"+scores[0]);

method(scores);

System.out.println("The Value after change: "+scores[0]);

}

Explanation:

In this section, we will try to passparameter by reference.We don’t pass the value

of the variable, but the reference to that variable.

Every variable has a address or reference.If we pass it to a method, we pass

everything in that variable: the address and the value. We can change the variable value

in that method.The value on the sender method is also changed.

For a example, we have an array scores in main method.Why we use array?

Because in Java, we can pass reference by using array variable. In scores[0], first we

instantiate with 15 and we display it.Then we call method(scores).In method(), the

scores[0]is changed to 7, and then we display the value in the main() method.The

value on the main method is also changed.

Output:

Page 103: Diktat Java Console

97 | P a g e

Return Value

There are method returning a value and no returning anything (null). Amethod

that returnsnulluses the keyword “void” for the return type.It meansthat the method

doesn’t return any value like this code:

publicstaticvoid method(int values[]){

values[0] = 7;

}

The other one is method which returns a value.We must define the return type

for the method.Return type can be a primitive data type, an array or a Class. The return

type for the method must be same with the data type of the returned value by the

method. This method must use keyword return to return a value. Let’s see the example

below:

public static intaddValue(intvalue1, intvalue2)

{

returnvalue1+ value2;

}

public static void main(String[] args) {

intresult = addValue(5, 7);

System.out.println("The Result 5 + 7 :" + result);

}

Explanation:

In the main method, we call method addValue(5, 7).The method addValue()

will returning a value, so we will store the result on the variable result.As we can see,

we didn’t use keyword voidwhen declaring the method addValue(), but we use

keyword int.Why we use int? It depends on what type we want to return. If we want to

return int, so we use int.If we want to return a floating number, so we use float. In

method addValue(), we will add value1 and value2, and finally we return the result of

the addition. The result variable is used to store the value that is returned by the

method addValue().

Page 104: Diktat Java Console

98 | P a g e

Output:

In a different case, a method can return an array.We use keyword int[] to

return an array of int. Example:

public static int[] givingArray()

{

intdecimal[] = {45,12,53,34,25,16,77};

returndecimal;

}

public static void main(String[] args) {

intresult[] = givingArray();

for(inti = 0;i<result.length;i++)

{

System.out.println((i+1)+"->"+ result[i]);

}

}

Explanation:

In main method, we called givingArray().Everything that is returned by

givingArray()will be stored on array result.The method givingArray()must be

returning an array. We use keyword int[] to return an array of int. In givingArray(),

we declare a new array with initialization and we return the array to main method.Array

result will have the same items with the array that is returned by givingArray().

Page 105: Diktat Java Console

99 | P a g e

Output:

Overloading Method

We can make two methods with a same name. Sometimes, we need methods

with same function, and only differ in parameter, Java allow us to have this kind of

method: two or more methods with same name, but with different parameter.The

parameter can be differed on the data type, and number of parameters. This kind of

method is called as Overloading Method. Example:

public static void view(String word)

{

System.out.println("The Word is: "+word);

}

public static void view(String word, String word2)

{

System.out.print("The First Word is: "+word);

System.out.println(" and the second Word is "+word2);

}

public static void main(String[] args) {

view("Hallo");

view("Hallo","World");

}

Page 106: Diktat Java Console

100 | P a g e

Explanation:

We write 2 methods with the same name but different paramater. It’s called

overloading method. It isn’t an error.Both methodsare different function. In main

method, we can call both methods.We call the first method with one parameter and the

second method with two parameters.

Output:

Each time a method is invoked, the system stores parameters and variables in an

area of memory known as a stack, which stores elements in last-in, first-out fashion.

When a method calls another method, the caller’s stack space is kept intact, and new

space is created to handle the new method call. When a method finishes its work and

return to its caller, its associated space is released.

Passing Arrays to Methods and Returning an Array from a Method

Just as you can pass primitve type values to methods, you can also pass arrays

to methods. For example, the following method displays the elements in an array of int:

public static void printArray(int[] array) {

for(inti=0;i<array.length;i++){

System.out.println((array[i]+" ");

}

}

You can invoke it by passing an array. For example, the following statement invokes the

printArray method to display 3, 1, 2, 6, 4, and 2.

printArray(new int[] { 3, 1, 2, 6, 4, 2 });

There’s no explicit reference variable for the array. Such array is called an anonymous

array.

Page 107: Diktat Java Console

101 | P a g e

A method may also return an array. For example, the method shown below

returns an array that is the reversal of another array:

public static int[]reverse(int[] list) {

int[] result = new int[list.length];

for(inti=0, j=result.length-1; i<list.length; i++, j--) {

result[j] = list[i];

}

}

1. Exercise

For exercise, you’ll creat a program to calculate everything that user inputs. First,

this program will ask a user to input how many number that the user want to

calculate.Input must be validated between 2 and 6.Afterthat,the program will ask

the user to input nnumbers according to the previous input.If on the previous, the user

inputs 4, the user will be asked to input 4 numbers later.Validate the next input must

be between 1and 25. The program will display 3 menus:

1. Calculate the All numbers

This menu displays the addition of all inputted number

2. Average of the All number

This menu displays the average of all inputted number

3. Exit

End of program.

a. Task 1: Create Project Java in Eclipse

- Run Eclipse from start Menu

- Open Menu File New Project

- Choose Java Project Fill Project Name example: ―Answer08‖

- Press Finish, and show pop up, choose ―No‖.

b. Task 2: Create the main Class

The Main class is where we write code. We write main method in the Main class,

and also import java.util.Scanner to use the Scanner class.

Page 108: Diktat Java Console

102 | P a g e

We need a global variable to create a Scannerobject, so it can be used by every

method.

c. Task 3: Create the input for calculating

Application needs to ask user to input a number, and also input nnumber.

We must write a method to input the number onint [] amount =

inputAmount();.Method inputAmountmust return an array.

Page 109: Diktat Java Console

103 | P a g e

We use keyword int[], not int or void, because the method returns array of

int.At the end of method,it returns array of int whose length that has been inputted by

the user.

d. Task 4: Create the main menu method

After we create the first step of this program, we create a method to display the

menu.

Method cls()is used to make a new clear window of command

prompt.MethoddisplayNumber(amount) is used to display the number that had been

inputted by the user.Methodmenu() is used to display the menu and returned the user’s

choice.

The code validateswhether the input is 3 or not. It will loop until the user input 3.

This is the code of the methods:

Page 110: Diktat Java Console

104 | P a g e

e. Task 5: Create the menu contents

Before we create menu 1, we must make a selection process. We may use

switch case.

Page 111: Diktat Java Console

105 | P a g e

Afterthat, we write code for each menu in each case.

Menu 1 isused to display calculating process of all numbers.

StatementSystem.out.println("Calculate the All number is

"+calculate(amount)) means that the method calculatehas paramater of array and

return a value. Here’s the method calcuate.

We just use loop process to count variable ifrom 0 until the length of the array

amount, and we sum its value to variablecount. Afterthat, we return count.

Menu 2 is used to display the average of all numbers.

StatementSystem.out.println(" Average of the All Number is

"+average(amount));means that the method averagehas parameter of array and

return a value. Here’s the method average.

Page 112: Diktat Java Console

106 | P a g e

This method returnsa result of calculate(amount) divided by length of array.

This method also call method calculate.

Menu 3 is used to display some messages and finish the program.

Page 113: Diktat Java Console

107 | P a g e

Chapter 09

Recursion

Page 114: Diktat Java Console

108 | P a g e

Recursion Definition

Recursion is a method that directly or indirectly invokes themselves. It means

thata method with name ―function1‖ calls itself.Recursionwill be neededin a program

which has a ―Divide and Conquer”characteristic.The declaration of recursion is same with

usual method.Remember, we must make a parameter or global variable to use a

condition to exit the function (which usually called as base-caseor stopping condition).If

not, the function will call itself infinitely and the runtime stack overflowsexception may

occur.

Example:

publicstaticvoid function1(int value)

{

if(value > 0)

{

System.out.println("Recursive");

function1(value-1);// we call the function itself

}

}

publicstaticvoid main(String[] args) {

function1(3);

}

Explanation:

In function1, we have a parametervalue. In this method, if value more than

zero,it will display the word ―Recursive‖ and call the function with parametervalue-1. In

main method, it call function1 with value 3.

Page 115: Diktat Java Console

109 | P a g e

Themain method will call function1(3). In function1method itself, it will create

its base-case (when the recursion will end) to check whether the variable valueis more

than 0 or not. If it’s true, the program will display ―Recusive‖ and call function1(3-1) or

in a simple form, function1(2), and so on until its value less than or equals 0 so the

function1 ends.The output will display ―Recursive‖ 3 times.

Output:

When we learn about recursion for the first time, we usually compare a recursion

with the common looping. The idea of iteration is similar to recursion looks like this:

publicstaticvoid main(String[] args) {

for(inti = 0; i< 3; i++)

{

System.out.println("Recursive");

}

Page 116: Diktat Java Console

110 | P a g e

}

The output of the loop above is same with the recursion we’ve made with function1().

We can also return a value in a recursion when we need it.For example:

publicstaticint function1(int value)

{

if(value > 0)

{

return value+function1(value-1);

}

return value;

}

publicstaticvoid main(String[] args) {

System.out.println(function1(3));

}

Explanation:

The explanation of this code is exactly same with the recursion without return

value.The different is, in the example above, when we callfunction1(3), we check

whether the value is more than 0 or not.

Page 117: Diktat Java Console

111 | P a g e

If it’s true, then it will return value+function1(3-1) or function1(2) and so

on. In that case, we must call the function1(2) on go until the value is 0 so we call

function1(0).If the condition is false, it returns the value without calling the method

again.So,it returnsa value and function1(0)ends.The chainsare:

function1(0): return 0, the function1(0) end;

function1(1): return 1+function1(0) return 1, the function1(1) end;

function1(2): return 2 + function1(1) return 3, the function1(2) end;

function1(3): return 3+function1(2) return 6, the function1(3) end;

and we will back to main method.

Output:

The recursionmethod is similar with loop process:

publicstaticvoid main(String[] args) {

intvalue = 0;

for(inti = 0; i<= 3; i++)

{

value+=i;

}

System.out.println(value);

}

Recursion is an alternative form of program control. It is essentially repetition

without a loop. When you use loops, you specify a loop body. The repetition of the loop

body is controlled by the loop control structure. In recursion, the method itself is called

repeatedly. Recursion bears substantial overhead. Each time the program calls a

method, the system must assign space for all of the method’s local variable and

parameters. This can consume considerable memory and requires extra time to manage

the additional space.

Any problem that can be solved recursively can be solved nonrecursively with

iterations. Recursion has some negative aspects: it uses up to much time and memory.

Page 118: Diktat Java Console

112 | P a g e

Why, then, should you use it? In some cases, using recursion enables you to specify for

an inherently recursive problem a clear, simple solution that would otherwise be difficult

to obtain.

The decision whether to use recursion or iteration should be based on the nature

of, and your understanding of, the problem you are trying to solve. The rule of thumb is

to use whichever approach can best develop an intuitive solution that naturally mirrors

the problem. If an iterative solution is obvious, use it.

Your recursive program could run out of memory, causing a

StackOverflowError. If you are concerned about your progam’s performance, avoid

using recursion, because it takes more time and consumes more memory than iteration.

2. Exercise

You have to make a program that uses binary number, Fibonacci number,

and odds and even number.First, you are asked to display menu:

1. Binary Number

2. Fibonacci Number

3. Odd and Even Number

4. Exit

- If user chooses Binary number, then:

o User is asked to input a number that user want to convert to binary

number.Validate the number so just can input number from 1 until

255.

o After this, display the binary number of it.

- If user choosesFibonacci number,then:

o User is asked to input a number and display nFibonaccinumber.Validate the

number so just can input number from 1 until 20.

o After this, display the nFibonacci number, where n is user’s input.

- If user choosesOdd and Even Number,then:

o User is asked to input a number and display nodd and even number.Validate

the number so just can input number from 5 until 50.

o After this, user is asked to input a start-number, validate the number so

just can input from 1 until 100.

Page 119: Diktat Java Console

113 | P a g e

o After this, display Odd and Even Number as many as user’s input beginsfrom

the start-number.

- If the user choosesExit, the program ends.

a. Task 1: Create Project Java in Eclipse

- Run Eclipse from start Menu

- Open Menu File New Project

- Choose Java Project Fill Project Name, example: ―Answer09‖

- Press Finish, and show pop up, choose ―No‖.

b. Task 2: Create the main Class

The Main class is where we write code. We will make the main method where

we will write code in the Main class, and also import java.util.Scanner to use the

Scanner class.

In this case, we use a global variable to create the scanner object, so it can be

used by every method.

Page 120: Diktat Java Console

114 | P a g e

c. Task 3:Create the main menu method

First, create the menu:

In this code, cls() isused to make a simulationof cleared command prompt.The

statementchoice = menu() isused to display the menu and get user’s choice.

The codeis used to validate whether the input is 4 or not (it will loop until the

user input 4). If the user input 4, the program will be ended.

This is the code of the methods:

Page 121: Diktat Java Console

115 | P a g e

d. Task 4: Create the menu contents

Before we create menu 1, we make a selection process.We use switch case.

Afterthat, we write code for each menu in each case.

Page 122: Diktat Java Console

116 | P a g e

Explanation:

In case 1, first we ask the user to input decimal number and validate the

number must be between 1 and 255. We use method validate(), with 3 parameters, to

display some word, minimum and maximum input number. Afterthat, we call

methodtoBinary(number) to convert decimal number to binary number.

Method validate that is used in case 1, 2 and 3:

In this method, we display the word that we have passed. We get user’s input

and store to variable number. We validate the number with min and maxthose we’ve

passed. Afterthat, we return the number.

Method toBinary to convert decimal to binary number:

It has base-case to stop the method if the number equals to 0.If the number

doesn’t equalto 0, it call the method withindivided-by-two parameter. After the number

is 0, it will display the number modulus by 2.

Page 123: Diktat Java Console

117 | P a g e

Example: The decimal number is 10, then the recursion steps:

o toBinary(10)

o Number != 0 -> toBinary(5) number = 10 …(1)

o Number != 0 -> toBinary(2) number = 5 …(2)

o Number != 0 -> toBinary(1) number = 2 …(3)

o Number != 0 toBinary(0) number = 1 …(4)

o Number == 0 end of function toBinary(0)

o Back to number(4), display number%2 1%2 = 1

o Back to number(3), display number%2 2%2 = 0

o Back to number(2), display number%2 5%2 = 1

o Back to number(1), display number%2 10%2 = 0

o The result is 1010

Incase 2, we ask the user to input the number, and validate the number

between 1 until 20. We use the method validate, with 3 parameters, to display some

word, minimum input number, and maximum input number. Afterthat, we call method

toFibonaci(number,0,1).It’s used to displayFibonacci number as many as passed

number.

We use method toFibonaci()to displaythe fibonacci number:

In this method, it has base-case to stop if the number equals to 0.If the number

doesn’t equals to 0, we display the value2. Afterthat, wecall the method again with

parameter number-1,value2, and value1+value2. The algorithm of fibonacci is:

Page 124: Diktat Java Console

118 | P a g e

Fibo(n) = Fibo(n – 1) + Fibo (n – 2)

Example:Input = 5, so the steps are:

o toFibonaci(5,0,1)

o Number != 0 -> display ―1 ‖ call toFibonaci(4,1,1)

o Number != 0 -> display ―1 ‖ call toFibonaci(3,1,2)

o Number != 0 -> display ―2 ‖ call toFibonaci(2,2,3)

o Number != 0 -> display ―3 ‖ call toFibonaci(1,3,5)

o Number != 0 -> display ―5 ‖ call toFibonaci(0,5,8)

o Number == 0 end of function toFibonaci(0,5,8)

o Number == 0 end of function toFibonaci(1,3,5)

o Number == 0 end of function toFibonaci(2,2,3)

o Number == 0 end of function toFibonaci(3,1,2)

o Number == 0 end of function toFibonaci(4,1,1)

o The result is ―1 1 2 3 5 ‖

In case 3, weask user to input amount of number to be displayed.We validate

the number between 5 until 50, and then ask the user to input the initial number of odd

and even number to be printed.

Afterthat,we validate the input must be between from 1 until 100. In this code,

we use the method validate()with 3 parameters, to display some word to, minimum

and maximum inputted number.

We call function toOdd(number, start) to display odd numberand start based

on thepassednumber.We call function toEven(number, start) to display number even

and start based on passed number.

Page 125: Diktat Java Console

119 | P a g e

In both methods, it has base-case to stop if the number equals 0.Themethod

toOdd() and toEven()are nearly same.The different ismethod

toOdd()validateswhether if the start number modulus by 2 is 0 and increase it by 1

(because we want to display the odd number).

Example: We have number 4 and it starts in 5

o toOdd(4,5)

o Number != 0 -> start%2 != 0 display ―5 ‖ call toOdd(3,7)

o Number != 0 -> start%2 != 0 display ―7 ‖ call toOdd(2,9)

o Number != 0 -> start%2 != 0 display ―9 ‖ call toOdd(1,11)

o Number != 0 -> start%2 != 0 display ―11 ‖ call toOdd(0,13)

o Number == 0 end of methodtoOdd(0,13)

o Number == 0 end of methodtoOdd(1,11)

o Number == 0 end of method toOdd(2,9)

o Number == 0 end of method toOdd(3,7)

o Number == 0 end of method toOdd(4,5)

o The result is ―5 7 9 11 ‖

o toEven(4,5)

o Number != 0 -> start%2 == 1 start+1 display ―6 ‖ call toEven (3,6)

o Number != 0 -> start%2 != 0 display ―8 ‖ call toEven (2,8)

o Number != 0 -> start%2 != 0 display ―10 ‖ call toEven(1,10)

Page 126: Diktat Java Console

120 | P a g e

o Number != 0 -> start%2 != 0 display ―12 ‖ call toEven (0,12)

o Number == 0 end of method toEven (0,12)

o Number == 0 end of method toEven(1,10)

o Number == 0 end of method toEven (2,8)

o Number == 0 end of method toEven (3,6)

o Number == 0 end of method toEven (4,5)

o The result is ―6 8 10 12 ‖

In case 4, it just display a sentence and finish the program.

The recursive implementation of the Fibonacci method is very simple and

straightforward, but not efficient. The more efficient solution is using loops. Though it is

not practical, the recursive Fibonacci method is a good example of how to write

recursvie methods.

Page 127: Diktat Java Console

121 | P a g e

Chapter 10

Sorting

Page 128: Diktat Java Console

122 | P a g e

Sorting Definition

In some application, sometimes we need to sort any of records. In that case, we can use

sorting algorithm. Sorting is a classic subject in computer science. We study sorting

algorithms to illustrate many creative approaches to problem solving, and these approaches

can be applied to solve other problems. Sorting algorithms are good for practicing

fundamental programming techniques using selection statements, loops, methods, and arrays.

In Java, we have so many sorting algorithms.In this tutorial, we will try to use 4 kinds of

sorting algorithm. There are bubble sort, selection sort, insertion sort, and merge sort.

Bubble Sort

public static void bubbleSort(int [] arr, int n)

{

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

for (int j = n-1; j >i; j--) {

if(arr[j-1] >arr[j])

{

int swap = arr[j-1];

arr[j-1] = arr[j];

arr[j] = swap;

}

}

}

}

Explanation:

In Bubble sort, we need a loop according to how many records we have in the variable.So we

will use loop, start from 0 until n times.In this example, we will make a method called

bubbleSort() for an easier usage.

After we create a loop torepeat n times, we use for again to check the value in array

arr.In this case, we check from the last index of the array.If we find the value in the array on

index j-1is greater than index j, we must swap the both value.The idea behind bubble sort

algorithm is, if we find the lower value, we must put the value in front index.

So we will start comparing from the last index with the previous index.If the value on the

last index is smaller than the previous index, swap the value. This process will be looped

until we compare to the first index of the array (index 0).

Page 129: Diktat Java Console

123 | P a g e

Selection Sort

public static void selectionSort(int [] arr, int n)

{

int temp;

for (int i = 0; i< n-1; i++) {

temp = i;

for (int j = i+1; j < n; j++)

if(arr[j] <arr[temp])

temp = j;

if(temp != i){

int swap = arr[i];

arr[i] = arr[temp];

arr[temp] = swap;

}

}

}

Explanation:

Selection Sort algorithm is similar to Bubble Sort algorithm.In Selection Sort, we will

search for the maximum or minimum value from the array, start from the first or last index of

the array until the end.Unlikely with the bubble sort, when we find the minimum or

maximum value, we will not swap the value, we just save the index in variable temp.

After we check the value using a loop, we will check whether the index we found on the

variable tempis same or not with the i, then we will swap the value.

Insertion Sort

public static void insertionSort(int [] arr, int n)

{

int i, j, temp;

for (i = 1; i<= n; i++) {

temp = arr[i];

for (j = i-1; j >= 0 &&arr[j] > temp; j--)

arr[j+1] = arr[j];

arr[j+1] = temp;

}

}

Page 130: Diktat Java Console

124 | P a g e

Explanation:

In Insertion Sort algorithm, we need a temporary variable to store the value of an array on

index i(we use a variable temp). On the second loop, we will start the loop using variable j.If

the initial value of j is i-1, we will check whether the value of the array on index j is larger

than temp or not.

If it’s true, value of the array on index j+1 will be changed with the value of array on

index j, and continuing the loop until j >= 0orarr[j] is bigger than temp. After the second

loop finished, the value of arr[j+1] will be filled with temp. The first loop will be repeated

until the condition is deal.

Merge Sort

public class Main {

public static void mergeSort(int array[],int lo, int n){

int low = lo;

int high = n;

if (low >= high) {

return;

}

int middle = (low + high) / 2;

mergeSort(array, low, middle);

mergeSort(array, middle + 1, high);

int end_low = middle;

int start_high = middle + 1;

while ((lo <= end_low) && (start_high<= high)) {

if (array[low] < array[start_high]) {

low++;

}

else {

int Temp = array[start_high];

for (int k = start_high- 1; k >= low; k--) {

array[k+1] = array[k];

}

array[low] = Temp;

low++;

end_low++;

start_high++;

}

}

}

}

Page 131: Diktat Java Console

125 | P a g e

Explanation:

Merge sort splits the array values in halves recursively until each half has only

single element. Merge the two 1/2 values together and sort the values. Do the same steps

iteratively until the values are not sorted.

First, we validate whether if lowis more than highor not, then the method ends.This

validationis used in recursiveuntil reachthe base-case. After that, we must split the array. The

data are divided by 2 and patched in variable middle.

Next we do recursionand send parameter array as array, low as lo and middle as n. We

do the recursion until we find low >= highcondition. We call the method again and send

parameter array as array, low as middle+1, n as high. Then, we patch variable end_low as

middle, and start_high as middle+1.

Working with merge sort algorithm

Let’s say that we have an unsorted array A[0],A[1],A[2], ...,A[n-1], and A[n] as input.

The following steps are followed by merge sort algorithm to sort the values of an array.

Steps of Merge Sort: Say an unsorted array values are: 12, 9, 4, 99, 120, 1, 3, 10

Step1: Spliting the values of array and divide the values into two

Step2: Merge two values and sort the values

Page 132: Diktat Java Console

126 | P a g e

Step3: Merge four values and sort the values

Step4: Merge n values and sort the values, n must be even number

3. Exercise

For exercise, you’ll have to make a book store program. User can add books and sort it.

There are list of books that user add, and 4 menus in this program.

There are:

1. Add Book

2. Sort Book ByNameAscending

3. Sort Book By Price Descending

4. Exit

- If user chooses Add Book, then:

o User is asked to input the name of book, validate inputwith length of stringis 3

until 25.

o After this, user is asked to input quantity, validate input is 1 until 25.

o After this, user is asked to input prices, validate user input is 1000 until 20000.

o Then, display the information of the book that user add.

- If user choosesSort book by Name Ascending, then:

o If there’s no book in the list, display the error message: “Please add book first.”

o Sort the book by name ascendingly, then display the result.

Page 133: Diktat Java Console

127 | P a g e

- If user choosesSort book byPriceDescending, then:

o If there’s no book in the list, display the error message: “Please add book first.”

o Sort the book by pricedescendingly, then display the result.

- If user choosesExit, thenprogram ends.

4. Answer

a. Task 1: Create Project Java in Eclipse

- Run Eclipse from start Menu

- Open Menu File New Project

- Choose Java Project Fill Project Name example: “Answer09”

- Press Finish, and show pop up, choose “No”.

b. Task 2: Create the main Class

The Main class is where we write code. We will make the main method where we

will write code in the Main class, and also import java.util.Scanner to use the Scanner

class.

In this case, we use a global variable to create the scanner object, so it can be used

by every method.

Page 134: Diktat Java Console

128 | P a g e

c. Task 3: Create the main menu method

First, create the menu:

In this code, cls() is used to make a simulation of cleared command prompt. The

statement choice = display(name,price,qty,n)is used to display the menu and get user’s

choice.

The codeis used to validate whether the input is 4 or not (it will loop until the user

input 4). If the user input 4, the program will be ended.

Page 135: Diktat Java Console

129 | P a g e

This is the code of the methods:

d. Task 4: Create the menu contents

Before we create menu 1, we make a selection process.We use switch case.

Page 136: Diktat Java Console

130 | P a g e

After that, we write code for each menu in each case.

In case 1, first we ask the user to input name of book, and we validate the input must

be between 3 until 25 characters. We ask user to input quantity and price, and validate

quantity must be between 1 and 25, and price must be between 1000 and 20000.

We use the method validate, with 3 paramaters: display a message to ask user,

minimum input number, and maximum input number. All of the inputsare

assigned/stored to variable array. Afterthat, we display the name, quantity, and price

that have been inputted.

Page 137: Diktat Java Console

131 | P a g e

Method validate:

In case 2, we call the method sortName(name,qty,price,n).In this method, we use

bubble sort algorithms to sort the records.We must swap 3 variables of array:name, qty,

and price. We use methodswap with the parameter of an Object array, integer i and j.

Method sortName uses to sort records based on name ascendingly.

Method swap uses to exchange an object/value each other:

Page 138: Diktat Java Console

132 | P a g e

In case 3, we call the method sortPrice(name,qty,price,n).In this method, we use

selection sort algorithm to sort the records.

Method sortPrice uses to sort records based on pricedescendingly.

Page 139: Diktat Java Console

133 | P a g e

Chapter 11

Utility

Page 140: Diktat Java Console

134 | P a g e

Random Number

In java, we can generate a random number with Class Random from

java.util.Random package.If we want to generate a random number from 1 to 10,

there are the steps to random numbers:

o First, we must import java.util.Random

o Second, we must create an object of class Random, then we can use the object to

generate a random number.

o Third, we can store to intvariable or directly display to console.

importjava.util.Random;

publicclass Main {

publicstaticvoid main(String[] args) {

Random rand = newRandom();

System.out.println(rand.nextInt());

}

}

Output:

In that case, we just generate an uncontrolled random number.If we want to

generate a control random number, we must put a parameter inside rand.nextInt().

For example, if we put 5, the result will be between 0 until 4. If we want to generate a

random number between 1 until 10, we must put 10 and the result of random must be

added by 1. If we don’t add the number by 1, it just generate a random number

between 0 – 9.

importjava.util.Random;

publicclass Main {

publicstaticvoid main(String[] args) {

Random rand = newRandom();

System.out.println((rand.nextInt(10)+1));

}

}

Page 141: Diktat Java Console

135 | P a g e

Currency Format

In Java, we can get currency format in some country. If we want to get the currency

format in US, we use the class Curency from java.util.Currency. Example:

importjava.util.Currency;

importjava.util.Locale;

publicclass Main {

publicstaticvoid main(String[] args) {

Currency currency = Currency.getInstance(Locale.JAPAN);

System.out.println("Currency.getSymbol() = "

+ currency.getSymbol());

currency = Currency.getInstance(Locale.UK);

System.out.println("Currency.getSymbol() = "

+ currency.getSymbol());

currency = Currency.getInstance(Locale.US);

System.out.println("Currency.getSymbol() = "

+ currency.getSymbol());

currency = Currency.getInstance(new Locale("in", "ID"));

System.out.println("Currency.getSymbol() = "

+ currency.getSymbol());

}

}

Output:

Delay Execution

If we want to make an animation or delay in our program, we can use

delayexecution. There are two kinds of delayexecution: use for(common looping) or

Thread.sleep. Example:

publicclass Main {

publicstaticvoid main(String[] args) {

int loop = 0;

Page 142: Diktat Java Console

136 | P a g e

System.out.print("Loading Menu");

do{

//with the common for

for(inti = 0;i <2000000000;i++);

System.out.print(".");

loop++;

}while(loop < 10);

for(inti = 0;i < 25;i++)

System.out.println();

loop = 0;

System.out.print("Loading Menu");

do{

try {

//with thread.sleep

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.print(".");

loop++;

}while(loop < 10);

}

}

Explanation:

In this code, we use for to delay or execution. If we use i<2000000000 loop statement, it

is too long. If we use Thread.sleep, we just write Thread.sleep(1000) for 1 second. We

must create a try catch to this Thread. The parameter inside Thread.sleep is millisecond.

Calendar Information

In java, there is class Calendar from java.util.Calendar. It is used to get date and time

information. Example:

Import java.util.Calendar;

public class Main {

Page 143: Diktat Java Console

137 | P a g e

public static void main(String[] args) {

do{

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

for(inti = 0;i < 25;i++)

System.out.println();

System.out.println(Calendar.getInstance().getTime());

}while(true);

}

}

Explanation:

In this code, we create the program to get time information. If we run this code, it will

loopinfinitely (that’s not an error) for displayingtime per second.

Reflection Class

In java, Reflection class is used to get information of a class by using

java.util.reflect.*package. There are many classes like Method, Fields and

etc.Reflection is used to get information inside a class.Example:

importjava.lang.reflect.Field;

importjava.lang.reflect.Method;

class People{

private String name;

private int age;

public People(String name,int age){

this.name=name;

this.age=age;

}

Public void setName(String name) {

this.name = name;

}

Public void setAge(int age) {

Page 144: Diktat Java Console

138 | P a g e

this.age = age;

}

public String getName() {

return name;

}

Public int getAge() {

Return age;

}

Public void display(String name, int ages){

System.out.println("I'm "+name+" with age "+ages);

}

}

Public class Main {

Public static void main(String[] args) {

Class <People> obj = People.class;

Field[] attr = obj.getDeclaredFields();

People objPeople = new People("Black", 17);

System.out.print("The Attribut in class People is ");

for(Field val:attr){

System.out.print(val.getName()+", ");

}

try {

Method method = obj.getMethod("getName", null);

System.out.println("\nName: "+method.invoke(objPeople,

null));

Method method2 = obj.getMethod("display", new

Class[]{String.class,int.class});

method2.invoke(objPeople, new Object[]{"White",17});

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

Explanation:

Page 145: Diktat Java Console

139 | P a g e

We create a variable from People.class and we create an array of Field from

java.util.reflect.Field.It’s used to get information of attributes in class People. Then,

if we want to call the method in another class, we must create an object of class

People, and create an object method to store the information of the method.If we

want to call the method, we may use invoke.

Output:

Timer Class

Java has class Timer in java.util.Timer package. It is used to schedule any

acitivites.The class Timer is similary use to Thread.sleep, but class Timer can repeat

an activity. Example:

importjava.util.Date;

importjava.util.Timer;

importjava.util.TimerTask;

/**

* Simple demo that uses java.util.Timer to schedule a task to execute

once 10

* seconds have passed.

*/

publicclass Main {

Timer timer;

public Main(int seconds) {

timer = new Timer();

//new date() to repeat, if we didn't use new date, it just delay

timer.schedule(newRemindTask(),new Date(), seconds * 1000);

}

Page 146: Diktat Java Console

140 | P a g e

classRemindTaskextendsTimerTask {

publicvoid run() {

System.out.println("Time's up!");

//timer.cancel(); //Not necessary because we call System.exit

//System.exit(0); //Stops the AWT thread (and everything else)

}

}

publicstaticvoid main(String args[]) {

System.out.println("About to schedule task.");

new Main(10);

System.out.println("Task scheduled.");

}

}

Explanation:

In this code, if we want to use the class Timer, we create an object of class

Timer.If we want to delay, we must use timer.schedule with parameter the

TimerTask, date(if you want to repeat), and delay.

5. Exercise

For exercise, you make a program that has many functions. First, it can be show

the datetime today, then there is a loading bar to generate random number 3 times

between 5 until 17.Finally,there is a choice to repeat the program or not.If use chooses

not, the program ends, If yes, the program restarts.

a. Task 1: Create Project Java in Eclipse

- Run Eclipse from start Menu

- Open Menu File New Project

- Choose Java Project Fill Project Name example: ―Answer11‖

- Press Finish, and show pop up, choose ―No‖.

b. Task 2: Create the main Class

The Main class is where we write code. We will make the main method where

we will write code in the Main class, and also import java.util.Scanner to use the

Scanner class.

Page 147: Diktat Java Console

141 | P a g e

In this case, we use a global variable to create the scanner object, so it can be

used by every method.

Page 148: Diktat Java Console

142 | P a g e

c. Task 3: Show the time of today

First, we must display the time of today by usingclass Calendar and import

java.util.Calendar.We also create an object of class Random to generate random

numbers.

d. Task 4: create the Random Number with delay

After we display the time, we display delayed random number.

We need variable index to loop 3 times.Variableindexis added by1, and afterthat

starts to loop again.We use delay execution by using Thread.sleepin 20 times looping

to display the dot symbol (―.‖).After loading-process ends, it displays the random

number between 5 until 17.We ask user to get the program repeat or not.

Page 149: Diktat Java Console

143 | P a g e

Page 150: Diktat Java Console

144 | P a g e

Code:

Page 151: Diktat Java Console

145 | P a g e

Chapter 12

Introduction to OOP Concept

Page 152: Diktat Java Console

146 | P a g e

Object Oriented Programming (OOP) is a programming paradigm using objects. Some

techniques may include feature such as data abstraction, encapsulation, inheritance, and so on.

Benefits of Object Oriented Programming:

a. The concept of a data class makes it possible to define subclasses of data objects that

share some or all of the main class characteristics. Called inheritance, this property of

OOP forces a more thorough data analysis, reduces development time, and ensures more

accurate coding.

b. Since a class defines only the data it needs to be concerned with, when an instance of that

class (an object) is run, the code will not be able to accidentally access other program

data. This characteristic of data hiding provides greater system security and avoids

unintended data corruption.

c. The definition of a class is reuseable not only by the program for which it is initially

created but also by other object-oriented programs (and, for this reason, can be more

easily distributed for use in networks).

The concept of data classes allows a programmer to create any new data type that is not

already defined in the language itself.

Exercise

Exercise for Object Oriented Programming

a. Blueprint for a software object is called a class

b. An object’s state is stored in fields.

c. An object’s behavior is exposed through methods.

What are the fields and behavior that a human has?

Fields

o Name

o Age

o Gender

o Etc

Page 153: Diktat Java Console

147 | P a g e

Behavior

o Speak

o Walk/Run

o Sleep

o etc

Page 154: Diktat Java Console

148 | P a g e

Chapter 13

Class and Object

Page 155: Diktat Java Console

149 | P a g e

Class Definition

Class is a collection of attribute and method that have similar function or a blueprint from a

object. A class usually represent a noun, such as person, place or thing. For an example, for a

simple program to calculate GPA from student, we will have class called „Student‟ that have

attribute to store data from the student such as NIM, Name, GPA, and Phone number. And

method to calculate GPA like the diagram below:

This diagram, show the structure from class Student

We can transfer that diagram into Java program with this code:

Object Definition

Objects are key to understanding object-oriented technology and a representation from a

class. As we already stated above, there are many examples of class or object, for example: your

bicycle, your computer, your car, your keyboard. Objects share two characteristics: state and

behavior. Bicycles have state (color, pedal, gear) and behavior (changing gear, applying brakes).

Page 156: Diktat Java Console

150 | P a g e

Objects are conceptually similar to real-world object (state and behavior). An object store its

state in fields (variable) and exposes its behavior through methods (function). An object is

defined by using keyword “new”.

This diagram shows the relation between fields (attribute) and methods

In the real world, you’ll find many individual objects all of the same kind. There may be

thousands of car in existence, all of the same make and model. Each car was built from the same

set of blueprints and contains the same components. A class is the blueprint from which

individual objects are created. Look at the example :

As we mentioned above, in the real world, you’ll find many individual objects all of the

same kind. Like an university that have thousand of students, all of their students is have similar

attribute, every student must have a nim, name, gpa, and phone number, the students in the

Page 157: Diktat Java Console

151 | P a g e

university is what we called object from a class, like showed in the picture above, thomas and

claire is a object that represent the class Student.

This following code is a example to make an object from class Student in Java:

Constructor

Each class has its constructor. A constructor is invoked every time an object is created.

Constructor declarations look like method declarations – except that they use the name of the

class and have no return type. Every class may have one or more constructors.

Inner Class

Inner class, or we can say nested class, occurs when you define a class within another class.

Nested classes are divided into two categories: static and non-static. Nested classes that are

declared static are simply called static nested classes. Non-static nested classes are called inner

classes.

Why use nested classes?

It is a way of logically grouping classes that are only used in one place.

It increases encapsulation.

Nested classes can lead to more readable and maintainable code.

Exercise

For exercise, you’ll have to make a program of student. This program has 4 menus (Get info,

Change name, Change GPA, and Exit). Validate each input must between 1 and 4.

Page 158: Diktat Java Console

152 | P a g e

If the user’s input is 1:

If the user’s input is 2:

If the user’s input is 3:

a. Task 1: Defining a class named Student:

First, we will make a class named Student with attribute id, name and gpa, and method to

print the student info. This class is used to store data about Student and accessed in our

Main class.

Page 159: Diktat Java Console

153 | P a g e

b. Task 2: Make the Main Class

The Main class is where we put our code to create the program. We will make the main

method and the constructor where we put our program in the Main class, and also import

java.util.Scanner to use the Scanner class.

c. Task 3: Make a object from Student class and Scanner class.

We will make an object from Student class that we make before, and because we need

user to give input to our program we need the Scanner class in our program.

Page 160: Diktat Java Console

154 | P a g e

d. Task 4: Make viewMenu Method

This method will be used to print the menu from our program

e. Task 5: Make changeName Method

changeName method will ask the user to input a new full name, with input validation the

full name that user inputted must be between 3 and 20 characters long.

f. Task 6: Make changeGPA Method

changeGPA method will ask the user to input a new GPA, with input validation the GAP

that user inputted must be between 0 and 4 in double format.

Page 161: Diktat Java Console

155 | P a g e

g. Task 7: Complete the main method

Here we will complete the main method that we create above with the method we create

like changeName and changeGPA method.

Page 162: Diktat Java Console

156 | P a g e

Chapter 14

Encapsulation

Page 163: Diktat Java Console

157 | P a g e

Encapsulation Concept Definition

Encapsulation is one of the fundamental of OOP concepts. Encapsulation is the technique of

making the fields in a class private and providing access to the fields via public methods. If a

field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the

fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being

randomly accessed by other code defined outside the class. Access to the data and code is tightly

controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without

breaking the code of others who use our code. With this feature Encapsulation gives

maintainability, flexibility and extensibility to our code.

Access Modifier

The access to classes, constructors, methods, and fields are regulated using access modifiers.

For example, a class can control what information or data can be accessible by other classes. To

take advantage of encapsulation, you should minimize access whenever possible.

Page 164: Diktat Java Console

158 | P a g e

Java provides a number of access modifiers to help you set the level of access you want for

classes as well as the fields, methods, and constructors in your classes. A member has package or

default accessibility when no accessibility modifier is specified.

Access Modifiers Same Class Same Package Subclass Other

Packages

Public √ √ √ √

Protected √ √ √ ×

No access modifier √ √ × ×

Private √ × × ×

public access modifier

Fields, methods and constructors declared public (least restrictive) within a public class are

visible to any class in the Java program, whether these classes are in the same package or in

another package.

private acess modifier

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It

also cannot be used for fields and methods within an interface. Fields, methods or constructors

declared private are strictly controlled, which means they cannot be accesses by anywhere

outside the enclosing class. A standard design strategy is to make all fields private and provide

public getter methods for them.

protected access modifier

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be

used for fields and methods within an interface. Fields, methods and constructors declared

protected in a superclass can be accessed only by subclasses in other packages. Classes in the

same package can also access protected fields, methods and constructors as well, even if they are

not a subclass of the protected member’s class.

Page 165: Diktat Java Console

159 | P a g e

no access modifier

Java provides a default specifier which is used when no access modifier is present. Any

class, field, method or constructor that has no declared access modifier is accessible only by

classes in the same package. The default modifier is not used for fields and methods within an

interface.

Let us look at an example code below:

This is how we call its method:

Static Variables

The static keyword is used to create variables that will exist independently of any instances

created for the class. Only one copy of the static variable exists regardless of the number of

Page 166: Diktat Java Console

160 | P a g e

instances of the class. Static variables are also known as class variables. Local variables cannot

be declared static.

Static methods

The static keyword is used to create methods that will exist independently of any instances

created for the class. Static methods do not use any instance variables of any object of the class

they are defined in. Static methods take all the data from parameters and compute something

from those parameters, with no reference to variables.

Class variables and methods can be accessed using the class name followed by a dot and the

name of the variable or method.

Let us look at an example code below:

Page 167: Diktat Java Console

161 | P a g e

Setter Getter

Setter and getter are one of many ways in assigning a value to the fields. Here is the way you

create setter and getter in eclipse IDE:

Right click in the editor, choose Source, and choose Generate Getters and Setters

On the Genereate Getters and Setters Dialog, select the fields you want to generate getters and

setters.

Page 168: Diktat Java Console

162 | P a g e

Click OK when you finished configuring. The result is shown below:

Page 169: Diktat Java Console

163 | P a g e

Exercise

Battle of Padawans - Ep. 1

Blues company is a company enganged in game programming. Once, they want to make a game

named “Battle of Padawans – Ep. 1”. You, as programmer, were asked by the company manager

to make this game using eclipse IDE. Here are the descriptions of the game:

First, program will ask for hero name.

Hero has some status: name, rank, body, mind, and stamina.

The main menu consist of 4 menus:

o Show status

o Train

o Rest

o Quit game

If the user choose “Show status”, then

o Print the name, rank, body, mind, and stamina of the hero.

If the user choose “Train”, then

o Show the “Jedi Training” menus:

Learn lightsaber (body)

Learn force (mind)

Done training

o If the user choose “Learn lightsaber (body)”, then

Lightsaber skill +2

Force power -1

Stamina -1

o If the user choose “Learn force (mind)”, then

Force power +2

Lightsaber skill -1

Stamina -1

o If the user choose “Done training”, then back to main menu

If the user choose “Rest”, then

o The stamina is recovered back to 5.

Page 170: Diktat Java Console

164 | P a g e

If the user choose “Quit game”, then end the program.

How to code:

a. Task 01 – Create Eclipse Java Project

Run Eclipse

Create a java project by selecting menu File -> New -> Project

On the “New Project” dialog, choose “Java Project”

Enter a project name, for example “Exercise 11”

Click Finish

Make a new Class by right clicking on the project folder, choose New -> Class

Enter a class Name, for example “Main”

Finish

b. Task 02 – Initialization

Make a New Class for the hero (Padawan.java)

Field Data Type Modifier Setter/Getter

Name String Private Yes

Rank String Private Yes

Body Integer Private Yes

Mind Integer Private Yes

Stamina Integer Private Yes

Page 171: Diktat Java Console

165 | P a g e

The purpose of using setter getter is you will have to call the set method to assign value

to a field, or call the get method to get the value from a field.

This means of information hiding. We cannot directly assign value into the field, but

calling the set/get method.

For example, getName() is a method to get the name’s value. setName() is a method to

assign value to name.

Make the main class (Main.java)

Page 172: Diktat Java Console

166 | P a g e

Create the clear function

Create the input name statement in the constructor

Create the menu method

Page 173: Diktat Java Console

167 | P a g e

c. Task 03 – Analyze Problems

Create “Show Status” method in Main.java

Page 174: Diktat Java Console

168 | P a g e

Create “Train” method in Main.java

o First, we need to make the menu and its validation

o Second, we create the learn lightsaber method

Page 175: Diktat Java Console

169 | P a g e

o Then we create the learn force method

Last, we create the “Rest” method in Main.java

And the whole code would be like this:

Main.java

Page 176: Diktat Java Console

170 | P a g e

Page 177: Diktat Java Console

171 | P a g e

Page 178: Diktat Java Console

172 | P a g e

Page 179: Diktat Java Console

173 | P a g e

Padawan.java

Page 180: Diktat Java Console

174 | P a g e

Chapter 15

Inheritance

Page 181: Diktat Java Console

175 | P a g e

Inheritance concept definition

Different kinds of objects often have a certain amount in common with each other.

Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of

bicycles (current speed, current pedal cadence, and current gear). Yet each also defines

additional features that make them different: tandem bicycles have two seats and two sets of

handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain

ring, giving them a lower gear ratio.

Inheritance is the mechanism through which we can derive classes from other classes. To

derive a class in java the keyword extends is used. Java does not support multiple

inheritances.

Benefits of inheritance is to minimise the amount of duplicate code in an application by

putting common code in a superclass and sharing amongst several subclasses.

Superclass

A java superclass is a class which gives a method or methods to a Java subclass, or we

can say it as parent class. For example, superclass of mountain bike is bike.

Page 182: Diktat Java Console

176 | P a g e

Subclass

A java subclass is a class which inherits a method or methods from a java superclass. For

example, mountain bike is subclass of bike which inherits its superclass method (change

gear, applying brakes, etc).

The result is as shown below:

Page 183: Diktat Java Console

177 | P a g e

As we can see, the first output is “Constructor of Superclass is called”. The Superclass’

constructor must be called first before Subclass’ object can be made. For example, mountain

bike will not exist unless bike is created.

Keyword super

The super keyword is used to access the member (field / method / constructor) of the

super class.

Final class

Page 184: Diktat Java Console

178 | P a g e

A final class cannot be extended. This is done for reasons of security and efficiency.

Many of the java standard library classes are final, for example java.lang.System and

java.lang.String. All methods in a final class are implicitly final.

Page 185: Diktat Java Console

179 | P a g e

Exercise

Battle of Knights – Ep. 2

Blues company is a known company as game producer. This company has been known

because of the first game released “Battle of Padawans – Ep. 1”. The company director has

assigned you, as the programmer, to make the second episode “Battle of Knights – Ep. 2”.

Here are the descriptions of the game:

The game has 2 forces, light and dark force

Hero has 4 attributes: name, saber, evade, and kill.

Each hero has the name, saber, evade, and kill attribute. But light hero has special

ability, is able to use force. And dark hero is able to throw the saber.

For light hero:

o Initial saber = 7, means attack success rate is 70%

o Initial evade = 8, means evade success rate is 80%

o Initial force = 9, means evade success rate is 90%

For dark hero:

o Initial saber = random from 7 – 9, means attack success rate is 70 – 90%

o Initial evade = random from 6 – 8, means evade success rate is 60 – 80%

o Initial throwsaber = 8, menas throw saber success rate is 80%

First, program will ask for hero name

Your hero will automatically join the light force

The game consist of 3 menus:

o Show status

o Battle

o Quit game

If the user choose “Show status”, then:

o Show name and total kills of the hero

If the user choose “Battle”, then:

o Print “An enemy has ambushed you!!”

o The hero has 3 actions: attack, force, and escape

o Your hero strikes first.

Page 186: Diktat Java Console

180 | P a g e

o If the user choose attack:

Attack success is according to the initial saber attack.

If your hero fail to attack, print “Your attack has missed”.

If your hero’s attack success, and enemy evade it, print “Enemy has evaded

your attack”.

If your attack success and enemy fail to evade, print “You have killed the

enemy” and end the battle.

o If the user use force:

Force success is according to the initial force attack.

If your hero fail to force, print “Your force has missed”.

If you’re her’s attack success and the enemy evade it, print “Enemy has

evaded your attack”.

If your attack success and enemy fail to evade, print “You have killed the

enemy” and end the battle.

o If the user use escape, then run from the battle, the hero gains nothing

o At the end of your turn, enemy will do a counter attack. Enemy has a chance 80%

of doing normal attack and 20% of doing saber attack.

If enemy attack fail, print “Enemy attack has missed”.

If enemy attack success and your hero evade it, print “You have evaded

enemy’s attack”

If enemy attack success and your hero fail to evade, print “You have been

killed! Game over”. And the program ends.

If the user choose “Quit game”, then end the program

How to code:

a. Task 01 – Create Eclipse Java Project

Run Elipse

Create a java project by selecting menu File -> New -> Project

On the “New Project” dialog, choose “Java Project”

Enter a project name, for example “Exercise 12”

Click Finish

Page 187: Diktat Java Console

181 | P a g e

Make a new Class by right clicking on the project folder, choose New -> Class

Enter a class name, for example “Main”

Finish

b. Task 02 – Create a superclass

First, we need to create a general hero class, for example Padawan.java

This padawan is the superclass of the Knight Class that we will make later. Every

Light Knight and Dark Knight have name, saber attack, evade rate, and kill ratio.

They can also do attack and get hit. So we need to put these fields and methods in

the Padawan class.

Field Data Type Modifier Setter/Getter

Name String Private Yes

Saber Integer Private Yes

Evade Integer Private Yes

Kill Integer Private Yes

Page 188: Diktat Java Console

182 | P a g e

Next we will fix the attack method, the attack rate is according to saber attack.

For example, if the saber attack is 7, means the attack success rate is 70%. So we

just need to make a random number from 0 to 10.

And so is the hit method:

Okay, the parent class is ready, next we will create the subclass

c. Task 03 – Create a subclass (Part 1)

Page 189: Diktat Java Console

183 | P a g e

There are two hero with different special attack, light hero can do force, on the

other hand, dark hero can throw saber, so we need to make 2 subclasses of

Padawan class.

In this part 1, we will create the Light hero class

Just create a new class, named LightKnight.java

LightKnight have a special attribute, that is force. And special attack, called force.

Force attack is almost the same as normal attack. It has success attack percentage.

d. Task 04 – Create a subclass (Part 2)

Create a new Class named DarkKnight.java

Dark hero can do throw saber attack.

Page 190: Diktat Java Console

184 | P a g e

e. Task 05 – Create the main class

Create the main method

Create the clear screen method

Create the main menu

Page 191: Diktat Java Console

185 | P a g e

Create show status method

Create battle method

Page 192: Diktat Java Console

186 | P a g e

Next, we will code the hero’s move. It starts with user’s input (attack, force, or

escape)

Next step, the hero will attack according to our moves (attack / force / escape)

Page 193: Diktat Java Console

187 | P a g e

Status is just a flag, to indicate whether hero attack success / fail

Last step is attacking to the enemy

Enemy has 80% chance to do normal attack and 20% chance to do special attack.

To make this code, we need to create a new method, for example, enemyAttack()

This is the enemy code:

Page 194: Diktat Java Console

188 | P a g e

f. Here’s the complete code:

Padawan.java

Page 195: Diktat Java Console

189 | P a g e

LightKnight.java

Page 196: Diktat Java Console

190 | P a g e

DarkKnight.java

Page 197: Diktat Java Console

191 | P a g e

Main.java

Page 198: Diktat Java Console

192 | P a g e

Page 199: Diktat Java Console

193 | P a g e

Page 200: Diktat Java Console

194 | P a g e

Page 201: Diktat Java Console

195 | P a g e

Page 202: Diktat Java Console

196 | P a g e

Chapter 16

Polymorphism

Page 203: Diktat Java Console

197 | P a g e

Polymorphism Concept Definition

Polymorphism is the ability of an object to take on many forms. The most common use of

polymorphism in OOP occurs when a parent class reference is used to refer to a child class

object.Any java object that can pass more than on IS-A test is considered to be polymorphic.

In java, all java objects are polymorphic since any object will pass the IS-A test for their own

type and for the class Object.

It is important to know that the only possible way to access an object is through a

reference variable. A reference variable can be of only one type.Once declared the type of a

reference variable cannot be changed.The reference variable can be reassigned to other

objects provided that it is not declared final. The type of the reference variable would

determine the methods that it can invoke on the object.

Overloading

Method overloading allows us to have same method name in a class or a subclass,

however, the class / subclass method (overloaded method) should change the argument

compulsarily. This brings us to the conclusion that overloaded methods may all be defined in

the same class, or they may be defined in different classes as long as those different classes

share a superclass.

Overriding

Overriding means creating a new set of method statements for the same method signature

(name, number of parameters and parameter types). The benefit of overriding is: ability to

define a behavior that’s specific to the sub class type. Which means a subclass can implement

a parent class method based on its requirement.

Page 204: Diktat Java Console

198 | P a g e

This would produce the following result:

Casting Object

In casting object, one object reference can be type cast into another object reference. The

cast can be to its own class type or to one of its subclass or superclass types or interfaces. The

casting of object references depends on the relationship of the classes involved in the same

hierarchy. Any object reference can be assigned to a reference.

There are 2 types of casting object: upcasting and downcasting. When we cast a reference

along the class hierarchy in a direction from the root class towards the children or subclasses,

it is a downcast.When we cast a reference along the class hierarchy in a direction from the

sub classes towards the root, it is an upcast.

Page 205: Diktat Java Console

199 | P a g e

Exercise

The Jedi Returns – Ep. 3

Blues company is a known company as a game producer. The company wants to make a

greater game than its anchestor, “Battle of Knights – Ep. 2”. You, as a programmer, is asked

to make this game with title “The Jedi Returns – Ep. 3”. According to the director’s plan, this

game will be the last Starwars game. Here are the descriptions of the game:

Player has 5 lives

Hero can promote himself into higher level, for example, from Knight rank into

Master rank.

Knight rank is only able to attack. Knight initial state is as describe below:

o Initial saber = 7

o Initial evade = 6

o Rank = “knight”

Master rank can either attack or use force. Force attack will not kill the enemy, but

weaken the attack power by 3 for 3 turns. Master is divided into 2 side, the light side

and the dark side.

o For light side:

Rank = “master”

Initial saber = 8

Initial evade = 7

Initial force = 9

o For dark side:

Rank = “master”

Initial saber = 9

Initial evade = 7

Initial force = 8

First, program will asked for hero’s name

The game consist of 4 menus:

o Show status

o Battle

o Choose side (only available for Knight rank and total kills > 5)

Page 206: Diktat Java Console

200 | P a g e

o Quit game

If the user choose “Show status”, then:

o Show the hero’s name, lives, and total kill

If the user choose “Battle”, then:

o If the hero’s rank is Knight, the enemy would be Knight.

o If the hero’s rank is Master, the enemy would be Master also.

o Attack success is according to initial saber attack

If the use choose “Choose side”, then:

o Hero must choose his side, light or dark side.

o If the hero choose light side, promote him into Master (light)

o If the hero choose dark side, promot him into Master (dark)

If the user choose “Quit game”, thenend the program.

How to code:

g. Task 01 – Create Eclipse Java Project

Run Elipse

Create a java project by selecting menu File -> New -> Project

On the “New Project” dialog, choose “Java Project”

Enter a project name, for example “Exercise 13”

Click Finish

Make a new Class by right clicking on the project folder, choose New -> Class

Enter a class name, for example “Main”

Finish

h. Task 02 – Create a superclass

First, we just need to create a general class, for example Knight.java

This “Knight.java” class will be superclass of the Master Class we will create

later. Both Knight and Master have their names, total kills, lives, saber attack,

evade rate, and rank. They can also do attack, get hit, and die.

Field Data Type Modifier Setter / Getter

Name String Private Yes

Page 207: Diktat Java Console

201 | P a g e

Kill Integer Private Yes

Lives Integer Private Yes

Saber Integer Private Yes

iSaber Integer Private Yes

Evade Integer Private Yes

Rank String Private Yes

Page 208: Diktat Java Console

202 | P a g e

Now we will fix the attack method, the attack rate is according to saber attack.

For example, if the saber attack is 7, means the attack success rate is 70%. So we

just need to make a random number from 0 to 10.

And so is the hit method

And the die method

Page 209: Diktat Java Console

203 | P a g e

Okay, the parent class is ready, next we will create the subclass

i. Task 03 – Create a subclass

As we can see, Master is derived from Knight class, so we just need to create

Master Class. Master has some new attributes: side, force, and counter (for force

side effect). Master can do force attack.

Page 210: Diktat Java Console

204 | P a g e

Beside do force attack method, Master can also receive force attack that will

weaken his attack. So we need to create “normalize” method to normalize the

force effect.

j. Task 04 – Create the main class

Create the main method

Page 211: Diktat Java Console

205 | P a g e

Create the clear screen method

Page 212: Diktat Java Console

206 | P a g e

Create the main menu

Create show status method

Page 213: Diktat Java Console

207 | P a g e

Create battle method

Page 214: Diktat Java Console

208 | P a g e

Both Knight and master has different battle option, knight has 2 options, while

master has 3 options. So, we need to check for the hero’s rank first

Page 215: Diktat Java Console

209 | P a g e

Next step, the hero will attack according to our moves (attack / force / escape)

Status is just a flag, to indicate whether hero attack success / fail

Last step is attacking to the enemy

Enemy has 80% chance to do normal attack and 20% chance to do special attack.

To make this code, we need to create a new method, for example, enemyAttack()

Page 216: Diktat Java Console

210 | P a g e

Enemy with knight rank can only do normal attack, but enemy with master rank

can do both normal attack and force attack. So we need to clarify the rank first

This is the enemy attack code

Page 217: Diktat Java Console

211 | P a g e

Page 218: Diktat Java Console

212 | P a g e

k. Here’s the complete code:

Knight.java

Page 219: Diktat Java Console

213 | P a g e

Page 220: Diktat Java Console

214 | P a g e

Master.java

Page 221: Diktat Java Console

215 | P a g e

Main.java

Page 222: Diktat Java Console

216 | P a g e

Page 223: Diktat Java Console

217 | P a g e

Page 224: Diktat Java Console

218 | P a g e

Page 225: Diktat Java Console

219 | P a g e

Page 226: Diktat Java Console

220 | P a g e

Page 227: Diktat Java Console

221 | P a g e

Page 228: Diktat Java Console

222 | P a g e

Chapter 17

Abstract and Interface

Page 229: Diktat Java Console

223 | P a g e

Abstract Class and Method

An abstract class is a class that is declared abstract – it may or may not include abstract

methods. Abstract classes cannot be instantiated, but they can be subclassed. If a class is

abstract and cannot be instantiated, the class does not have much use unless it is subclassed.

This is typically how abstract classes come about during the design phase. A parent class

contains the common functionality of a collection of child classes, but the parent class itself

is too abstract to be used on its own.

An abstract method is a method that is declared without an implementation (without

braces, and followed by a semicolon). Declaring a method as abstract has two results: first,

the class must also be declared abstract. If a class contains an abstract method, the class must

be abstract as well. Second, any child class (sub class) must either override the abstract

method or declare itself abstract.

An abstract class can contain fields that are not static and final, and they can contain

implemented methods.

Interface

An interface is a collection of abstract methods. A class implements an interface, thereby

inheriting the abstract methods of the interface. An interface is not a class. Writing an

interface is similar to writing a class, but they are two different concepts. A class describes

the attributes and behaviors of an object. An interface contains behaviors that a class

Page 230: Diktat Java Console

224 | P a g e

implements. Unless the class that implements the interface is abstract, all the methods of the

interface need to be defined in the class.

An interface is similar to a class in the followin ways:

An interface can contain any number of methods

An interface is written in a file with a .java extension, with the name of the interface

matching the name of the file

The bytecode of an interface appears in a .class file

Interfaces appear in packages, and their corresponding bytecode file must be in a

directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

An interface cannot be instantiated

An interface does not contain any constructors

All of the methods in an interface are abstract

An interface cannot contain instance fields. The only fields that can appear in an

interface must be declared both static and final.

An interface is not extended by a class, it is implemented by a class

An interface can extend multiple interfaces

A class can implement multiple interfaces

Page 231: Diktat Java Console

225 | P a g e

Exercise

Geome-Try

Math Corp is a corporation engaged in education. This corporation want to make a

simulation about geometry such as Rectangle, Square, and Triangle to elementary students all

over the world. You, as the programmer, is asked to make this program using eclipse IDE.

Here are the descriptions of the program.

Program has 4 menus:

o Rectangle

o Square

o Triangle

o Exit

If the user choose “Rectangle”, then

o Ask user’s input for width and height of the rectangle.

o Vaildate that the input is number and between 1 and 10

o Draw the rectangle

o Get the description of the rectangle (width, height)

o Calculate the area

If the user choose “Square”, then

o Ask user’s input for side of the square.

o Vaildate that the input is number and between 1 and 10

o Draw the square

o Get the description of the square (side)

o Calculate the area

If the user choose “Triangle”, then

o Ask user’s input for height and base of the square.

o Vaildate that the input is number and between 1 and 10

o Draw the triangle

o Get the description of the square (height, base)

o Calculate the area

Page 232: Diktat Java Console

226 | P a g e

Draw the rectangle and get the description above the main menu after the user has chosen

a menu.

How to code:

a. Task 01 – Create Eclispe Java Project

Run Elipse

Create a java project by selecting menu File -> New -> Project

On the “New Project” dialog, choose “Java Project”

Enter a project name, for example “Exercise 14”

Click Finish

Make a new Class by right clicking on the project folder, choose New -> Class

Enter a class name, for example “Main”

Finish

b. Task 02 – Create an abstract class

As we can see, rectangle, square, and triangle is a shape. A shape has its area and it

has a shape to draw.

Create an abstract class, for example, “Shape.java” which has 2 abstract methods:

getArea() and draw()

getArea() and draw() are an abstract method that must be overridden in Shape class’

subclasses.

c. Task 03 – Create Rectangle class

A rectangle has both width and height. Once a rectangle is made, it has its width and

height.

Page 233: Diktat Java Console

227 | P a g e

The image above is the illustration of coding the rectangle

Page 234: Diktat Java Console

228 | P a g e

The getArea() method is a method that will return the result of width multiplied by

height.

d. Task 04 – Create Square class

Square is almost the same as rectangle, but has the same width and height. So, we just

assume it has side.

Page 235: Diktat Java Console

229 | P a g e

The getArea() method is a method that will return the result of side quadrate.

e. Task 05 – Create Triangle class

Triangle only has its height and base.

Page 236: Diktat Java Console

230 | P a g e

The getArea() method is a method that will return the result of half the base time the

height.

f. Task 06 – Create the main class

Create the main method

Create the clear screen method

Create the main menu

Page 237: Diktat Java Console

231 | P a g e

Create the rect() method

Page 238: Diktat Java Console

232 | P a g e

Create the square() method

Page 239: Diktat Java Console

233 | P a g e

Create the triangle() method

g. Here is the complete code:

Shape.java

Page 240: Diktat Java Console

234 | P a g e

Rectangle.java

Page 241: Diktat Java Console

235 | P a g e

Square.java

Page 242: Diktat Java Console

236 | P a g e

Triangle.java

Main.java

Page 243: Diktat Java Console

237 | P a g e

Page 244: Diktat Java Console

238 | P a g e

Page 245: Diktat Java Console

239 | P a g e

Page 246: Diktat Java Console

240 | P a g e

Chapter 18

Package

Page 247: Diktat Java Console

241 | P a g e

A java package is a set of classes which are grouped together. This grouping helps to

organize Java classes and codevent multiple Java classes with the same name.

Creating and Naming Package

This is how to make and name a package:

right click on the src folder, then choose new -> package

On the “new Java Package” dialog, type the package name:

Press Finish.

Page 248: Diktat Java Console

242 | P a g e

After pressing finish, you will see in the project explorer the new package you have just

made.

Next, you can create/import existing class into this package.

Using Package

To use a package in your Java source code, you must either import the package or use the

fully qualified class name each time you use a class. In this example,there are 2 packages, each

package contains 1 class:

From Main.java, we want to create an instance of DemoClass. This shows you how to do it:

Page 249: Diktat Java Console

243 | P a g e

Let’s take a look at the code above. The first line is “package mainProgram;”, this means the

Main class is inside the mainProgram package. The next statement is “import

myClass.DemoClass;”, this means we want to import DemoClass class from myClass package.

Beside this way, you can use “import myClass.*;”, where * means import all public classes from

myClass package.

There are 2 ways in using packages:

The first way, you have to import the class’ package, so that you can use that class to

create instances.

The second way, you have to use the [package name].[class name] to create instances.

For example: “myClass.DemoClass demo2 = new myClass.DemoClass(“Demo 2”);”

Exercise

Zooooo

Zooooo kindergarden is planning on making a program about animal. They want to brief

to the children about animals. The program is to give some descriptions about the animal

they choose. You, as the programmer, is asked to make this program using eclipse IDE. Here

are the descriptions of the program:

Program consists of 3 menus:

o Visit aves family

o Visit reptile family

Page 250: Diktat Java Console

244 | P a g e

o Go home

If the user choose “Visit aves family”, then:

o Show another 3 menus:

Eagle

Owl

Exit

o If the user choose “Eagle”, then

Show the descriptions of Eagle

“Eagles are members of the bird family Accipitridae, and belong to several genera

which are not necessarily closely related to each other. Most of the more than 60

species occur in Eurasia and Africa.”

Print the sound of eagle

Eagle is chirping

Twit.. twit.. twit..

o If the user choose “Owl”, then

Show the descriptions of Owl

Owls belong to the order Strigiformes, constituting 200 extant bird of prey

species.

Most are solitary and nocturnal, with some exceptions (e.g. the Northern Hawk

Owl).

Owls hunt mostly small mammals, insects, and other birds, although a few species

specialize in hunting fish.

Print the sound of owl

Owl is hooting

Whoo... whoo... whoo...

o If the user choose “Exit”, then back to main menu

If the user choose “Visit reptile family”, then:

o Show another 3 menus:

Snake

Crocodile

Page 251: Diktat Java Console

245 | P a g e

Exit

o If the user choose “Snake”, then

Show the descriptions of Snake

Snakes are elongate, legless, carnivorous reptiles of the suborder Serpentes that

can be distinguished from legless lizards by their lack of eyelids and external ears.

Many species of snakes have skulls with many more joints than their lizard

ancestors, enabling them to swallow prey much larger than their heads with their

highly mobile jaws.

Print the sound of Snake

Snake is hissing

hisss........

o If the user choose “Crocodile”, then

Show the descriptions of Crocodile

A crocodile is any species belonging to the family Crocodylidae (sometimes

classified instead as the subfamily Crocodylinae).

The term can also be used more loosely to include all extant members of the order

Crocodilia

Print the sound of eagle

Crocodile is silent

...........

If the user choose “Go home”, then end the program.

How to code:

a. Task 01 – Create Eclipse Java Project

Run Elipse

Create a java project by selecting menu File -> New -> Project

On the “New Project” dialog, choose “Java Project”

Enter a project name, for example “Exercise 15”

Click Finish

Make a new Class by right clicking on the project folder, choose New -> Class

Enter a class name, for example “Main”

Page 252: Diktat Java Console

246 | P a g e

Finish

b. Task 02 – Create aves and reptile package

Eagle and Owl is 1 type, so we just need to make a package of it, for example, “aves”

package.

Right click on the project, choose New -> Package, give package name: aves

Finish

Next, we will create the reptile package

So, the result would be like this:

Page 253: Diktat Java Console

247 | P a g e

c. Task 03 – Create Eagle and Owl class

We will create 2 classes in the aves package

First, create a new Class, named Eagle

You will nothice that additional “package aves” is added in top of your code. This

means Eagle class is inside the aves package.

Next, we will code its behavior, such as speak and description.

Page 254: Diktat Java Console

248 | P a g e

And so is the Owl class

d. Task 04 – Create Snake and Crocodile class

We will create 2 classes in the reptile package, the Snake and Crocodile class

Snake class

Crocodile class

Page 255: Diktat Java Console

249 | P a g e

e. Task 05 – Create the main class

Create the main method

Create the clear screen method

Create the main menu

Page 256: Diktat Java Console

250 | P a g e

Create the aves method

Page 257: Diktat Java Console

251 | P a g e

Create the reptile method

Page 258: Diktat Java Console

252 | P a g e

Page 259: Diktat Java Console

253 | P a g e

f. Here is the complete code:

aves

Eagle.java

Owl.java

Page 260: Diktat Java Console

254 | P a g e

reptile

Snake.java

Crocodile.java

Page 261: Diktat Java Console

255 | P a g e

Main.java

Page 262: Diktat Java Console

256 | P a g e

Page 263: Diktat Java Console

257 | P a g e

Page 264: Diktat Java Console

258 | P a g e

Page 265: Diktat Java Console

259 | P a g e

Chapter 19

Basic Class in Java

Page 266: Diktat Java Console

260 | P a g e

1. Wrapper Class

Each of Java's eight primitive data types has a class dedicated to it. These are known as

Wrapper Class, because they "wrap" the primitive data type into an object of that class. So,

there is an Integer class that holds an int variable, there is a Double class that holds a double

variable, and so on. The wrapper classes are part of the java.lang package, which is imported

by default into all Java programs.

The following two statements illustrate the difference between a primitive data type

and an object of a wrapper class:

We usually use wrapper class for convert string to number. If we have string “12”, we

can’t use mathematical operation for that string. If you want to do that we must convert that

string to a number first. For example we will convert that string to Integer.

Page 267: Diktat Java Console

261 | P a g e

After we convert the string “12” to Integer, we can use mathematical operation.

2. String Class

The String Class represents character strings. String is a collection of some characters

into an array (Array of Character). There are several ways that can be used to make a string.

For example, if we want to create “Hello World” string, we can use this code:

String also could be create from a collection of characters like this code:

The class String includes methods for examining individual characters of the sequence,

for comparing strings, for searching strings, for extracting substrings, and for creating a copy

of a string with all characters translated to uppercase or to lowercase. For example if we

want to know length of string “Hello World”, we can use this code:

The result from code above is 11, which means that the number of characters that exist

on the object “msg1” is 11.

There are many other methods that can be use for String Class. Below we can see some

methods that are often used:

Return

Type

Method Explanation

char charAt(int index) Returns the character at the specified

index.

int compareTo(String another

String)

Compares two strings lexicographically.

int compareToIgnoreCase(S Compares two strings lexicographically,

Page 268: Diktat Java Console

262 | P a g e

tring str) ignoring case differences.

String concat(String str) Concatenates the specified string to the

end of this string.

boolean equals(Object anObject) Tests if this string ends with the specified

suffix.

boolean equalsIgnoreCase(String

anotherString)

Compares this String to another String,

ignoring case considerations.

int length() Returns the length of this string.

String[] split(String regex) Splits this string around matches of the

given regular expression.

String substring(int beginIndex,

int endIndex)

Returns a new string that is a substring of

this string.

String toLowerCase() Converts all of the characters in this

String to lower case using the rules of the

default locale.

String toUpperCase() Converts all of the characters in this

String to upper case using the rules of the

default locale.

String trim() Returns a copy of the string, with leading

and trailing whitespace omitted.

3. Math Class

The Math Class contains methods for performing basic numeric operations such as the

elementary exponential, logarithm, square root, and trigonometric functions.

There are 2 constant number in Math Class, there are phi and E.

Page 269: Diktat Java Console

263 | P a g e

Here is the example of Math Method:

Trigonometric Method

Exponent Method

If we want to make 23 we can use this code:

If we want to make 25 we can use this code:

Rounding Method

Random Method

Page 270: Diktat Java Console

264 | P a g e

4. Exercise

For excercise we will make a simple program.

Program consists of 4 menus:

1. Input String

2. See String

3. Rounding Number

4. Exit

If user chooses Input String, then:

- Ask user to input a string. Validate that the length of the string must be between 5

and 20.

If user chooses See String, then:

- Validate if user never Input String (Menu 1), then show message “You must input a

string first”.

- If user already input the string then show:

String that user inputed.

Length of the string.

The string in Upper Case.

The string in Lowwer Case.

If user chooses Rounding Number, then:

- Ask user to input a number. Validate that the number must between 1.0 and 5.0 and

must be a number.

- Show:

Number that user Inputed.

Numer after ceil.

Numer after floor.

Numer after rint.

Numer after round.

If user chooses Exit, then:

- Program ends.

Page 271: Diktat Java Console

265 | P a g e

a. Task 01 - Create Project

1. Run Eclipse from Start Menu

2. Open Menu File -> New -> Java Project

3. Enter Project Name “Chap16”

4. Then Press Finish

5. Expand Project folder

6. Right click on src -> new -> class

7. Enter Class Name “Main”

8. Then Press Finish

b. Task 02 – Make a class named StringEdit

1. Right click on src -> new -> class

2. Enter Class Name “StringEdit”

3. Then Press Finish

4. Double Click at StringEdit.java

5. We will make a class named StringEdit for store string data with attribute str, a

constructor, setter and getter for str, and 3 method (strLength, strUP, strLOW). We

will use method strLength() for get the length of the str, strUP to make Upper Case str

and strLOW to make Lower Case str.

Page 272: Diktat Java Console

266 | P a g e

c. Task 03 – Make the Main class

1. Double Click at Main.java

Page 273: Diktat Java Console

267 | P a g e

2. Add a global Scanner for input and an global object from class String Edit

d. Task 04 – Make clear method in main class

We will make a method named “clear” for clear our screan.

e. Task 05 – Make menu1 method in main class

We will make a method named “menu1”. We will call it if user choose menu 1 (Input

String). We must validate the length of the string must be between 5 and 20.

Page 274: Diktat Java Console

268 | P a g e

f. Task 06 – Make menu2 method in main class

We will make a method named “menu2”. We will call it if user choose menu 2 (See

String).

1. First we will validate if user never input the string

sEdit.getStr() -> get the value of String

equals(“”) -> compare string that we get with string ””(empty).

2. Show the result

g. Task 07 – Make menu3 method in main class

We will make a method named “menu3”. We will call it if user choose menu 3

(Rounding Number).

1. First we will validate input must be number and between 1.0 – 5.0

Page 275: Diktat Java Console

269 | P a g e

2. Show the result

h. Task 08 – Make Menu validation in void main

In void main we will make menu validation and call the method that we have made.

1. Print menu option and looping menu

Page 276: Diktat Java Console

270 | P a g e

2. Input menu

3. Selection menu

Page 277: Diktat Java Console

271 | P a g e

Chapter 20

Data Structure in Java

Page 278: Diktat Java Console

272 | P a g e

Data structure is a collection of data that has been developed in a certain mode. Structure not

only store data, but also supports operations to access and manipulate data. In OOP, Data

Structure = Collection. Where an object that stores other objects, referred to as data or elements.

1. ArrayList

ArrayList are implemented with an underlying array, and when that array is full and an

additional element is added, a new, larger, array is allocated and the elements are copied

from the old to the new. Because it takes time to create a bigger array and copy the elements

from the old array to the new array, it is a slightly faster to create an ArrayList with a size

that it will commonly be when full. Of course, if you knew the final size, you could simply

use an array. However, for non-critical sections of code programmers typically don't specify

an initial size.

ArrayList has these characteristics:

An ArrayList automatically expands as data is added.

Access to any element of an ArrayList is O(1). Insertions and deletions are O(N).

An ArrayList has methods for inserting, deleting, and searching.

An ArrayList can be traversed using a foreach loop, iterators, or indexes.

The following functions are frequently used in the ArrayList class

add(element) adding element to the list

clear() delete all element in the list

clone() returns the copied object in the list

containts(element) searching element contains in the list

get(index) take a certain element at index in list

isEmpty() to check whether the list is empty or no

remove(index) to remove the designated element in the list

size() number of element in the list

set(index, element) fill an element in the list in accordance with the

designated position

Example of ArrayList:

Page 279: Diktat Java Console

273 | P a g e

2. Vector

Vectors are commonly used instead of arrays, because they expand automatically when

new data is added to them. The Java 2 Collections API introduced the similar ArrayList data

structure. ArrayLists are unsynchronized and therefore faster than Vectors, but less secure in

a multithreaded environment. The Vector class was changed in Java 2 to add the additional

methods supported by ArrayList.

The following functions are frequently used in the ArrayList class

addElement(element) adding element to the final sequence of

the vector

capacity() restore the capacity vector

clone() restore object coppied in that vector

containts(element) searching element in the vector

copyInto(element[]) copy element ke specific array

elementAt(index) take the element of the designated

Page 280: Diktat Java Console

274 | P a g e

index

insertElementAt(element , index) add an element to the designated index

isEmpty() check whether the vector is empty or

not

remove(index) remove the designated element in the

vector

size() number of elements in vector

set(index, element) fills a vector element in accordance

with the designated position

Example of Vector:

3. ArrayList VS Vector

Each method Vector given keyword “synchronized”, so that when executed in the

Thread, it will not happen Thread congestion.

In ArrayList every method not given keyword “synchronized”, so when executed in

Thread, this can resulted unsafe Thread, in other words collision of Thread can occur,

when Thread try to call ArrayList Method.

Page 281: Diktat Java Console

275 | P a g e

Time used by ArrayList is shorter as compared to Vector.

If we want to create dynamic array run using a Thread, use Vector. Whereas if

indeed the process that we do not need to use threads, then use the ArrayList to faster

processing of dynamic arrays.

4. Exercise

For excercise we will make a simple program.

First the program will show index of vector, name and age.

Program consists of 3 menus:

1. Add

2. Delete

3. Exit

If user chooses Add, then:

- Ask user to input name. Validate that the length of the name must be between 2 and

5 characters.

- Ask user to input age. Validate that the age must be between 10 and 100.

- Add name and age to vector.

If user chooses Delete, then:

- Validate if vector is empty, then show message “Vector empty!!!”.

- Else Ask user to input index of vector. Validate that the index must be between 0 and

maximum index of vector.

- Remove data from vector base on inputed index.

If user chooses Exit, then:

- Program ends.

i. Task 01 - Create Project

1. Run Eclipse from Start Menu

2. Open Menu File -> New -> Java Project

3. Enter Project Name “Chap17”

4. Then Press Finish

5. Expand Project folder

Page 282: Diktat Java Console

276 | P a g e

6. Right click on src -> new -> class

7. Enter Class Name “Main”

8. Then Press Finish

j. Task 02 – Make a class named Data

1. Right click on src -> new -> class

2. Enter Class Name “Data”

3. Then Press Finish

4. Double Click at Data.java

5. We will make a class named Data for store data with attribute name and age, a

constructor, setter and getter for both name and age.

Page 283: Diktat Java Console

277 | P a g e

k. Task 03 – Make the Main class

1. Double Click at Main.java

2. Add a global Scanner for input and an global vector that have Class Data as generic

type.

l. Task 04 – Make clear method in main class

We will make a method named “clear” for clear our screan.

m. Task 05 – Make view method in main class

We will make a method named “view”. We will use it for show index of vector, name

and age that obtained from vector we made.

Page 284: Diktat Java Console

278 | P a g e

1. Create view method

2. View index

This looping will increase the value of variable “i” start from 0 until the total data in

vector(size of vector) and it will print the value of “i”.

3. View name

This looping will increase the value of variable “i” start from 0 until the total data in

vector(size of vector) and it will print name base on index of vector. vec.get(i) -> get

data (Class Data) from Vector “vec” base on index “i”.

getName() -> method from Class data that return the value of attribute “name”.

4. View age

This looping will increase the value of variable “i” start from 0 until the total data in

vector(size of vector) and it will print age base on index of vector. vec.get(i) -> get

data (Class Data) from Vector “vec” base on index “i”.

Page 285: Diktat Java Console

279 | P a g e

getAge() -> method from Class Data that return the value of attribute “age”.

n. Task 06 – Make menu1 method in main class

We will make a method named “menu1”. We will call it if user choose menu 1 (Add).

1. Make menu1 method and make 2 temporary variable 1 String for name and 1 int for

age

2. Input name, validate legth of the name must between 2-5 characters

3. Input age, validate age must between 10-100

4. Add to vector

Page 286: Diktat Java Console

280 | P a g e

Add data to vector. Because the type of vector that we made is Class Data, then we

add new object to the Vector.

o. Task 07 – Make menu2 method in main class

We will make a method named “menu2”. We will call it if user choose menu 2 (Delete).

1. First validate if vector is empty

2. Input index, Validate that the index must be between 0 and maximum index of vector.

3. Remove, remove data from vector base on inputed index

Remove data from Vector base on index that user inputed.

p. Task 08 – Make Menu validation in void main

In void main we will make menu validation and call the method that we have made.

1. Print menu option and looping menu

Page 287: Diktat Java Console

281 | P a g e

2. Input menu

3. Selection menu

Page 288: Diktat Java Console

282 | P a g e

Chapter 21

File

Page 289: Diktat Java Console

283 | P a g e

1. File

In Java we can make a file to stored all data of programs that we make. Before we study

that data stored in variables, arrays and objects are temporary, when the program ends then it

will lose all that has been stored. If we make a file, we can save the data. Each file is placed

in a directory in the file system.

Example : c:\library\bookA.txt

File name : bookA.txt

Directory path : c:\library\

The files and directories are accessed and manipulated by the class java.io.File

Declaration:

If you want to make a file use method createNewFile();

Page 290: Diktat Java Console

284 | P a g e

If you want to make a directory use method mkdir();

The file will be made inside project directory.

The following functions in the class file

canRead() check whether the file can be read

canWrite() check whether the file can be written

exists() check if file exists

getName() restore a file name srting

getPath() return the form srting path of the file

getParent() return the parent directory of the current directory or

the files are placed

isFile() check whether the object is a file or not

isHidden() check whether the type is hidden or not

lastModified() display the last time of modification

length() displays the file size

renameTo(File dest) change the file name to the abstract path name, etc.,

can be seen again in Java help

Page 291: Diktat Java Console

285 | P a g e

Static variable

File.separator string with file separator

File.separatorCha char with file separator

File.pathSeparator string with file separator

File.pathSeparatorChar char with file separator

2. Write File

We will use class PrintWriter for write data in files of type text.

Declaration:

When constructor called it will create a file, if it is missing then the file will be created or

if the file exists then its contents will be discarded. Don’t forget to close the PrintWriter after

finish writing.

Boolean “true” in FileWriter means that you will add the text in the end of file, if you

change it to “false” it will overwrite the old text with the new one.

Page 292: Diktat Java Console

286 | P a g e

Handling used I/O exception.

Result:

The following functions are used

print(value) Write the value in the file can be a string, char, int, double.

long, float, boolean or array of characters.

println(value) Same as the print value by adding a new line int the end.

close() Close connection to the file stream

flush() Clear connection to the file stream

3. Read File

Scanner Class can also be used to read data from a file.

Declaration:

First you must make a file named “data.txt” in project folder. Fill the file with text. In this

example I will add text “The quick brown fox jump over the lazy dog”.

Page 293: Diktat Java Console

287 | P a g e

Result:

Handling used I/O exception.

Function in the Scanner

close() Closes this scanner.

hasNext() Returns true if this scanner has another token in its input.

next() Finds and returns the next complete token from this scanner.

nextLine() Advances this scanner past the current line and returns the input

that was skipped.

nextInt() Scans the next token of the input as an int.

nextFloat() Scans the next token of the input as a float.

nextLong() Scans the next token of the input as a long.

nextDouble() Scans the next token of the input as a double.

Page 294: Diktat Java Console

288 | P a g e

6. Exercise

For excercise we will make a simple program.

Program has 1 file named “data.txt” witch contains data”

“Browniz#dog”

“Lucy#cat”

“Prikitiw#bird”

First program will read data from file “data.txt” and store it to a vector;

Program consists of 2 menus:

1. Add new data

2. Exit and Save

If user chooses Add new data, then:

- Ask user to input name of pet. Validate that the length of the name must be

between 1 and 15.

- Ask user to input type of pet. Validate that the length of the type must be between

1 and 15.

- Add data to vector

If user chooses Exit and Save, then:

- Write data from vector to file “data.txt”.

- Program ends.

a. Task 01 - Create Project

1. Run Eclipse from Start Menu

2. Open Menu File -> New -> Java Project

3. Enter Project Name “Chap16”

4. Then Press Finish

5. Expand Project folder

6. Right click on src -> new -> class

7. Enter Class Name “Main”

8. Then Press Finish

Page 295: Diktat Java Console

289 | P a g e

b. Task 02 - Create File “data.txt”

1. Open Project folder

2. Add new txt file in the folder

3. Named it “data.txt”

4. Add the data.

c. Task 03 – Make a class named Pet

1. Right click on src -> new -> class

2. Enter Class Name “Pet”

3. Then Press Finish

4. Double Click at Pet.java

5. We will make a class named Pet for store pet data with attribute name and type,

getter for both name and type, and a Constructor.

Page 296: Diktat Java Console

290 | P a g e

d. Task 04 – Make the Main class

1. Double Click at Main.java

2. Add a global Scanner for input and an global vector that have Class Pet as generic

type.

Page 297: Diktat Java Console

291 | P a g e

e. Task 05 – Make clear method in main class

We will make a method named “clear” for clear our screan.

f. Task 06 – Make readFile method in main class

We will make a method named “readFile”. We will use it for read data from file

“data.txt” then stored it to vector.

1. First we will validate if “data.txt” never created.

Make a temporary array of string variable

First we define a file name “data.txt” with class File

We validate it with method exists().

If the return is false then “data.txt” is missing

If the return is true then “data.tst” exists

2. Read File

Page 298: Diktat Java Console

292 | P a g e

sn.hasNextLine() -> looping until there are no data that can be read.

sn.nextLine().split(“#”) -> split the string that read from file base on String “#” and

store it to array temp.

Example:

If the program read String “abc#def” then it will be split into String “abc” and

“def”. After that, the string will be stored to array temp.

temp[0] = “abc”

temp[1] = “def”

vec.add() -> Add data to vector. Because the type of vector that we made is Class

Pet, then we add new object to the Vector.

g. Task 07 – Make writeFile method in main class

We will make a method named “writeFile”. We will use it for write data from file

vector stored it to file “data.txt”.

This looping will increase the value of variable “i” start from 0 until the total data in

vector(size of vector) and it will print to file “data.txt” name and type base on index of

vector.

vec.get(i) -> get data (Class Pet) from Vector “vec” base on index “i”.

getName() -> method from Class Pet that return the value of attribute “name”.

getType() -> method from Class Pet that return the value of attribute “type”.

h. Task 08 – Make view method in main class

We will make a method named “view”. We will use it for show all data in vector.

Page 299: Diktat Java Console

293 | P a g e

This looping will increase the value of variable “i” start from 0 until the total data in

vector(size of vector) and it will print name and type base on index of vector.

vec.get(i) -> get data (Class Pet) from Vector “vec” base on index “i”.

getName() -> method from Class Pet that return the value of attribute “name”.

getType() -> method from Class Pet that return the value of attribute “type”.

i. Task 09 – Make menu1 method in main class

We will make a method named “menu1”. We will call it if user choose menu 1 (Add

new data). Make 2 temporary String variable.

1. Input name, Validate that the name must be between 1 and 15

2. Input type, Validate that the type must be between 1 and 15

Page 300: Diktat Java Console

294 | P a g e

3. Add to Vector

Add data to vector. Because the type of vector that we made is Class Pet, then we

add new object to the Vector.

j. Task 10 – Make Menu validation in main class

1. Read File

2. Menu Validation

3. Write File

Page 301: Diktat Java Console

295 | P a g e

Chapter 22

Thread

Page 302: Diktat Java Console

296 | P a g e

1. Theory

Thread: sequence of execution from beginning to end in a program, actually similar to the

process, but how to share resources among processes with threads that are very different. A

thread provides the mechanization of the executed command. A set of instructions executed

in parallel with the time-scale method (when one processor make the shift from one thread

to another thread).

Task: program units that execute independently from one part of the program.

Multiprocessing: the use of two or more CPU in a computer system.

Multitasking: a method to run more than one process where there is sharing of resources

such as CPU.

Multithreading: a way that allows execution of multiple threads going on in a process,

sharing of resources but can be run independently. Multiple thread can be executed in

parallel on a computer system. Multiple thread can make the program more responsive and

interactive and to improve program performance.

There are three models multithreading:

1. Many to One (Solaris Green Thread and GNU Portable Thread)

2. One to One (Windows NT/XP/2000 , Linux, Solaris 9 and above)

3. Many to Many (Windows NT/2000, Solaris prior versions of nine )

Page 303: Diktat Java Console

297 | P a g e

Advantage of multithreading is categorized into four sections:

Responsive

Sharing resources

Economical

Utilization of multiprocessor architectures

The following methods are methods in class Thread

start() Start a thread with the function running in the class. implementing

the Runnable interface and is run by the JVM.

isAlive() find out whether the thread running or not.

setPriority(p : int) thread priority set from 1 to 10.

join() wait for some thread to finish.

sleep(t : long) create a thread to sleep in the size of millisecond.

yeild() stop the thread while and allow another thread to the road.

interrupt() interrupts thread.

2. Exercise

For excercise we will make a simple thread.

We will make 2 process:

- Process 1 will show number from 1 to 10.

- Process 2 will show number from 1 to 10.

Give 1 second delay for each process

a. Task 01 - Create Project

1. Run Eclipse from Start Menu

2. Open Menu File -> New -> Java Project

3. Enter Project Name “Chap21”

4. Then Press Finish

5. Expand Project folder

6. Right click on src -> new -> class

7. Enter Class Name “Main”

8. Then Press Finish

Page 304: Diktat Java Console

298 | P a g e

b. Task 02 – Make a class named Tasks

1. Right click on src -> new -> class

2. Enter Class Name “Tasks”

3. Then Press Finish

4. Double Click at Tasks.java

5. We will use this class for 2nd

process. We will make a class Tasks that have Class

Runnable as interface. Don’t forget to add unimplemented methods.

Click on a the error mark and choose “add unimplemented methods”.

6. Print message for 2nd

process

This looping will increase the value of “i” from 1 to 10.

Page 305: Diktat Java Console

299 | P a g e

Thread.sleep(1000); -> use for make a delay, 1000 means 1000 milliseconds. It

must surond with try-catch.

c. Task 03 – Make the Main class

1. Double Click at Main.java

2. Make object from Class Tasks

3. Make object from Class Thread

Add object from Class Tasks (ts) in Thread Constructor. This means that the thread

will runs Method run in Tasks Class

4. Start the thread

5. Print message for 1st process

Page 306: Diktat Java Console

300 | P a g e

This looping will increase the value of “i” from 1 to 10.

Thread.sleep(1000); -> use for make a delay, 1000 means 1000 milliseconds. It must surond

with try-catch.

Result:

Process 1 will run together with Process 2.

Page 307: Diktat Java Console

301 | P a g e

Chapter 23

Generic

Page 308: Diktat Java Console

302 | P a g e

1. Generic

Generic Programming Facility was added to the Java programming language in 2004 as

part of J2SE 5.0. Generic allows types or functions to be operated in different types of data

objects at compile time. Defining a class or function with a generic type that can be replaced

with concrete data types by the compiler. Strings and Numbers is the kind of concrete data

to overwrite the generic data type.

Advantage of Generic Class

Allows compile time error detection when (compile) compared to the time of the

program (runtime).

A generic class or function allows us as programmers to create certain types of objects

or functions that will be created.

Example interface with generic type

Where <T> considered as formal generic type, which can in substitutes with type specific

later. Substitution of a generic type called a generic instantiation. Generic type must be a

reference for other types. It can not be replaced with primitive data types such as int, double

or char. Capital like the letter T and E is always used to refer to generic types. ArrayList,

iterator, LinkedList and Vector are examples of generic classes.

2. Wildcard

Type parameter with the form“?”.Providing the right kind of element of an object with an

unknown wildcard, placed restrictions on the type of function called in an object. List<?>

indicates that a list has an unknown object type.

Type of Wildcard:

Unbounded wildcard to form ? extends Object example:

<? Extends Number> is a wildcard type is a reference to the number.

Page 309: Diktat Java Console

303 | P a g e

Bounded wildcard to form ? extends T where the wildcard reference to the type T.

Lower bound wildcard to form ? super T where the reference to the type of super T.

Example:

<? extends Number> is a kind of wildcard that refers Number class or subtype Number

class. So we can call with:

max(new TesGenerik<Integer>());

max(new TesGenerik<Double>());

3. Exercise

For excercise we will make a simple Generic and Wildcard.

a. Task 01 - Create Project

1. Run Eclipse from Start Menu

2. Open Menu File -> New -> Java Project

3. Enter Project Name “Chap21”

4. Then Press Finish

5. Expand Project folder

6. Right click on src -> new -> class

7. Enter Class Name “Main”

8. Then Press Finish

b. Task 02 – Make a class named Tasks

1. Right click on src -> new -> class

2. Enter Class Name “Num”

3. Then Press Finish

4. Double Click at Tasks.java

Page 310: Diktat Java Console

304 | P a g e

5. In this class we will make Generic Class with a setter and a getter as Methods.

setNum() -> method for add value to obj

getNum() -> method for get value from obj

c. Task 03 – Make the Main class

1. Double Click at Main.java

2. Make object wildcard

Page 311: Diktat Java Console

305 | P a g e

Make a wildcard that extends Class Number, this object can only be replace with

Byte, Double, Float, Integer, Long, Short

3. Make object generic

Make object from class Num that have generic Integer and Double

4. Set Number

Add Number to object intNum = 100 and douNum = 10.7

5. Print Number

Inserted intNum value to num then print the value of num (result 100)

Inserted douNum value to num then print the value of num (result 10,7)