0% found this document useful (0 votes)
5 views151 pages

Intermediate Programming Lecture Notes

Java, created in 1991 by James Gosling and others at Sun Microsystems, was initially called Oak and aimed to be a platform-independent language for consumer electronics. It encompasses a programming language, development environment, application environment, and deployment environment, allowing applications to run on any machine with the Java Runtime Environment. The document also covers Java programming fundamentals, including comments, statements, identifiers, keywords, literals, and variable management.

Uploaded by

dahryll44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views151 pages

Intermediate Programming Lecture Notes

Java, created in 1991 by James Gosling and others at Sun Microsystems, was initially called Oak and aimed to be a platform-independent language for consumer electronics. It encompasses a programming language, development environment, application environment, and deployment environment, allowing applications to run on any machine with the Java Runtime Environment. The document also covers Java programming fundamentals, including comments, statements, identifiers, keywords, literals, and variable management.

Uploaded by

dahryll44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION

TO
JAVA

1
Java Background: History

• Java
– was created in 1991
– by James Gosling et al. of Sun
Microsystems.
– Initially called Oak, in honor of
the tree outside Gosling's
window, its name was changed
to Java because there was
already a language called Oak.

2
• 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.
– One of the first projects developed using Java: a
personal hand-held remote control named Star 7.
– 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.

3
Java Background:
What is Java Technology?

• The Java technology is:


– A programming language
– A development environment
– An application environment
– A deployment environment

4
Java Technology: Programming
Language

• As a programming language, Java can create


all kinds of applications that you couldn’t
create using any conventional programming
language.

5
Java Technology:
A Development Environment
• As a development environment, Java
technology provides you with a large
suite of tools:
– A compiler
– An interpreter
– A documentation generator
– A class file packaging tool

6
Java Technology:
An Application and Runtime Environment
Java technology applications are typically general-purpose
programs that run on any machine where the Java Runtime
Environment (JRE) is installed.

There are two main deployment environments:


1. The JRE supplied by the Java 2 Software Development Kit (SDK)
contains the complete set of class files for all the Java technology
packages, which includes basic language classes, GUI component
classes, and so on.

2. The other main deployment environment is on your web browser.


Most commercial browsers supply a Java technology interpreter and
runtime environment.

7
Phases of a Java Program
• The following figure describes the process of
compiling and executing Java program.

8
Phases of a Java Program
– Bytecode
• a special machine language that can be
understood by the Java Virtual Machine
(JVM).
• is independent of any particular computer
hardware, so any computer with a Java
interpreter can execute the compiled Java
program, no matter what type of computer
the program was compiled on.

9
– The Java Virtual Machine

• is an imaginary machine that is implemented


by emulating software on a real machine.
• provides the hardware platform specifications
to which you compile all Java technology
code.
• this specification enables the Java software
to be platform-independent because the
compilation is done for a generic machine
known as the JVM.

10
Phases of a Java Program

11
Programming Fundamentals
Topics
• Dissecting my first Java program
• Java Comments
– C++-Style Comments
– C-Style Comments
– Special Javadoc Comments
• Java Statements and Blocks
• Java Identifiers
• Java Keywords
• Java Literals (integer, floating point, boolean,
character, String)
Topics
• Primitive data types
– Logical – boolean
– Textual – char
– Integral – byte, short, int & long
– Floating Point – float and double
• Variables
– Declaring and Initializing Variables
– Outputting Variable Data
– [Link]() vs. [Link]()
– Reference Variables vs. Primitive Variables
Topics

• Operators
– Arithmetic operators
– Increment and Decrement operators
– Relational operators
– Logical operators
– Conditional operator
– Operator Precedence
Dissecting my First Java Program
1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){

7 //prints the string “Hello world” on screen


8 [Link](“Hello world”);

9 }
10 }
Dissecting my First Java Program

1 public class Hello


