You are on page 1of 163

Chapter One

Fundamentals of Programming
Contents
 Introduction
 History of Java
 Java Technology
 Java Development Kit (JDK)
 JDK Editions
 JDK Versions
 Java Runtime Environment (JRE)
 Why Java?
 The five phases of Java
 Example Java Programs
 Compiling and running java programs
Programs
 Computer programs, known as software, are
instructions to the computer.

 We tell a computer what to do through programs.


 Without programs, a computer is an empty machine.
 Computers do not understand human languages, so we
need to use computer languages to communicate with
them.

 Programs are written using programming languages.


Programming Languages
Machine Language Assembly Language High-Level Language
 Machine language is a set of primitive instructions
built into every computer.

 The instructions are in the form of binary code, so


you have to enter binary codes for various
instructions.

 Program with native machine language is a tedious


process. Moreover the programs are highly difficult
to read and modify. For example, to add two numbers, you
might write an instruction in binary like this: 
1101101010011010
Programming Languages
Machine Language Assembly Language High-Level Language
Assembly languages were developed to make programming
easy. Since the computer cannot understand assembly
language, however, a program called assembler is used to
convert assembly language programs into machine code.

For example, to add two numbers, you might write an


instruction in assembly code like this:
ADDF3 R1, R2, R3
Assembly Source File
Machine Code File


ADDF3 R1, R2, R3
Assembler …
1101101010011010


Programming Languages
Machine Language Assembly Language High-Level Language

The high-level languages are English-like and easy to learn


and program. For example, the following is a high-level
language statement that computes the area of a circle with
radius 5:
area = 5 * 5 * 3.1415;
Popular High-Level Languages
COBOL (COmmon Business Oriented Language)
FORTRAN (FORmula TRANslation)
BASIC (Beginner All-purpose Symbolic Instructional Code)
Pascal (named for Blaise Pascal)
Ada (named for Ada Lovelace)
C (whose developer designed B first)
Visual Basic (Basic-like visual language developed by Microsoft)
Delphi (Pascal-like visual language developed by Borland)
C++ (an object-oriented language, based on C)
Java
History of Java

 Java
• Was created in 1991 and formally
announced in 1995 by James Gosling et al. of Sun
Microsystem.

• Initially called Oak, latter was changed to Java


because there was already a language called Oak.
History of Java…
 The original motivation for Java
• The need for platform independent language that could be
embedded in various consumer electronic products like
toasters and refrigerators.

 At about the same time, the World Wide Web


and the Internet were gaining popularity.
• Gosling et. al. realized that Java could be used for
Internet programming.
Java Technology
 Java technology is more than just a programming
language.

 As a programming language, Java can create all kinds of


applications that you could create using any
conventional programming language.

 Java technology applications are typically general-


purpose programs that run on any machine where the
Java runtime environment (JRE) is installed.
Java Technology

 Java Technology mainly consists two parts


 JDK
 JRE.
Java Development Kit (JDK)

 JDK is A free software development package


from Sun Microsystems that implements the
basic set of tools needed to write, test and
debug Java applications and applets.

 i.e. JDK is Java Software Development kit (SDK)


Java Development Kit (JDK)
 It is the toolkit for developers that includes the
Java compiler and the runtime environment.

 To write Java programs, you need the JDK


installed.

 The major component of JDK are


 Java compiler (.java file  .class file)
 Java launcher and jdb debugger
JDK Editions
 Java Standard Edition (J2SE)
 J2SE can be used to develop client-side standalone
applications or applets.

 Java Enterprise Edition (J2EE)


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

 Java Micro Edition (J2ME)


 J2ME can be used to develop applications for mobile
devices such as cell phones.
JDK Versions
 JDK 1.02 (1995)
 JDK 1.1 (1996)
 JDK 1.2 (1998)
 JDK 1.3 (2000)
 JDK 1.4 (2002)
 JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
 JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
 JDK 1.7 (late 2010) a. k. a. JDK 7 or Java 7
Java Runtime Environment (JRE)
 JRE is the program that emulates the JVM, so that
users can run Java programs.
 To run Java programs, you need download and install
the JRE.
 Runs code compiled for a JVM and performs class
