diktat java console
DESCRIPTION
Diktat BinusTRANSCRIPT
-
Java Programming (Console)
Hands on Lab
September 2011
For the latest information, please see bluejack.binus.ac.id
-
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.
-
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
-
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
-
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
-
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
-
1 | P a g e
Chapter 01
Introduction to Java Programming
-
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.
http://en.wikipedia.org/wiki/Software_applicationhttp://en.wikipedia.org/wiki/Software_applicationhttp://en.wikipedia.org/wiki/Software_applicationhttp://en.wikipedia.org/wiki/Computer_programmerhttp://en.wikipedia.org/wiki/Software_developmenthttp://en.wikipedia.org/wiki/Software_developmenthttp://en.wikipedia.org/wiki/Software_developmenthttp://en.wikipedia.org/wiki/Source_code_editorhttp://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Interpreter_%28computing%29http://en.wikipedia.org/wiki/Build_automationhttp://en.wikipedia.org/wiki/Debuggerhttp://en.wikipedia.org/wiki/Version_control_systemhttp://en.wikipedia.org/wiki/GUIhttp://en.wikipedia.org/wiki/Class_browserhttp://en.wikipedia.org/w/index.php?title=Object_inspector&action=edit&redlink=1http://en.wikipedia.org/w/index.php?title=Object_inspector&action=edit&redlink=1http://en.wikipedia.org/w/index.php?title=Object_inspector&action=edit&redlink=1http://en.wikipedia.org/wiki/Class_hierarchyhttp://en.wikipedia.org/wiki/Class_hierarchyhttp://en.wikipedia.org/wiki/Class_hierarchyhttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://www.jetbrains.com/idea/http://www.jcreator.com/http://en.wikipedia.org/wiki/Platform_%28computing%29http://en.wikipedia.org/wiki/Integrated_development_environmenthttp://en.wikipedia.org/wiki/Java_%28programming_language%29http://en.wikipedia.org/wiki/JavaScripthttp://en.wikipedia.org/wiki/PHPhttp://en.wikipedia.org/wiki/Python_%28programming_language%29http://en.wikipedia.org/wiki/Ruby_%28programming_language%29http://en.wikipedia.org/wiki/Groovy_%28programming_language%29http://en.wikipedia.org/wiki/C_%28programming_language%29http://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/Scala_%28programming_language%29http://en.wikipedia.org/wiki/Clojurehttp://en.wikipedia.org/wiki/Java_Virtual_Machinehttp://en.wikipedia.org/wiki/Java_Development_Kithttp://en.wikipedia.org/wiki/Software_componenthttp://en.wikipedia.org/wiki/Third_party_developerhttp://en.wikipedia.org/wiki/Software_development_environmenthttp://en.wikipedia.org/wiki/Integrated_development_environmenthttp://en.wikipedia.org/wiki/Plug-in_%28computing%29http://en.wikipedia.org/wiki/Java_%28programming_language%29http://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/Ada_%28programming_language%29http://en.wikipedia.org/wiki/C_%28programming_language%29http://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/COBOLhttp://en.wikipedia.org/wiki/Perlhttp://en.wikipedia.org/wiki/PHPhttp://en.wikipedia.org/wiki/Python_%28programming_language%29http://en.wikipedia.org/wiki/Ruby_%28programming_language%29http://en.wikipedia.org/wiki/Ruby_on_Railshttp://en.wikipedia.org/wiki/Scala_%28programming_language%29http://en.wikipedia.org/wiki/Clojurehttp://en.wikipedia.org/wiki/Scheme_%28programming_language%29
-
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
http://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/James_Goslinghttp://en.wikipedia.org/wiki/Sun_Microsystemshttp://en.wikipedia.org/wiki/Sun_Microsystemshttp://en.wikipedia.org/wiki/Sun_Microsystemshttp://en.wikipedia.org/wiki/Oracle_Corporationhttp://en.wikipedia.org/wiki/Java_%28software_platform%29http://en.wikipedia.org/wiki/Syntax_%28programming_languages%29http://en.wikipedia.org/wiki/C_%28programming_language%29http://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/Object_modelhttp://en.wikipedia.org/wiki/Low-level_programming_languagehttp://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Java_bytecodehttp://en.wikipedia.org/wiki/Class_%28file_format%29http://en.wikipedia.org/wiki/Java_Virtual_Machinehttp://en.wikipedia.org/wiki/Computer_architecturehttp://en.wikipedia.org/wiki/Reference_implementation_%28computing%29http://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Library_%28computing%29http://en.wikipedia.org/wiki/Java_Community_Processhttp://en.wikipedia.org/wiki/GNU_General_Public_Licensehttp://en.wikipedia.org/wiki/GNU_Compiler_for_Javahttp://en.wikipedia.org/wiki/GNU_Compiler_for_Javahttp://en.wikipedia.org/wiki/GNU_Compiler_for_Javahttp://en.wikipedia.org/wiki/GNU_Classpathhttp://en.wikipedia.org/wiki/Dalvik_%28software%29http://en.wikipedia.org/wiki/Java_bytecodehttp://en.wikipedia.org/wiki/Machine_codehttp://en.wikipedia.org/wiki/Interpreter_%28computing%29http://en.wikipedia.org/wiki/Virtual_machine
-
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.
http://en.wikipedia.org/wiki/End-userhttp://en.wikipedia.org/wiki/Java_Virtual_Machinehttp://en.wikipedia.org/wiki/Applethttp://en.wikipedia.org/wiki/Thread_%28computer_science%29http://en.wikipedia.org/wiki/Computer_network
-
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
http://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Java_%28programming_language%29http://en.wikipedia.org/wiki/Class_%28file_format%29http://en.wikipedia.org/wiki/Java_bytecodehttp://en.wikipedia.org/wiki/Machine_codehttp://en.wikipedia.org/wiki/Operating_systemhttp://en.wikipedia.org/wiki/Jikeshttp://en.wikipedia.org/wiki/Optimization_%28computer_science%29http://en.wikipedia.org/wiki/Run_time_%28computing%29http://en.wikipedia.org/wiki/JREhttp://en.wikipedia.org/wiki/Java_Virtual_Machinehttp://en.wikipedia.org/wiki/Java_Virtual_Machine
-
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
http://en.wikipedia.org/wiki/Interpreter_%28computing%29http://en.wikipedia.org/wiki/Bytecodehttp://en.wikipedia.org/wiki/Just-in-time_compilationhttp://en.wikipedia.org/wiki/Machine_codehttp://en.wikipedia.org/wiki/Dynamic_compilation
-
7 | P a g e
Creating a Java Application
After learning the theory about Java Language, lets 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".
http://en.wikipedia.org/wiki/Virtual_machinehttp://en.wikipedia.org/wiki/Scripting_language
-
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
http://java.sun.com/j2se/
-
9 | P a g e
ii. On the Eclipse Menu, Open File New Project
iii. On Project Window, choose Java Project and click Next
-
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
-
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
-
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 :
-
13 | P a g e
Chapter 02
Data Type and I/O
-
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
variables 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 dont.
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.
-
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.
-
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).
-
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 quietlyproducing 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.
-
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 valuesfor 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 thats 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 wont
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
-
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 :
http://en.wikipedia.org/wiki/Character_encodinghttp://en.wikipedia.org/wiki/Order_%28mathematics%29http://en.wikipedia.org/wiki/English_alphabethttp://en.wikipedia.org/wiki/Character_%28computing%29http://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Telecommunication
-
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 cant start with a digit.
Cant 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
-
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
-
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.
-
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:
-
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
-
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)
-
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.
-
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.
-
28 | P a g e
-
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.
Its 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
mk:@MSITStore:C:\Program%20Files\Java\JDK%206%20Documentation.chm::/j2se6/api/java/util/Scanner.html#nextInt()mk:@MSITStore:C:\Program%20Files\Java\JDK%206%20Documentation.chm::/j2se6/api/java/util/Scanner.html#nextFloat()mk:@MSITStore:C:\Program%20Files\Java\JDK%206%20Documentation.chm::/j2se6/api/java/util/Scanner.html#nextDouble()mk:@MSITStore:C:\Program%20Files\Java\JDK%206%20Documentation.chm::/j2se6/api/java/util/Scanner.html#nextByte()mk:@MSITStore:C:\Program%20Files\Java\JDK%206%20Documentation.chm::/j2se6/api/java/util/Scanner.html#nextLong()mk:@MSITStore:C:\Program%20Files\Java\JDK%206%20Documentation.chm::/j2se6/api/java/util/Scanner.html#nextShort()
-
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
-
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
-
32 | P a g e
c. Task 03 Receive input for any kind of data type
-
33 | P a g e
d. Task 04 Print variable using print format (Read Formatted Output in this
Chapter)
-
34 | P a g e
Chapter 03
Arithmetic Operation
-
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.
-
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
-
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 > 5
right-shift
-
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.
-
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
-
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.
-
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
-
42 | P a g e
Chapter 04
Selection Statement
-
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 students grade is greater than or equal to 60.Print Passed
determines if the condition students 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 symbolthe 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.
-
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 Javas 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 programmers 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
-
45 | P a g e
when the conditionis true rather than when the condition is false. For example, the
pseudocode statement
If students grade is greater than or equal to 60
Print Passed
else
Print Failed
printsPassedif the students grade is greater than or equal to 60 and prints Failedif
thestudents 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 programmersjob 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.
-
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 isnt a match in any of the cases and default
doesnt exist, the switch statement completes without doing anything.
-
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.
Heres 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,
youll 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.
-
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
-
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 students grade is greater than or equal to 90
Print A
else
If students grade is greater than or equal to 80
Print B
else
If students grade is greater than or equal to 70
Print C
else
If students 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 :
-
50 | P a g e
First input is students 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
-
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
-
52 | P a g e
Grade E : final score
-
53 | P a g e
Chapter 05
Iteration Statement, Jump Operator
-
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
-
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
algorithms 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
-
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.
-
57 | P a g e
Repetition with For
The forrepetition structure handles all of the details of counter-controlled
repetition. The forstructures 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 loops control variable and provides its initial
value,expression2is the loop-continuation condition (containing the control variables
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
-
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 structures 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
-
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
-
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
-
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.
-
62 | P a g e
Chapter 06
Exception Handling
-
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
}
-
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
blockscatch 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)
-
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.
-
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{
-
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