2 {
3 /**
4 * My first Java program
5 */
● indicates the name of the class which is Hello
● In Java, all code should be placed inside a class
declaration
● The class uses an access specifier public, which
indicates that our class in accessible to other
classes from other packages (packages are a
collection of classes).
Dissecting my First Java Program
1 public class Hello
2 {
3 /**
4 * My first Java program
5 */

• The next line which contains a curly brace {


indicates the start of a block.
• In this code, we placed the curly brace at the next
line after the class declaration, however, we can
also place this next to the first line of our code. So,
we could actually write our code as:
Dissecting my First Java Program
1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
● The next three lines indicates a Java comment.
● A comment
− something used to document a part of a code.
− It is not part of the program itself, but used for
documentation purposes.
− It is good programming practice to add comments to
your code.
Dissecting my First Java Program
1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){

● indicates the name of one method in Hello which is the


main method.
● The main method is the starting point of a Java program.
● All programs except Applets written in Java start with the
main method.
● Make sure to follow the exact signature.
Dissecting my First Java Program

1 public class Hello


2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){

7 //prints the string “Hello world” on screen

● The next line is also a Java comment


Dissecting my First Java Program
1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){

7 //prints the string “Hello world” on screen


8 [Link](“Hello world”);

● The command [Link](), prints the text


enclosed by quotation on the screen.
Dissecting my First Java Program
1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){

7 //prints the string “Hello world” on screen


8 [Link](“Hello world”);

9 }
10 }

● The last two lines which contains the two curly braces is
used to close the main method and class respectively.
Coding Guidelines
1. Your Java programs should always end with the
.java extension.

2. Filenames should match the name of your public


class. So for example, if the name of your public
class is Hello, you should save it in a file called
[Link].

3. You should write comments in your code explaining


what a certain class does, or what a certain method
does.
Java Comments

• Comments
– These are notes written to a code for
documentation purposes.
– Those texts are not part of the program and
does not affect the flow of the program.

• 3 Types of comments in Java


– C++ Style Comments
– C Style Comments
– Special Javadoc Comments
Java Comments

• C++-Style Comments
– C++ Style comments starts with //
– All the text after // are treated as comments
– For example:
// This is a C++ style or single line comments
Java Comments

• C-Style Comments
– C-style comments or also called multiline
comments starts with a /* and ends with a */.
– All text in between the two delimeters are treated
as comments.
– Unlike C++ style comments, it can span multiple
lines.
– For example:
/* this is an exmaple of a
C style or multiline comments */
Java Statements

• Statement
– one or more lines of code terminated by a
semicolon.
– Example:
[Link](“Hello world”);
Java Blocks
• Block
– is one or more statements bounded by an opening
and closing curly braces that groups the statements
as one unit.
– Block statements can be nested indefinitely.
– Any amount of white space is allowed.
– Example:
public static void main( String[] args
){
[Link]("Hello");
[Link]("world”);
}
Java Statements and Blocks
Coding Guidelines

1. In creating blocks, you can place the opening curly


brace in line with the statement. For example:
public static void main( String[]
args ){
or you can place the curly brace on the next line,
like,
public static void main( String[]
args )
{
Java Statements and Blocks
Coding Guidelines

2. You should indent the next statements after the


start of a block. For example:

public static void main( String[]


args ){
[Link]("Hello");
[Link]("world");
}
Java Identifiers

• Identifiers
– are tokens that represent names of variables,
methods, classes, etc.
– Examples of identifiers are: Hello, main, System,
out.

• Java identifiers are case-sensitive.


– This means that the identifier Hello is not the
same as hello.
Java Identifiers

• Identifiers must begin with either a letter, an


underscore “_”, or a dollar sign “$”. Letters may be
lower or upper case. Subsequent characters may
use numbers 0 to 9.

• Identifiers cannot use Java keywords like class,


public, void, etc. We will discuss more about Java
keywords later.
Java Identifiers
Coding Guidelines

1. For names of classes, capitalize the first letter of the


class name. For example,
ThisIsAnExampleOfClassName

2. For names of methods and variables, the first letter of the


word should start with a small letter. For example,
thisIsAnExampleOfMethodName
Java Identifiers
Coding Guidelines

3. In case of multi-word identifiers, use capital letters to


indicate the start of the word except the first word. For
example,
charArray, fileNumber, ClassName.

4. Avoid using underscores at the start of the identifier such


as _read or _write.
Java Keywords

• Keywords are predefined identifiers reserved by


Java for a specific purpose.

• You cannot use keywords as names for your


variables, classes, methods ... etc.

• The next line contains the list of the Java


Keywords.
Some Java Keywords
Java Literals

• Literals are tokens that do not change or are


constant.
• The different types of literals in Java are:
– Integer Literals
– Floating-Point Literals
– Boolean Literals
– Character Literals
– String Literals
Java Literals: Integer
• Integer literals come in different formats:
– decimal (base 10)
– hexadecimal (base 16)
– octal (base 8).
• Special Notations in using integer literals in our programs:
– Decimal
• No special notation
• example: 12
– Hexadecimal
• Precede by 0x or 0X
• example: 0xC
– Octal
• Precede by 0
• example: 014
Java Literals: Floating Point

• Represents decimals with fractional parts


– Example: 3.1416
• Can be expressed in standard or scientific notation
– Example: 583.45 (standard), 5.8345e2
(scientific)
Java Literals: Boolean

• Boolean literals have only two values, true or false.


Java Literals: Character

• Character Literals represent single Unicode


characters.
• Unicode character
– a 16-bit character set that replaces the 8-bit
ASCII character set.
– Unicode allows the inclusion of symbols and
special characters from other languages.
Java Literals: Character

• To use a character literal, enclose the character in


single quote delimiters.
• For example
– the letter a, is represented as ‘a’.
– special characters such as a newline character,
a backslash is used followed by the character
code. For example, ‘\n’ for the newline character
Java Literals: String

• String literals represent multiple characters and are


enclosed by double quotes.
• An example of a string literal is, “Hello World”.
Primitive Data Types
• The Java programming language defines eight
primitive data types.
– boolean (for logical)
– char (for textual)
– byte (8 bits – very small whole numbers)
– short (16 bits – small whole numbers)
– int (32 bits – whole numbers)
– long (64 bits – large whole number)
– double (64 bits – decimal numbers, more precise)
– float (32 bits – decimal numbers, floating point)
Variables
• A variable is an item of data used to store the state
of objects.

• A variable has a:
– data type
• The data type indicates the type of value that
the variable can hold.
– name
• The variable name must follow rules for
identifiers.
Declaring and Initializing Variables

• Declare a variable as follows:


<data type> <name> [=initial value];

• Note: Values enclosed in <> are required values,


while those values in [] are optional.
Declaring and Initializing Variables:
Sample Program
1 public class VariableSamples {
2 public static void main( String[] args ){
3 //declare a data type with variable name
4 // result and boolean data type
5 boolean result;

6 //declare a data type with variable name


7 // option and char data type
8 char option;
9 option = 'C'; //assign 'C' to option

10 //declare a data type with variable name


11 //grade, double data type and initialized
12 //to 0.0
13 double grade = 0.0;
14 }
Declaring and Initializing Variables: Coding
Guidelines

1. It always good to initialize your variables as you


declare them.

2. Use descriptive names for your variables. Like for


example, if you want to have a variable that
contains a grade for a student, name it as, grade
and not just some random letters you choose.
Declaring and Initializing Variables: Coding
Guidelines

3. Declare one variable per line of code. For example,


the variable declarations,
double exam=0;
double quiz=10;
double grade = 0;
is preferred over the declaration,
double exam=0, quiz=10, grade=0;
Outputting Variable Data

• In order to output the value of a certain variable, we


can use the following commands:
– [Link]()
– [Link]()
Outputting Variable Data: Sample Program
1 public class OutputVariable {
2 public static void main( String[] args ){
3 int value = 10;
4 char x;
5 x = ‘A’;

6 [Link]( value );
7 [Link]( “The value of x=“ + x );
8 }
9 }

The program will output the following text on screen:

10
The value of x=A
[Link]() vs.
[Link]()

• [Link]()
– Appends a newline at the end of the data output

• [Link]()
– Does not append newline at the end of the data
output
[Link]() vs.
[Link]() Examples
● Program 1:
[Link](“Hello”);
[Link](“World”);
Output:
HelloWorld

● Program 2:
[Link](“Hello”);
[Link](“World”);
Output:
Hello
World
Operators

• Different types of operators:


– arithmetic operators
– relational operators
– logical operators
– conditional operators

• These operators follow a certain kind of precedence so


that the compiler will know which operator to evaluate
first in case multiple operators are used in one
statement.
Arithmetic Operators
Arithmetic Operators:
Sample Program
1 public class ArithmeticDemo {
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 double x = 27.475;
7 double y = 7.22;
8 [Link]("Variable values...");
9 [Link](" i = " + i);
10 [Link](" j = " + j);
11 [Link](" x = " + x);
12 [Link](" y = " + y);
[Link]("Adding...");
13 [Link](" i + j = " + (i + j));
14 [Link](" x + y = " + (x + y));
Arithmetic Operators:
Sample Program
15 //subtracting numbers
16 [Link]("Subtracting...");
17 [Link](" i - j = " + (i – j));
18 [Link](" x - y = " + (x – y));

19 //multiplying numbers
20 [Link]("Multiplying...");
21 [Link](" i * j = " + (i * j));
22 [Link](" x * y = " + (x * y));

23 //dividing numbers
24 [Link]("Dividing...");
25 [Link](" i / j = " + (i / j));
26 [Link](" x / y = " + (x / y));
Arithmetic Operators:
Sample Program

29 //computing the remainder resulting from dividing


30 // numbers
31 [Link]("Computing the remainder...");
32 [Link](" i % j = " + (i % j));
33 [Link](" x % y = " + (x % y));

34 //mixing types
35 [Link]("Mixing types...");
36 [Link](" j + y = " + (j + y));
37 [Link](" i * x = " + (i * x));
38 }
39}
Arithmetic Operators:
Sample Program Output
Variable values... Dividing...
i = 37 i/j=0
j = 42 x / y = 3.8054 Computing the
x = 27.475 remainder...
y = 7.22 i % j = 37
Adding... x % y = 5.815
i + j = 79 Mixing types...
x + y = 34.695 j + y = 49.22
Subtracting... i * x = 1016.58
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Arithmetic Operators

• Note:
– When an integer and a floating-point number are
used as operands to a single arithmetic
operation, the result is a floating point. The
integer is implicitly converted to a floating-point
number before the operation takes place.
Increment and Decrement Operators

• unary increment operator (++)


• unary decrement operator (--)
• Increment and decrement operators increase and
decrease a value stored in a number variable by 1.
• For example, the expression,
count = count + 1; //increment the value of count
by 1 is equivalent to,
count++;
Increment and Decrement Operators
Increment and Decrement Operators

• The increment and decrement operators can be


placed before or after an operand.
• When used before an operand, it causes the
variable to be incremented or decremented by 1,
and then the new value is used in the expression in
which it appears.
• For example,

int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
Increment and Decrement Operators

• When the increment and decrement operators are


placed after the operand, the old value of the
variable will be used in the expression where it
appears.
• For example,

int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13
Increment and Decrement Operators:
Coding Guidelines

• Always keep expressions containing increment and


decrement operators simple and easy to
understand.
Relational Operators
• Relational operators compare two values and
determines the relationship between those values.
• The output of evaluation are the boolean values
true or false.
Relational Operators:
Sample Program
1 public class RelationalDemo{
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 int k = 42;
7 [Link]("Variable values...");
8 [Link](" i = " +i);
9 [Link](" j = " +j);
10 [Link](" k = " +k);
11 //greater than
12 [Link]("Greater than...");
13 [Link](" i > j = "+(i>j));//false
14 [Link](" j > i = "+(j>i));//true
15 [Link](" k > j = "+(k>j));//false
Relational Operators:
Sample Program
16 //greater than or equal to
17 [Link]("Greater than or equal to...");
18 [Link](" i >= j = "+(i>=j));//false
19 [Link](" j >= i = "+(j>=i));//true
20 [Link](" k >= j = "+(k>=j));//true
21 //less than
22 [Link]("Less than...");
23 [Link](" i < j = "+(i<j));//true
24 [Link](" j < i = "+(j<i));//false
25 [Link](" k < j = "+(k<j));//false
26 //less than or equal to
27 [Link]("Less than or equal to...");
28 [Link](" i <= j = "+(i<=j));//true
29 [Link](" j <= i = "+(j<=i));//false
30 [Link](" k <= j = "+(k<=j));//true
Relational Operators:
Sample Program
31 //equal to
32 [Link]("Equal to...");
33 [Link](" i == j = " + (i==j));//false
34 [Link](" k == j = " + (k==j));//true
35 //not equal to
36 [Link]("Not equal to...");
37 [Link](" i != j = " + (i!=j));//true
38 [Link](" k != j = " + (k!=j));//false
39 }
40 }
Relational Operators:
Sample Program Output
Variable values... Less than or equal to...
i = 37 i <= j = true
j = 42 j <= i = false
k = 42 k <= j = true
Greater than... Equal to...
i > j = false i == j = false
j > i = true k == j = true
k > j = false Not equal to...
Greater than or equal to... i != j = true
i >= j = false k != j = false
j >= i = true
k >= j = true
Less than...
i < j = true
j < i = false
k < j = false
Logical Operators
• Logical operators have one or two boolean
operands that yield a boolean result.
• There are six logical operators:
– && (logical AND)
– & (boolean logical AND)
– || (logical OR)
– | (boolean logical inclusive OR)
– ^ (boolean logical exclusive OR)
– ! (logical NOT)
Logical Operators

• The basic expression for a logical operation is,


x1 op x2
where,
x1, x2 - can be boolean expressions, variables or
constants
op - is either &&, &, ||, | or ^ operator.

• The truth tables that will be shown next, summarize


the result of each operation for all possible
combinations of x1 and x2.
Logical Operators: &&(logical) and
&(boolean logical) AND

● Here is the truth table for && and &,


Logical Operators: &&(logical) and
&(boolean logical) AND
● The basic difference between && and & operators :
− && supports short-circuit evaluations (or partial evaluations),
while & doesn't.

● Given an expression:
exp1 && exp2
− && will evaluate the expression exp1, and immediately return
a false value is exp1 is false.
− If exp1 is false, the operator never evaluates exp2 because
the result of the operator will be false regardless of the value
of exp2.
● In contrast, the & operator always evaluates both exp1 and exp2
before returning an answer.
Logical Operators: &&(logical) and
&(boolean logical) AND
1 public class TestAND {
2 public static void main( String[] args ){
3 int i = 0;
4 int j = 10;
5 boolean test= false;
6 //demonstrate &&
7 test = (i > 10) && (j++ > 9);
8 [Link](i);
9 [Link](j);
10 [Link](test);
11 //demonstrate &
12 test = (i > 10) & (j++ > 9);
13 [Link](i);
14 [Link](j);
15 [Link](test);
16 }
17 }
Logical Operators: &&(logical) and
&(boolean logical) AND
● The output of the program is,
0
10
false
0
11
false

● Note, that the j++ on the line containing the &&


operator is not evaluated since the first expression
(i>10) is already equal to false.
Logical Operators: || (logical) and | (boolean
logical) inclusive OR
• Here is the truth table for || and |,
Logical Operators: || (logical) and | (boolean
logical) inclusive OR
● The basic difference between || and I operators :
− || supports short-circuit evaluations (or partial evaluations),
while | doesn't.
● Given an expression:
exp1 II exp2
− || will evaluate the expression exp1, and immediately return a
true value is exp1 is true
− If exp1 is true, the operator never evaluates exp2 because
the result of the operator will be true regardless of the value
of exp2.
− In contrast, the | operator always evaluates both exp1 and
exp2 before returning an answer.
Logical Operators: || (logical) and | (boolean
logical) inclusive OR
1 public class TestOR {
2 public static void main( String[] args ){
3 int i = 0;
4 int j = 10;
5 boolean test= false;
6 //demonstrate ||
7 test = (i < 10) || (j++ > 9);
8 [Link](i);
9 [Link](j);
10 [Link](test);
11 //demonstrate |
12 test = (i < 10) | (j++ > 9);
13 [Link](i);
14 [Link](j);
15 [Link](test);
16 }
17 }
Logical Operators: || (logical) and | (boolean
logical) inclusive OR

● The output of the program is,


0
10
true
0
11
true

● Note, that the j++ on the line containing the ||


operator is not evaluated since the first expression
(i<10) is already equal to true.
Logical Operators: ^ (boolean logical
exclusive OR)
• Here is the truth table for ^,

• The result of an exclusive OR operation is TRUE, if


and only if one operand is true and the other is
false.
• Note that both operands must always be evaluated
in order to calculate the result of an exclusive OR.
Logical Operators: ^ (boolean logical
exclusive OR)
1 public class TestXOR {
2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = true;
5 [Link](val1 ^ val2);
6 val1 = false; val2 = true;
7 [Link](val1 ^ val2);
8 val1 = false; val2 = false;
9 [Link](val1 ^ val2);
10 val1 = true; val2 = false;
11 [Link](val1 ^ val2);
12 }
13 }
Logical Operators: ^ (boolean logical
exclusive OR)
● The output of the program is,
false
true
false
true
Logical Operators: ! ( logical NOT)

• The logical NOT takes in one argument, wherein


that argument can be an expression, variable or
constant.
• Here is the truth table for !,
Logical Operators: ! ( logical NOT)

1 public class TestNOT {


2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = false;
5 [Link](!val1);
6 [Link](!val2);
7 }
8 }
• The output of the program is,
false
true
Logical Operators: Conditional
Operator (?:)
• The conditional operator ?:
– is a ternary operator.
• This means that it takes in three arguments that together
form a conditional expression.
– The structure of an expression using a conditional operator is
exp1?exp2:exp3
wherein,
exp1 - is a boolean expression whose result must either be
true or false

– Result:
If exp1 is true, exp2 is the value returned.
If it is false, then exp3 is returned.
Logical Operators: Conditional
Operator (?:)
1 public class ConditionalOperator {
2 public static void main( String[] args ){
3 String status = "";
4 int grade = 80;
5 //get status of the student
6 status = (grade >= 60)?"Passed":"Fail";
7 //print status
8 [Link]( status );
9 }
10 }

• The output of this program will be,


Passed
Logical Operators: Conditional
Operator (?:)
Operator Precedence
Operator Precedence

• Given a complicated expression,

6%2*5+4/2+88-10

we can re-write the expression and place some


parenthesis base on operator precedence,

((6%2)*5)+(4/2)+88-10;
Operator Precedence: Coding
Guidelines

• To avoid confusion in evaluating mathematical


operations, keep your expressions simple and use
parentheses.
Summary

• Java Comments (C++-Style Comments, C-Style


Comments, Special Javadoc Comments)
• Java statements, blocks, identifiers, keywords
• Java Literals (integer, floating point, boolean,
character, String)
• Primitive data types( boolean, char, byte, short, int,
long, float, double)
Summary

• Variables (declare, initialize, output)


• [Link]() vs. [Link]()
• Reference Variables vs. Primitive Variables
• Operators (Arithmetic operators, Increment and
Decrement operators, Relational operators, Logical
operators, Conditional Operator (?:), Operator
Precedence)
Getting Input from Keyboard
Topics

• Using BufferedReader to get input


• Using JOptionPane to get input
Control Structures
Topics

• Decision Control Structures


– if statement
– if-else statement
– if-else-if statement
– switch statement
• Repetition Control Structures
– while loop
– do-while loop
– for loop
Control Structures

• Control structures
– allows us to change the ordering of how the
statements in our programs are executed

• Two types of Control Structures


– decision control structures
• allows us to select specific sections of code to
be executed
– repetition control structures
• allows us to execute specific sections of the
code a number of times
Decision Control Structures

• Decision control structures


– Java statements that allows us to select
and execute specific blocks of code while
skipping other sections

• Types:
– if-statement
– if-else-statement
– If-else if-statement
The if-statement

• The if-statement specifies that a


statement (or block of code) will be
executed if and only if a certain boolean
statement is true.

• The if-statement has the form,


if( boolean_expression )
statement;

expression or boolean variable.


• or
if( boolean_expression ){
statement1;
statement2;
. . .
}
where,
– boolean_expression is either a boolean
The if-statement:
Flowchart
The if-statement:
Sample code snippets
int grade = 68;
if( grade > 60 )
[Link]("Congratulations!");

int grade = 68;


if( grade > 60 ){
[Link]("Congratulations!");
[Link]("You passed!");
}
The if-statement:
Coding Guidelines
1. The boolean_expression part of a statement should
evaluate to a boolean value.
That means that the execution of the condition should
either result to a value of true or a false.

2. Indent the statements inside the if-block.


For example,
if( boolean_expression ){
//statement1;
//statement2;
}
The if-else statement
• The if-else statement is used when we want to execute a
certain statement if a condition is true, and a different
statement if the condition is false.

• The if-else statement has the form,


if( boolean_expression ){
statement1;
statement2;
. . .
}
else{
statement3;
statement4;
. . .
}
The if-else statement:
Flowchart
The if-else statement:
Sample Code Snippet
int grade = 68;

if( grade > 60 )


[Link]("Congratulations!");
else
[Link]("Sorry you failed");

___________________________________________________________________

int grade = 68;

if( grade > 60 ){


[Link]("Congratulations!");
[Link]("You passed!");
}
else{
[Link]("Sorry you failed");
}
The if-else statement:
Coding Guidelines
1. To avoid confusion, always place the statement or statements of
an if or if-else block inside brackets {}.
2. 2. You can have nested if-else blocks. This means that you can
have other if-else blocks inside another if-else block.
For example,
if( boolean_expression ){
if( boolean_expression ){
//some statements here
}
}
else{
//some statements here
}
The if-else-else if statement
• The statement in the else-clause of an if-else block
can be another if-else structures. This cascading
of structures allows us to make more complex
selections.

• The if-else if statement has the form,


if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;
The if-else-else if statement

• Note:
– You can have many else-if blocks after an
if-statement.
– The else-block is optional and can be
omitted.
The if-else-else if statement:
Flowchart
The if-else-else if statement:
Sample Code Snippet
int grade = 68;

if( grade > 90 ){


[Link]("Very good!");
}
else if( grade > 60 ){
[Link]("Very good!");
}
else{
[Link]("Sorry you failed");
}
Common Errors when using the if-
else statements
1. The condition inside the if-statement does not
evaluate to a boolean value. For example,
//WRONG
int number = 0;
if( number ){
//some statements here
}
The variable number does not hold a boolean
value.

2. Writing elseif instead of else if.


Common Errors when using the if-
else statements
3. Using = instead of == for comparison.
For example,
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}