loading (through the class loader), code verification
(through the bytecode verifier) and finally code
execution.
 The major component of JRE are
 Java platform core classes libraries
 Java virtual machine (JVM)
Why Java?
 The answer is that Java enables users to develop and
deploy applications on the

 Desktop computers…………..Standalone Application


 Internet for servers …………..Servlets, Applets
 Small hand-held devices ……. Mobile Application
Phases of a Java Program
 Java programs normally go through five phases –
edit, compile, load, verify and execute
Phase 1: Creating a program…
 Involves editing a file with an editor
 The following are some Java Integrated Development
Environments (IDEs).
 Jbuilder, NetBeans , Sun ONE Studio, Eclipse, jEdit,
Jcreator, BlueJ, jGRASP, etc.
 Most of this editors can be downloaded for free.

 Any text editor can also be used for creating Java


programs.

 Programs written on IDEs or any other editors are


known as Source Code.

 Java source code file names end with .java extension


Phase 2: Compiling Java Programs into Bytecodes
 Since a computer cannot understand a source program,
program called a compiler is used to translate the
source program into a machine language program
called an object program.

 With Java, you write the program once, and compile


the source program into a special type of object code,
known as bytecode.

 The bytecode can then run on any computer (platform)


with a Java Virtual Machine
Phase 2: Compiling Java Programs into Bytecodes...

 A virtual machine is a software


application that simulates a Java Bytecode

computer-JVM is one of the most Java Virtual


Machine
widely used virtual machine
Any
 Java Virtual Machine, which is part Computer

of JRE, is a software that interprets


Java bytecode.
 To compile Java Program
 Javac welcome.java
 To execute java programs
 Java welcome
Phase 3: Loading a program
 A program must be placed in memory before it can
execute : a process known as loading.

 The class loader takes the .class file (produced during


compilation process) containing the program’s
bytecodes and transform them to primary memory.

 The class loader also loads any of the .class files


provided by java that your program uses.

 The .class files can be loaded from a disk on your system


or over a network
Phase 4 : Bytecode Verification

 Involves examining bytecodes to ensure that they are


valid and do not violate Java’s security restriction.

 Java enforces strong security, to make sure that Java


programs arriving over the network do not damage
your files or your system (as computer viruses and
worms might)
Phase 5: Execution
 The JVM executes the program’s bytecodes, thus performing
the actions specified by the program.

 .class file is not final machine code yet. It is virtual machine


code. JVM need a second compilation to convert virtual
machine code to real machine code. We call it just-in-time
compiler (JIT).

 This greatly affects the speed of the execution.

 Traditionally, our C/C++ program can finish all the


compilation before execution. The generated machine code
could run directly on OS or hardware
A Simple Java Program
 The following code is a java program that prints the string “ Welcome
to Java”. Now lets make a line by line investigation of the program

1. /* Your first Java program; Welcome.java


2. The program prints a string Welcome to Java Programming
3. */
4. public class Welcome {
5. //main method begins execution of Java application
6. public static void main (String args[])
7. {
8. System.out.println(“Welcome to Java”);
9. }//end of main method
10. } //end of class Welcome
A Simple Java Program…
 Lines 1-3 & 5 comment lines
 There are two types of comments in Java
 End-of-line (Single line) comments
o A line that begins with //

 Traditional (Multiple line ) Comments


o A text that begins in /* ends in */
o All text between these delimiters is comment so it is
ignored by the compiler.
o These comment can be applied for a line, more than a
lines or part(s) of a line
A Simple Java Program…
 Javadoc comments

o A text that begins in /** and ends in*/

o As with traditional comments, all text between the


Javadoc comment delimiters is ignored by the compiler.

o Javadoc comments enable programmers to embed


