Introduction To Java Programming: Week 2
Introduction To Java Programming: Week 2
Chapter 2
Week 2
Conversion b/w Primitive Data Types
• Value’s data type must be compatible with variable’s data type
• Java performs some conversions between data types automatically
• Java does not automatically perform any conversion that can result in
the loss of data
int x;
double y = 2.5;
x = y;
• Java compiler gives an error message “possible loss of precision” as
we are trying to store double value in an int variable
Conversion b/w Primitive Data Types
• Java allows the following assignment:
int x;
short y = 2;
x = y;
• Why?
Conversion b/w Primitive Data Types
import java.util.Scanner;
The Scanner Class
• Scanner objects work with System.in
• To create a Scanner object:
Scanner keyboard = new Scanner (System.in);
The Scanner Class
• Scanner class methods are listed in Table 2-17 in the text.
• See example: Payroll.java
Output given by InputProblem.java
CorrectedInputProblem.java
CorrectedInputProblem.java
Output given by CorrectedInputProblem.java
Dialog Boxes
• A dialog box is a small graphical window that displays a message to
the user or requests input.
• A variety of dialog boxes can be displayed using the JOptionPane
class.
• Two of the dialog boxes are:
• Message Dialog - a dialog box that displays a message.
• Input Dialog - a dialog box that prompts the user for input.
The JOptionPane Class
• The JOptionPane class is not automatically available to your Java
programs.
• The following statement must be before the program’s class header:
import javax.swing.JOptionPane;
• This statement tells the compiler where to find the JOptionPane
class.
The JOptionPane Class
The JOptionPane class provides methods to
display each type of dialog box.
Message Dialogs
• JOptionPane.showMessageDialog method
is used to display a message dialog.
JOptionPane.showMessageDialog(null, "Hello World");
// Store 10 in sVar.
short sVar = Short.parseShort("10");
int number;
String str;
str = JOptionPane.showInputDialog(
"Enter a number.");
number = Integer.parseInt(str);
Reading a double with an Input Dialog
double price;
String str;
str = JOptionPane.showInputDialog(
"Enter the retail price.");
price = Double.parseDouble(str);
if (coldOutside)
{ Is it cold Yes
wearCoat(); outside?
wearHat(); Wear a coat.
wearGloves();
Wear a hat.
}
Wear gloves.
Note the use of curly
braces to block several
statements together.
Relational Operators
• In most cases, the boolean expression, used by the
if statement, uses relational operators.
Expression Meaning
x > y Is x greater than y?
x < y Is x less than y?
x >= y Is x greater than or equal to y?
x <= y Is x less than or equal to y.
x == y Is x equal to y?
x != y Is x not equal to y?
if Statements and Boolean Expressions
if (x > y)
System.out.println("X is greater than Y");
if(x == y)
System.out.println("X is equal to Y");
if(x != y)
{
System.out.println("X is not equal to Y");
x = y;
System.out.println("However, now it is.");
}
Example: AverageScore.java
Programming Style and if Statements
is functionally equivalent to
No semicolon here.
Semicolon ends statement here.
Block if Statements
• Conditionally executed statements can be grouped
into a block by using curly braces {} to enclose
them.
• If curly braces are used to group conditionally
executed statements, the if statement is ended by
the closing curly brace.
if (expression)
{
statement1;
statement2;
} Curly brace ends the statement.
Block if Statements
• Remember that when the curly braces are not used, then only the next
statement after the if condition will be executed conditionally.
if (expression)
statement1;
statement2;
statement3;
Only this statement is conditionally executed.
Flags
• A flag is a boolean variable that monitors some condition in a
program.
• When a condition is true, the flag is set to true.
• The flag can be tested to see if the condition has changed.
if (average > 95)
highScore = true;
char c = ′A′;
if(c < ′Z′)
System.out.println("A is less than Z");
if-else Statements
• The if-else statement adds the ability to conditionally execute
code when the if condition is false.
if (expression)
statementOrBlockIfTrue;
else
statementOrBlockIfFalse;
• See example: Division.java
if-else Statement Flowcharts
No Yes
Is it cold
outside?
No Yes
Is it cold
outside?
Wear shorts.
No Is it Yes
snowing?
wearJacket();
}
if-else-if Statements
if (expression_1)
{ If expression_1 is true these statements are
statement; executed, and the rest of the structure is ignored.
statement;
etc.
}
Otherwise, if expression_2 is true these statements are
else if (expression_2)
executed, and the rest of the structure is ignored.
{
statement;
statement;
etc.
}
These statements are executed
Insert as many else ififclauses
none of as the
necessary
expressions
else above are true.
{
if-else-if Statements
• Nested if statements can become very complex.
• The if-else-if statement makes certain types of nested decision
logic simpler to write.
• Care must be used since else statements match up with the
immediately preceding unmatched if statement.
• See example: TestResults.java
if-else-if Flowchart
Logical Operators
• Java provides two binary logical operators (&& and
||) that are used to combine boolean expressions.
• Java also provides one unary (!) logical operator to
reverse the truth of a boolean expression.
Logical Operators
Operator Meaning Effect
Connects two boolean expressions into one. Both
&& AND expressions must be true for the overall expression to
be true.
Connects two boolean expressions into one. One or
both expressions must be true for the overall
|| OR
expression to be true. It is only necessary for one to be
true, and it does not matter which one.
The ! operator reverses the truth of a boolean
expression. If it is applied to an expression that is
! NOT
true, the operator returns false. If it is applied to an
expression that is false, the operator returns true.
The && Operator
• The logical AND operator (&&) takes two operands that must
both be boolean expressions.
• The resulting combined expression is true if (and only if) both
operands are true.
• See example: LogicalAnd.java
Expression 1 !Expression1
true false
false true
Order of Precedence
• The ! operator has a higher order of precedence than the && and ||
operators.
• The && and || operators have a lower precedence than relational
operators like < and >.
• Parenthesis can be used to force the precedence to be changed.
Order of Precedence
Order of
Operators Description
Precedence
1 (unary negation) ! Unary negation, logical NOT
2 * / % Multiplication, Division, Modulus
3 + - Addition, Subtraction
• Example: IncrementDecrement.java
Differences Between Prefix and Postfix
• When an increment or decrement are the only operations in a
statement, there is no difference between prefix and postfix notation.
• When used in an expression:
• prefix notation indicates that the variable will be incremented or
decremented prior to the rest of the equation being evaluated.
• postfix notation indicates that the variable will be incremented or
decremented after the rest of the equation has been evaluated.
• Example: Prefix.java
The while Loop
• Java provides three different looping structures.
• The while loop has the form:
while(condition)
{
statements;
}
• While the condition is true, the statements will execute repeatedly.
• The while loop is a pretest loop, which means that it will test the
value of the condition prior to executing the loop.
The while Loop
• Care must be taken to set the condition to false somewhere in the
loop so the loop will end.
• Loops that do not end are called infinite loops.
• A while loop executes 0 or more times. If the condition is false, the
loop will not execute.
• Example: WhileLoop.java
The while loop Flowchart
true
boolean
statement(s)
expression?
false
Infinite Loops
• In order for a while loop to end, the condition must become false.
The following loop will not end:
int x = 20;
while(x > 0)
{
System.out.println("x is greater than 0");
}
• The variable x never gets decremented so it will always be greater
than 0.
• Adding the x-- above fixes the problem.
Infinite Loops
• This version of the loop decrements x during each
iteration:
int x = 20;
while(x > 0)
{
System.out.println("x is greater than 0");
x--;
}
Block Statements in Loops
• Curly braces are required to enclose block statement while loops. (like
block if statements)
while (condition)
{
statement;
statement;
statement;
}
The while Loop for Input Validation
• Input validation is the process of ensuring that user input is valid.
System.out.print("Enter a number in the " +
"range of 1 through 100: ");
number = keyboard.nextInt();
// Validate the input.
while (number < 1 || number > 100)
{
System.out.println("That number is invalid.");
System.out.print("Enter a number in the " +
"range of 1 through 100: ");
number = keyboard.nextInt();
}
• Example: SoccerTeams.java
The do-while Loop
• The do-while loop is a post-test loop, which means it will execute
the loop prior to testing the condition.
• The do-while loop (sometimes called called a do loop) takes the
form:
do
{
statement(s);
}while (condition);
• Example: TestAverage1.java
The do-while Loop Flowchart
statement(s)
true
boolean
expression?
false
The for Loop
• The for loop is a pre-test loop.
• The for loop allows the programmer to initialize a
control variable, test a condition, and modify the
control variable all in one line of code.
• The for loop takes the form:
for(initialization; test; update)
{
statement(s);
}
• See example: Squares.java
The for Loop Flowchart
boolean true
statement(s) update
expression?
false
The Sections of The for Loop
• The initialization section of the for loop allows the loop to initialize
its own control variable.
• The test section of the for statement acts in the same manner as the
condition section of a while loop.
• The update section of the for loop is the last thing to execute at the
end of each loop.
• Example: UserSquares.java
The for Loop Initialization
• The initialization section of a for loop is optional; however, it is
usually provided.
• Typically, for loops initialize a counter variable that will be tested by
the test section of the loop and updated by the update section.
• The initialization section can initialize multiple variables.
• Variables declared in this section have scope only for the for loop.
The Update Expression
• The update expression is usually used to increment or decrement the
counter variable(s) declared in the initialization section of the for
loop.
• The update section of the loop executes last in the loop.
• The update section may update multiple variables.
• Each variable updated is executed as if it were on a line by itself.
Modifying The Control Variable
• You should avoid updating the control variable of a for loop within
the body of the loop.
• The update section should be used to update the control variable.
• Updating the control variable in the for loop body leads to hard to
maintain code and difficult debugging.
Multiple Initializations and Updates
• The for loop may initialize and update multiple variables.
for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2)
{
statement(s);
}
• Note that the only parts of a for loop that are mandatory are the
semicolons.
for(;;)
{
statement(s);
} // infinite loop