This should be written as,


//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
Sample Program
1 public class Grade {
2 public static void main( String[] args )
3 {
4 double grade = 92.0;
5 if( grade >= 90 ){
6 [Link]( "Excellent!" );
7 }
8 else if( (grade < 90) && (grade >= 80)){
9 [Link]("Good job!" );
10 }
11 else if( (grade < 80) && (grade >= 60)){
12 [Link]("Study harder!" );
13 }
14 else{
[Link]("Sorry, you
failed.");
15

16 }
17 }
18 }
The switch-statement
• Another way to indicate a branch is through the
switch keyword.
• The switch construct allows branching on multiple
outcomes.
• The switch statement has the form,
switch( switch_expression ){
case case_selector1:
statement1;//
statement2;//block 1
break;
case case_selector2:
statement1;//
statement2;//block 2
break;
:
default:
statement1;//
statement2;//block n}
The switch-statement

• where,
– switch_expression
• is an integer or character expression
– case_selector1, case_selector2 and so on,
• are unique integer or character constants.
• When a switch is encountered,
– Java first evaluates the switch_expression, and jumps
to the case whose selector matches the value of the
expression.
– The program executes the statements in order from
that point on until a break statement is encountered,
skipping then to the first statement after the end of
the switch structure.
– If none of the cases are satisfied, the default block is
executed. Take note however, that the default part is
optional.
The switch-statement

• NOTE:
– Unlike with the if statement, the multiple statements are
executed in the switch statement without needing the
curly braces.
– When a case in a switch statement has been matched, all
the statements associated with that case are executed.
Not only that, the statements associated with the
succeeding cases are also executed.
– To prevent the program from executing statements in the
subsequent cases, we use a break statement as our last
statement.
The switch-statement:
Flowchart
The switch-statement:
Sample Program
1 public class Grade {
2 public static void main( String[] args )
3 {
4 int grade = 92;
5 switch(grade){
6 case 100:
7 [Link]( "Excellent!" );
8 break;
9 case 90:
10 [Link]("Good job!" );
11 break;
12 case 80:
13 [Link]("Study harder!" );
14 break;
15 default:
16 [Link]("Sorry, you failed.");
17 }
18 }
19 }
The switch-statement:
Coding Guidelines
1. Deciding whether to use an if statement or a switch
statement is a judgment call. You can decide which to
use, based on readability and other factors.

2. An if statement can be used to make decisions based


on ranges of values or conditions, whereas a switch
statement can make decisions based only on a single
integer or character value. Also, the value provided to
each case statement must be unique.
Repetition Control Structures

• Repetition control structures


– are Java statements that allows us to
execute specific blocks of code a number
of times.

• Types:
– while-loop
– do-while loop
– for-loop
The while-loop
• The while loop is a statement or block of statements
that is repeated as long as some condition is
satisfied.

• The while statement has the form,


while( boolean_expression ){
statement1;
statement2;
. . .
}

The statements inside the while loop are executed as


long as the boolean_expression evaluates to true.
The while-loop:
Sample Program 1
int x = 0;

while (x<10) {
[Link](x);
x++;
}
The while-loop:
Sample Program 2

//infinite loop
while(true)
[Link](“hello”);
The while-loop:
Sample Program 3
//no loops
// statement is not even executed
while (false)
[Link](“hello”);
The do-while-loop
• The do-while loop is similar to the while-loop. The
statements inside a do-while loop are executed several
times as long as the condition is satisfied.

• The main difference between a while and do-while loop:


– the statements inside a do-while loop are executed at least once.
• The do-while statement has the form,
do{
statement1;
statement2;
. . .
}while( boolean_expression );
The do-while-loop:
Sample Program 1

int x = 0;

do {
[Link](x);
x++;
}while (x<10);
The do-while-loop:
Sample Program 2

//infinite loop
do{
[Link](“hello”);
} while (true);
The do-while-loop:
Sample Program 3

//one loop
// statement is executed once
do
[Link](“hello”);
while (false);
The do-while-loop:
Coding Guidelines
1. Common programming mistakes when using
the do-while loop is forgetting to write the
semi-colon after the while expression.
do{
...
}while(boolean_expression) //WRONG-
>forgot semicolon ;

2. Just like in while loops, make sure that your


do-while loops will terminate at some point
The for-loop
• The for loop, like the previous loops, allows
execution of the same code a number of times.

• The for loop has the form,


for(InitializationExpression;LoopCondition;StepExpression)
{
statement1;
statement2;
. . .
}

where,
– InitializationExpression -initializes the loop variable.
– LoopCondition - compares the loop variable to some
limit value.
– StepExpression - updates the loop variable.
The for-loop:
Sample Program
int i;
for( i = 0; i < 10; i++ ){
[Link](i);
}

int i = 0;
while( i < 10 ){
[Link](i);
i++;
}
• The code shown above is equivalent to the following
while loop.
Summary

• Decision Control Structures


– if
– if-else
– if – else if
– switch
• Repetition Control Structures
– while
– do-while
– for
Getting Input from the Keyboard

– JOptionPane class
• graphical user interface
• The Java Application Programming
Interface (API) contains hundreds of
predefined classes that you can use in
your programs. These classes are
organized into what we call packages.

• Packages contain classes that have


related purpose.
Sample Program
• The statement,
public class GetInputFromKeyboard {

means we declare a class named


GetInputFromKeyboard

public static void main( String[] args ){


• The next statement declares the main
method.
Sample Program

• The statement, String name = "";

declares a String variable with identifier


name.

The next statement, [Link]("Please Enter Your Name:");


outputs a String on the screen asking for the
user's name
Using JoptionPane Class

• Another way to get input from the user


is by using the JOptionPane class which
is found in the [Link] package.

• JOptionPane makes it easy to pop up a


standard dialog box that prompts users
for a value or informs them of
something.
Methods/Dialogs

1) showMessageDialog (Show Information)


It displays a message to the user with an OK
button.

Sample:
[Link](null, "Hello, World!");

142
Methods/Dialogs

2) showInputDialog (Get Information)


It pops up a box for the user to type something.
Note: It always returns text as a String.

Sample:
String name = [Link]("What is your name?");

143
Methods/Dialogs

showConfirmDialog(show Confirmation)
It is use for Yes / No / Cancel choices.

Sample:
int result = [Link](null,"Do you want
to continue?");

Return values:
• JOptionPane.YES_OPTION
• JOptionPane.NO_OPTION
• JOptionPane.CANCEL_OPTION
144
Handling Numbers (Conversion)

Because showInputDialog returns a String, you


must convert it to a number if you want to do
math.

Sample:
String input = [Link]("Enter
your age:");int age = [Link](input);

// Converts String to int


145
Sample Program
1 import [Link];

2 public class GetInputFromKeyboard {

3 public static void main( String[] args ){


4 String name = "";
5 name=[Link](“Please enter your
name");
6 String msg = "Hello " + name + "!";
7 [Link](null, msg);
8 }
9}
Sample Program Output
Sample Program

• The statement,
import [Link];

indicates that we want to import the


class JOptionPane from the [Link]
package.

• This can also written as,


import [Link].*;
Sample Program
• The statement,
name=[Link](“Please enter your name");

creates a JOptionPane input dialog, which


will display a dialog with a message, a
textfield and an OK button as shown in the
figure.
• This returns a String which we will save in the
name variable.
Sample Program

• The statement,
String msg = "Hello " + name + "!";

creates the welcome message, which


we will store in the msg variable.
Sample Program

• The statement,
[Link](null, msg);

displays a dialog which contains a


message and an OK button.

You might also like