program documentation directly in their programs.
A Simple Java Program…
 Line 4: public class Welcome {

 This line begins class declaration of the class Welcome.

 Every program in Java consists of at least one class


declaration .

 Generally, Java class decleration has the following


format:
[Access level Specifier] class class_name { … }
A Simple Java Program…
 The class is the essential Java construct. A class is a
template or blueprint for objects.

 To program in Java, you must understand classes and be


able to write and use them.

 The mystery of the class will continue to be unveiled


throughout this course. For now, though, understand that
a program is defined by using one or more classes.
A Simple Java Program…
 Access level Specifier
 Could be omitted (none), public, private, or
protected

 These are keywords that help to set the visibility and


accessibility of a class, its member variables, and
methods.

 They determine whether a field or method in a class,


can be used or invoked by another method in another
class or sub-class.
A Simple Java Program…
 class
 The class keyword introduces a class declaration in Java
and is immediately followed by the class name
(Welcome).

 class_Name
 Is the name of a class. A Java class name is an identifier.
 By convention class names should start with capital
letters
 Java is case Sensitive
A Simple Java Program…

 Line 6: public static void main(String args[])


 Is a method of which the starting point of every java
application.

 Every Java application must contain one main method.

 public is a keyword which specifies access level of the


method.

 The JVM executes the application by invoking the main


method
A Simple Java Program…

 static is another keyword [its meaning is to be


discussed latter]

 void is a return type that indicates that this method


performs a task but will not return any information
when it completes its task.

 String args[] … is an array of strings which is


an argument of the main function.
A Simple Java Program…
 Line 7: System.out.println( "Welcome
to Java Programming!" );

 This line prints the string contained in quotation.

 System.out is known as the standard output object.

 When System.out.println completes its task, it


positions the output cursor (the location where the
next character will be displayed) to the beginning of
the next line while System.out.print don’t.
A Simple Java Program…

 Every statement of java must end in semicolon (;)


so is line 7
 Lines 8 and 9
 This line depicts the end of the main method and
the class welcome.
Creating and Editing Using Notepad

To use Notepad, type


notepad Welcome.java
from the DOS prompt.

37
Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.

38
Compiling and Running Java programs
 Using Command line
 If you are using a text editor which is not specially
designed as Java IDE , java program are compiled and
run using command line.

 Before actually starting compiling and running java


source code, environmental variable path must be set
(How?)
 Set path to JDK bin directory
 set path=c:\Program Files\java\jdk1.6.0\bin
 Set classpath to include the current directory
 set classpath=.
Compiling and Running Java programs….
 Then open command line prompt

• To Compile
Javac […\]Welcome.Java
• To Run
Java […\]Welcome

 Compiling the source could will add a new file ,


Welcome.class to the folder containing the
source code
Creating, Compiling, and
Running Programs
Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code
}
}

Compile Source Code


Byte code (generated by the compiler for JVM i.e., javac Welcome.java
to read and interpret, not for you to understand)

Method Welcome() If compilation errors
0 aload_0 stored on the disk

Bytecode
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return Run Byteode
i.e., java Welcome

Result

If runtime errors or incorrect result 41


Displaying Text in a Message Dialog Box

 Display
 Most Java applications use windows or a dialog
box
 We have used command window
 Class JOptionPane allows us to use dialog
boxes
Displaying Text in a Message Dialog Box…
Packages
 Set of predefined classes for us to use
 Groups of related classes called packages
 Group of all packages known as Java class library or
Java applications programming interface (Java API).

 JOptionPane is one of the predefined classes in the


javax.swing package that has classes for using
Graphical User Interfaces (GUIs).
 We can use the showMessageDialog method in the
JOptionPane class to display message in Dialog box .
The showMessageDialog Method

JOptionPane.showMessageDialog(null,
"Welcome to Java!",
“Display Message",
JOptionPane.INFORMATION_MESSAGE);

44
Two Ways to Invoke the Method
 There are several ways to use the showMessageDialog
method. For the time being, all you need to know are two
ways to invoke it.
 One is to use a statement as shown in the example:
JOptionPane.showMessageDialog(null,
x,y,JOptionPane.INFORMATION_MESSAGE);
 where x is a string for the text to be displayed, and y is a
string for the title of the message dialog box.
 The other is to use a statement like this:
JOptionPane.showMessageDialog(null, x);
where x is a string for the text to be displayed.
45
import javax.swing.JOptionPane;
public class Welcome {
public static void main( String args[])
{
JOptionPane.showMessageDialog( null,

Welcome\nto\nJava\nProgramming!" );
}
}
 import declarations

• Used by compiler to identify and locate classes used in


Java programs.

• Tells compiler to load class JOptionPane from


javax.swing package.

• Class System part of package java.lang


 No import declaration needed
 java.lang automatically imported in every Java program
The exit Method
 Prior to JDK 1.5, you have to invoke System.exit()
to terminate the program if the program uses
JOptionPane dialog boxes.

 Since JDK 1.5, it is not necessary.

48
Message dialog type Icon Description
JOptionPane.ERROR_MESSAGE Displays a dialog that indicates
an error to the user.

JOptionPane.INFORMATION_MESSAGE Displays a dialog with an


informational message to the
user. The user can simply
dismiss the dialog.

JOptionPane.WARNING_MESSAGE Displays a dialog that warns the


user of a potential problem.

JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a


question to the user. This dialog
normally requires a response,
such as clicking on a Yes or a No
button.

JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply


contains a message, with no icon.
Fig . 2.12 JOptionPane c o nsta nts fo r me ssa g e dia lo g s.
Identifiers
 An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).

 An identifier must start with a letter, an underscore (_),


or a dollar sign ($). It cannot start with a digit.
 An identifier cannot be a reserved word.

 An identifier cannot be true, false, or null.

 An identifier can be of any length.

50
Identifiers…..

 Since Java is case-sensitive, X and x are different


identifier.

 Identifiers are used for naming variables,


constants, methods, classes, and packages.

 Descriptive identifiers make programs easy to


read.
Variables
 To put a value in memory, and later to get it back, a program
must have a name for each section of memory that it uses.

 Variable:- a name for a location in main memory which


uses a particular data type to hold a value.

 Variables are used to store data in a program.


 When new value is placed into a variable, replaces (and
destroys) previous value
Variable Declaration
 To use a variable, you declare it by telling the compiler
the name of the variable as well as what type of data it
represents.

 This is called variable declaration.

 Declaring a variable tells the compiler to allocate


appropriate memory space for the variable based on its
data type.

 The syntax for declaring a variable is:

datatype variableName;
53
Variable Declaration….

int x; // Declare x to be an
// integer variable;

double radius; // Declare radius to


// be a double variable;

char a; // Declare a to be a
// character variable;
Assignment Statements
 After a variable is declared, you can assign a value to it by using
an assignment statement. In java, the equal sign(=) is used as the
assignment operator.
 The syntax for assignment statement is as follows:
variable = expression;

x = 5*(3/2) + 2; // Assign the value


// of expression to x

radius = 1.0; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;

55
Variable Declaration and initialization
 Declaring and Initializing can be done in one step
 int x = 1
 String str = “Hi”;
 boolean b = (1 > 2);

 if variables are of the same type, they can be


declared together, as follows:
Examples: int i, j, k;
Constants
 The values of constants can never be changed once they
are initialized.
 Constant variables are also called named constants or
read-only variables.
 The general format for declaration of constants is given
by:
 final datatype CONSTANTNAME = VALUE;
 Examples
 final double PI = 3.14159;
 final int MAX_SIZE = 3;
57
Keywords
 Are reserved for use by Java and are always spelled with
all lowercase letters.

58
Primitive Data Type
 There are around 8 primitive data types in java.
 These are
 byte
 short
 int
 long
 float
 double
 boolean
 char

59
Numeric Data Type

Name Range Storage Size


byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed


(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
60
Numeric Data Type…..
 Java uses four types for integer : byte, short
int, and long.
 Choose the type that is most appropriate for your
variable.
Example:
 If you know an integer stored in a variable is within
the range of byte, declare the variable as a byte.

 Java uses two types for floating-point numbers: float


and double. The double type is twice a big as float.
Numeric Data Type…..

 The character data type, char, is used to represent a


single character.

 A character literal is enclosed in single quotation


marks.

Example:
char letter = ‘A’;
char numChar = ‘4’;
Casting
 Is converting from one data type to another

 The cast operator can be used to convert between


primitive numeric types, such as int and double, and
between related reference types

 The syntax for casting is to give the target type in


parentheses, followed by the variable name.

63
Casting…..
Example:
 double x =9.997; int n = (int) x; n is now 9
 double x = 9.997; int n = (int) Math.round(x); n is
now 10
 int i = 'a'; // same as int i = (int)'a'; i = 97
 char c = 97; // same as char c = (char)97; c is a
 int i = (int)’A’; System.out.println(i); // i is 65
 Casting to the wrong type may cause compilation errors
or runtime errors.
The String Type
 The char type only represents one character.
 To represent a string of characters, use the data type
called String.

Exampe:
String message = “Welcome to Java”

 String is actually a predinefed class in Java library


just like the System class and JOptionPane class.
The String Type …..

 The String type is not a primitive type. It is known


as a reference type.
 Any java class can be used as a reference type for a
variable.
 The plus sign (+) is the concatenation operator if
one of the operand is a string.
Example:
String message = “Welcome” + “to” + “Java”
The String Type …..

 If one of the operand is a non-string (e.g. a number),


the non-string value is converted into a string and
concatenated with the other string.

Example:
String s = “Chapter” + 2; // s becomes Chapter2
The String Type …..
 If neither of the operand is a string , the plus sign (+)
is the addition operator that adds two numbers.
 The shorthand += operator can be also used for string
concatenation.
Example:
String message = “ Welcome to Java”;
message += “ and Java is fun”;

So the message is “Welcome to Java and Java is fun ”


The String Type …..
 Suppose that i = 1 and j = 2, what is the output of
the following statement?
System.out.print(“i + j is ” + i + j);
Output is: i + j is 12

 To force i + j to be executed first , enclose i + j in


the parentheses, as follow

System.out.print(“ i + j is ” + (i + j));
Java Operator

Arithmetic operators
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Remainder 20 % 3 2
Java Operator ….
 When performing a binary operation involving two
operands of different types, Java automatically converts
the operand based on the following rules:
 
1.    If one of the operands is double, the other is converted
into double.
2.    Otherwise, if one of the operands is float, the other is
converted into float.
3.    Otherwise, if one of the operands is long, the other is
converted into long.
4.    Otherwise, both operands are converted into int.
Shortcut Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8

72
Increment and Decrement Operators
Operator Name Description

++var preincrement The expression (++var)


increments
var by 1 and evaluates to the new
value in var after the increment.

var++ postincrement The expression (var++)


evaluates to
the original value in var and
increments var by 1.

73
Increment and Decrement Operators

Operator Name Description


--var predecrement The expression (--var)
decrements
var by 1 and evaluates to the new
value in var after the decrement.

var-- postdecrement The expression (var--) evaluates


to the original value in var and
decrements var by 1.
Increment and Decrement Operators, cont.
int i = 10; Same effect as
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

75
Java Operator…
Logical operators
 && for the logical “and” operator and
 || for the logical “or” operator

76
Java Operator…

Relational operators
 == (equal),
 != (not equal)
 < (less than),
 > (greater than),

 <= (less than or equal), and


 >= (greater than or equal) operators.
77
Java Operator…

 Conditional Operator (?:)


 Is the Java’s only ternary operator - that means it takes
three operands
 The first operand is Boolean expression
 Either the second or the third operand is executed based
on the value of the first operand
Example:
System.out.println(Grade>=60?”Passed”:”Failed);
Max = X > Y ? X : Y

78
Java Operator…

 The new Operator


 Is used to create an object or instance from a class.

Example:

Scanner s = new Scanner(System.in);


DataInputStream str = new DataInputStream (System.in);
Expressions
 An expression is any legal combination of symbols that
represents a value.
 Each programming language and application has its own
rules for what is legal and illegal.
 In Java, arithmetic, boolean, and String expressions are
written in conventional mathematical infix notation.
 Examples of valid expressions in java are:

Var X+1 “string”


5 ! (5 < 6) (x*x + y*y > 25) && (x > 0)

80
Obtaining Input

1. Using JOptionPane input dialogs


2. Using Scanner class

81
Getting Input from Input Dialog Boxes
 You can use the showInputDialog method in JoptionPane
class to get input at run time.
String input = JOptionPane.showInputDialog(
null,“Prompting Message”,“Dialog Title”,
JOptionPane.QUESTION_MESSAGE);

82
Two Ways to Invoke the Method
There are several ways to use the showInputDialog method. For
the time being, you only need to know two ways to invoke it.
One is to use a statement as shown in the example:

String string = JOptionPane.showInputDialog(null,


x,y, JOptionPane.QUESTION_MESSAGE));

where x is a string for the prompting message, and y is a string for


the title of the input dialog box.

The other is to use a statement like this:


JOptionPane.showInputDialog(x);
where x is a string for the prompting message.

83
Converting Strings to Integers
 The input returned from the input dialog box is a string.
 If you enter a numeric value such as 123, it returns
“123”.
 To obtain the input as a number, you have to convert a
string into a number.
 To convert a string into an int value, you can use the
static parseInt method in the Integer class as follows:
 
int intValue = Integer.parseInt(intString);
 
where intString is a numeric string such as “123”.
84
Converting Strings to Doubles
 To convert a string into a double value, you can use the
static parseDouble method in the Double class as
follows:

double doubleValue =Double.parseDouble(doubleString);

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

85
Getting Input Using Scanner
 Java uses System.out to refer to the standard output
device , and System.in the standard input device.

 By default the output device is the console and the


input device is the keyboard.

 To perform console output, you simply use the


println
method a primitive values or a string to the console.

 Console input is not directly supported in Java but


you can use the Scanner class in java.util package to
86
Getting Input Using Scanner
1. Create a Scanner object
Scanner scanner = new Scanner(System.in);

2. Use the methods next(), nextByte(), nextShort(),


nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int,
long, float, double, or boolean value.
For Example:
System.out.print("Enter a double value: ");
Scanner scanner = new Scanner(System.in);
double d = scanner.nextDouble();

87
Getting Input Using Scanner Examples

import java.util.Scanner;
public class TestScanner {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");

int intValue = scanner.nextInt();


System.out.println("You entered the
integer " + intValue);
Getting Input Using Scanner Examples…
System.out.print("Enter a double value: "); double
doubleValue = scanner.nextDouble();
System.out.println("You entered the double value “
+ doubleValue);

System.out.print("Enter a string without space:");


String string = scanner.next();
System.out.println("You entered the string " +
string);
}
}
Control Flows
The boolean Type and Operators
 Often in a program you need to compare two values,
such as whether i is greater than j.

 Java provides six comparison operators (also known as


relational operators) that can be used to compare two
values.

 The result of the comparison is a Boolean value: true or


false.

boolean b = (1 > 2);

90
Control Flows….
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
91
Control Flows….
Boolean Operators

Operator Name
! not
&& and
|| or
^ exclusive or

92
Control Flows….
The & and | Operators

&& : conditional AND operator


& : unconditional AND operator

||: conditional OR operator


|: unconditional OR operator

93
Control Flows
 There are three basic types of program flows
Sequential
 In Sequential execution statements in a program are
executed one after the other in sequence.
Selection
 Selection or conditional execution executes part of the
code based on the condition.
Iteration
 In iterative program flow statements inside looping
statement are executed repeatedly as long as a condition is
true
94
Selection/conditional Statement
 Java has the following Conditional statements

 if Conditions
 if Statement
 If…else Statement
 if …else if…else Statement
 Conditional Operators (?:)
 switch Statements

95
if Statements
if (radius >= 0) {
if (booleanExpression) { area = radius * radius * PI;
statement(s); System.out.println("The area"
}
+ " for the circle of radius "
+ radius + " is " + area); }

false false
Boolean (radius >= 0)
Expression

true true

Statement(s) area = radius * radius * PI;


System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);

(A) (B)
96
if Statements ….

Note

Outer parentheses required Braces can be omitted if the block contains a single
statement

if ((i > 0) && (i < 10)) { Equivalent if ((i > 0) && (i < 10))
System.out.println("i is an " + System.out.println("i is an " +
+ "integer between 0 and 10"); + "integer between 0 and 10")
}
(a) (b)

97
if Statements ….
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation
error or a runtime error, it is a logic error.
98
The if...else Statement
 These selection statement is used if there are exactly two selections

 Syntax:
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}

99
The if...else Statement…..

true false
Boolean
Expression

Statement(s) for the true case Statement(s) for the false case
The if...else Statement, example

if (radius >= 0)
{
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else
{
System.out.println("Negative input");
}

101
Conditional Operators (?:)
 Conditional statement can be used instead of if…else
statement
if (x > 0)
y = 1
else
y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;
 Syntax
(booleanExp) ? exp1 : exp2

102
if …else if…else Statement
 if…else if…else statement is important if there are
more than two conditions.
 Syntax:

if(booleanExpression1) {
statement(s);
}
else if booleanExpression2){
statement(s);
}
……
else {
statement(s);
}
103
if …else if…else Statement, example
•The following code snippet depicts how nested if else
statement is used to calculate letter grade from a score
out of 100

104
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


grade = 'A'; grade = 'A';
else Equivalent else if (score >= 80.0)
if (score >= 80.0) grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F';
grade = 'D';
else
grade = 'F';

105
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

106
Trace if-else statement…
Suppose score is 70.0 The condition is false

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

107
Trace if-else statement…
Suppose score is 70.0 The condition is true

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

108
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

109
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

110
 The else clause matches the most recent if clause in the
same block.

int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; int k = 3;
Equivalent
if (i > j) if (i > j)
if (i > k) if (i > k)
System.out.println("A"); System.out.println("A");
else else
System.out.println("B"); System.out.println("B");

(a) (b)

111
Note, cont.
 Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you must
add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.

112
if …else if…else Statement, example
 The example in preceding slide can be done by
using sequence of if statements
if(score>=90)
grade =‘A’
if (score>=80)
grade = “B”
if (score >=70)
grade = ‘C’
if (score>=60)
grade = ‘D’

113
if …else if…else Statement, example
 Problem: Write a program that solves quadratic
equation

114
switch Statements
 The if/else construct can be cumbersome when you have
to deal with multiple selections with many alternatives.
Example: To set up Menu System
 Syntax
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
………
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
} 115
switch Statements flow chart

Case 1
St atement(s) break

Case 2
St atement(s) break

sCase 3
St atement(s) break

Case N
St atement(s) break

default
St atement(s)

Next St at ement
116
switch Statements…
 The switch-expression must yield a value of char, byte,
short, or int type and must always be enclosed in
parentheses.
 The value1, ..., and valueN must have the same data type
as the value of the switch-expression.
 The resulting statements in the case statement are executed
when the value in the case statement matches the value of
the switch-expression.
 Note that value1, ..., and valueN are constant
expressions, meaning that they cannot contain
variables in the expression, such as 1 + x.
117
switch Statements…
 The keyword break is optional, but it should be used at the
end of each case in order to terminate the remainder of the
switch statement.
 If the break statement is not present, the next case statement
will be executed.
 The default case, which is optional, can be used to perform
actions when none of the specified cases matches the switch-
expression.
 The case statements are executed in sequential order, but the
order of the cases (including the default case) does not matter.
 However, it is good programming style to follow the logical
sequence of the cases and place the default case at the end.

118
switch Statements, Example

 Write a java program that converts students score to


letter grade using switch statement
case 5:
int Choice = score/10
case 4:
switch(choice){
case 3:
case 9:
grade = ‘A’;
case 2:
break; case 1:
case 8: case 0:
grade = ‘B’; grade = 'F';
break; break;
case 7: default:
grade = ‘C’;
System.out.println("Invalid
break; score");
119
}
Repetition Statement

 Java have the following repetition statements

 while loop
 do…while loop
 for loop
 for each loop

120
while Loop
Syntax: int count = 0;

while(loop-continuation- while (count < 100) {


System.out.println("Welcome to
condition)
Java!");
Statement(s);
count++;
increment;
}
}
count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true true
Statement(s) System.out.println("Welcome to
(loop body) Java!");
count++;

121
(A) (B)
while Loop….
 Each loop contains a loop continuation condition, a
Boolean expression that controls the execution of the
body.

 The part of the loop that contains the statements to be


repeated is called the loop body.

 A one time execution of a loop body is referred to as an


iteration of the loop.
 The braces enclosing the loop body can be omitted only
if the loop contains one or no statement.
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

123
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

124
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

125
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

126
animation

Trace while Loop, cont.


(count < 2) is still true since
int count = 0; count is 1

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

127
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

128
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

129
animation

Trace while Loop, cont.


(count < 2) is false since count is
int count = 0; 2 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

130
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

131
Controlling a loop with Confirmation Dialog

 A confirmation dialog can be created using the


following statement:

int option = JOptionPane.showConfirmDialog


(null,“Continue”)
Controlling a loop with Confirmation Dialog…

 When a button is clicked, the method returns an


option value.
 The value is :
 JOptionPane.YES_OPTION or 0 for the Yes button.

 JOptionPane.NO_OPTION or 1 for the No button.

 JOptionPane.CANCEL_OPTION or 2 for the


Cancel button.
Ending a Loop with a Sentinel Value
 Often the number of times a loop is executed is not
predetermined.
You may use an input value to signify the end of the
loop. Such a value is known as a sentinel value.

Examples:

Write a program that reads and calculates the sum of an


unspecified number of integers. The input 0 signifies the
end of the input.

134
Ending a Loop with a Sentinel Value
 Often the number of times a loop is executed is not
predetermined.
 You may use an input value to signify the end of the
loop. Such a value is known as a sentinel value.

Exercise:
Write a program that reads and calculates the sum of an
unspecified number of integers. The input 0 signifies the
end of the input.
do-while Loop

Syntax:
do {
Statement(s)
// Loop body; (loop body)

Statement(s);
true Loop
} while (condition); Continuation
Condition?

Note that: in do while loop false


the body of the loop is
executed at least once

136
For loop
 Syntax
for ( initialization; loopContinuationCondition; increment )
{
Statement (s);
}

137
For loop…

138
animation

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

139
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

140
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}

141
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

142
animation

Trace for Loop, cont.


Execute adjustment
int i; statement
for (i = 0; i < 2; i++) { i now is 1
System.out.println("Welcome to Java!");
}

143
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

144
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

145
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

146
animation

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

147
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

148
Note
 The initial-action in a for loop can be a list of zero or
more comma-separated expressions.
 The action-after-each-iteration in a for loop can be a list
of zero or more comma-separated statements.
Therefore, the following two for loops are correct.
for (int i = 1; i < 100; System.out.println(i++));

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


// Do something
} 149
Note ….
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct.

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

150
Note….
 The while loop and for loop are called pre-test
loops because the continuation condition is checked
before the loop body is executed.

 The do-while loop is called a post-test loop


because the condition is checked after the loop body
is executed.
Nested for loop
 Problem: Write a program that uses nested for
loops to print the following output.
 Output: should look like

*
**
***
****
*****

152
Nested for loop Example

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
System.out.print("*");
System.out.println();

153
Recommendations
Use the one that is most intuitive and comfortable for you.
In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times.
A while loop may be used if the number of repetitions is
not known, as in the case of reading the numbers until the
input is 0.
A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition.

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

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


{
System.out.println("i is " + i);
}

155
Caution….
Similarly, the following loop is also wrong:
int i=0; Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct

156
break and continue Statements
 Two statements, break and continue, can be used in loop
statements to provide the loop with additional control.

break : immediately ends the innermost loop that contains


it. It is generally with an if control.

continue: only ends the current iteration. Program control


goes to the end of the loop body. It is generally with an
if control

157
break Example

int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100)
break;
}
continue Example

int sum = 0;
int number = 0;
while (number < 20) {
number++;
if(number == 10 || number == 11)
continue;
sum += number;
}
Statement Labels and Breaking with Labels

outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
break outer;
}
}
Statement Labels and Breaking with Labels..

outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
continue outer;
}
}
For-each Loop
 The basic for loop was extended in Java 5 to
make iteration over arrays and other collections
more convenient.
 This newer for statement is called the enhanced
for or for-each (because it is called this in other
programming languages).

162
For-each Loop example
• The for-each loop is used to access each successive value
in a collection of values.
• Here is a loop written as both a for-each loop and a basic
for loop to add all elements of an array
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
// i indexes each element successively.
for (int i = 0; i < ar.length; i++) {
Sum += ar[i];
}
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
// d gets successively each value in ar
for (double d : ar)
{
sum += d; 163

You might also like