0% found this document useful (0 votes)
44 views

Introduction To Java Programming: Week 2

This document discusses primitive data type conversions in Java. It covers: - Java performs automatic widening conversions between data types but not narrowing conversions to avoid data loss. - Cast operators allow manual conversions between data types. - Integer division results in an integer, so a cast may be needed to get a decimal result. - Constants are declared with final and can only hold a single value once initialized.

Uploaded by

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

Introduction To Java Programming: Week 2

This document discusses primitive data type conversions in Java. It covers: - Java performs automatic widening conversions between data types but not narrowing conversions to avoid data loss. - Cast operators allow manual conversions between data types. - Integer division results in an integer, so a cast may be needed to get a decimal result. - Constants are declared with final and can only hold a single value once initialized.

Uploaded by

Shabana Tahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 93

Introduction to Java Programming

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

• Two types of conversions:


• Widening conversion
• Values of lower-ranked data types are stored in variables of high-ranked data types
• Java does this automatically
• Narrowing conversion
• Values of high-ranked data types are stored in variables of low-ranked data types
• Java does not do this automatically
Conversion b/w Primitive Data Types
• Cast operators
• Lets you manually convert a value
Conversion b/w Primitive Data Types
• Integer division results in an integer
int pies = 10, people = 4;
double piesPerPerson;
piesPerPerson = pies/people; (Result will be 2 instead of 2.5)

piesPerPerson = (double)pies/people; (Result will be 2.5)

piesPerPerson = pies/(double)people; (Result will be 2.5)

piesPerPerson = (double)(pies/people); (What would be the result?)


Creating Constants
• Many programs have data that does not need to be changed.
• Littering programs with literal values can make the program hard do
read and maintain.
• Replacing literal values with constants remedies this problem.
• Constants allow the programmer to use a name rather than a value
throughout the program.
• Constants also give a singular point for changing those values when
needed.
Creating Constants
• Constants keep the program organized and easier to maintain.
• Constants are identifiers that can hold only a single value.
• Constants are declared using the keyword final.
• Constants need not be initialized when declared; however, they must
be initialized before they are used or a compiler error will be
generated.
Creating Constants
• Once initialized with a value, constants cannot be changed
programmatically.
• By convention, constants are all upper case and words are separated
by the underscore character.
final int CAL_SALES_TAX = 0.725;
Scope
• Scope refers to the part of a program that has access to a variable’s
contents.
• Variables declared inside a method (like the main method) are called
local variables.
• Local variables’ scope begins at the declaration of the variable and
ends at the end of the method in which it was declared.
See example: Scope.java (This program contains an intentional error.)
Scope
The Scanner Class
• To read input from the keyboard we can use the Scanner class.
• The Scanner class is defined in java.util, so we will use the
following statement at the top of our programs:

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");

• The first argument will be discussed in Chapter 7.


• The second argument is the message that is to be
displayed.
Input Dialogs
• An input dialog is a quick and simple way to ask the user to enter
data.
• The dialog displays a text field, an Ok button and a Cancel button.
• If Ok is pressed, the dialog returns the user’s input.
• If Cancel is pressed, the dialog returns null.
Input Dialogs
String name;
name = JOptionPane.showInputDialog(
"Enter your name.");
• The argument passed to the method is the message to
display.
• If the user clicks on the OK button, name references the
string entered by the user.
• If the user clicks on the Cancel button, name references
null.
The System.exit Method
• A program that uses JOptionPane does not automatically stop
executing when the end of the main method is reached.
• Java generates a thread, which is a process running in the computer,
when a JOptionPane is created.
• If the System.exit method is not called, this thread continues to
execute.
Converting a String to a Number
• The JOptionPane’s showInputDialog
method always returns the user's input as a
String
• A String containing a number, such as “127.89,
can be converted to a numeric data type.
The Parse Methods
• Each of the numeric wrapper classes, (covered in Chapter 10) has a
method that converts a string to a number.
• The Integer class has a method that converts a string to an int,
• The Double class has a method that converts a string to a double, and
• etc.
• These methods are known as parse methods because their names
begin with the word “parse.”
The Parse Methods
// Store 1 in bVar.
byte bVar = Byte.parseByte("1");

// Store 2599 in iVar.


int iVar = Integer.parseInt("2599");

// Store 10 in sVar.
short sVar = Short.parseShort("10");

// Store 15908 in lVar.


long lVar = Long.parseLong("15908");

// Store 12.3 in fVar.


float fVar = Float.parseFloat("12.3");

// Store 7945.6 in dVar.


double dVar = Double.parseDouble("7945.6");
Reading an Integer with an Input Dialog

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);

See example: PayrollDialog.java


The if Statement
• The if statement decides whether a section of code executes or not.
• The if statement uses a boolean to decide whether the next
statement or block of statements executes.

if (boolean expression is true)


execute next statement.
Flowcharts
• If statements can be modeled as a flow chart.

if (coldOutside) Is it cold Yes


outside?
wearCoat();
Wear a coat.
Flowcharts
• A block if statement may be modeled as:

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.

Relational Operator Meaning


> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== is equal to
!= is not equal to
Boolean Expressions
• A boolean expression is any variable or calculation that
results in a true or false condition.

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

• An if statement can span more than one line;


however, it is still one statement.

if (average > 95)


grade = ′A′;

is functionally equivalent to

if(average > 95) grade = ′A′;


Programming Style and if Statements
• Rules of thumb:
• The conditionally executed statement should be on the line after the if
condition.
• The conditionally executed statement should be indented one level from the
if condition.
• If an if statement does not have the block curly braces, it is ended by the
first semicolon encountered after the if condition.
if (expression)
statement;

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;

• Later, this condition can be tested:


if (highScore)
System.out.println("That′s a high score!");
Comparing Characters
• Characters can be tested with relational operators.
• Characters are stored in memory using the Unicode character format.
• Unicode is stored as a sixteen (16) bit number.
• Characters are ordinal, meaning they have an order in the Unicode character set.
• Since characters are ordinal, they can be compared to each other.

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?

Wear shorts. Wear a coat.


Nested if Statements
• If an if statement appears inside another if statement (single or
block) it is called a nested if statement.
• The nested if is executed only if the outer if statement results in a
true condition.
• See example: LoanQualifier.java
Nested if Statement Flowcharts

No Yes
Is it cold
outside?

Wear shorts.
No Is it Yes
snowing?

Wear a jacket. Wear a parka.


Nested if Statements
if (coldOutside)
{
if (snowing)
{
wearParka();
}
else
{
wearJacket();
}
}
else
if-else Matching
• Curly brace use is not required if there is only one statement to be
conditionally executed.
• However, sometimes curly braces can help make the program more
readable.
• Additionally, proper indentation makes it much easier to match up
else statements with their corresponding if statement.
Alignment and Nested if Statements
if (coldOutside)
{
This if and if (snowing)
This if and else {
else go together.
go together.
wearParka();
}
else
{

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 Expression 2 Expression1 && Expression2


true false false
false true false
false false false
true true true
The || Operator
• The logical OR operator (||) takes two operands that
must both be boolean expressions.
• The resulting combined expression is false if (and only if)
both operands are false.
• Example: LogicalOr.java
Expression 1 Expression 2 Expression1 || Expression2
true false true
false true true
false false false
true true true
The ! Operator
• The ! operator performs a logical NOT operation.
• If an expression is true, !expression will be false.
if (!(temperature > 100))
System.out.println("Below the maximum temperature.");

• If temperature > 100 evaluates to false, then the output


statement will be run.

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

< > <= >= Less-than, Greater-than, Less-than or


4
equal to, Greater-than or equal to
5 == != Is equal to, Is not equal to
6 && Logical AND
7 || Logical NOT
= += -= Assignment and combined assignment
8 *= /= %= operators.
Comparing String Objects
• In most cases, you cannot use the relational operators to compare
two String objects.
• Reference variables contain the address of the object they represent.
• Unless the references point to the same object, the relational
operators will not return true.
• See example: StringCompare.java
• See example: StringCompareTo.java
Ignoring Case in String Comparisons
• In the String class the equals and compareTo methods are
case sensitive.
• In order to compare two String objects that might have different
case, use:
• equalsIgnoreCase, or
• compareToIgnoreCase
• See example: SecretWord.java
Variable Scope
• In Java, a local variable does not have to be declared at the beginning
of the method.
• The scope of a local variable begins at the point it is declared and
terminates at the end of the method.
• When a program enters a section of code where a variable has scope,
that variable has come into scope, which means the variable is visible
to the program.
• See example: VariableScope.java
The Conditional Operator
• The conditional operator is a ternary (three operand) operator.
• You can use the conditional operator to write a simple statement that
works like an if-else statement.
The Conditional Operator
• The format of the operators is:

BooleanExpression ? Value1 : Value2

• This forms a conditional expression.


• If BooleanExpression is true, the value of the conditional
expression is Value1.
• If BooleanExpression is false, the value of the conditional
expression is Value2.
The Conditional Operator
• Example:
z = x > y ? 10 : 5;
• This line is functionally equivalent to:
if(x > y)
z = 10;
else
z = 5;
The Conditional Operator
• Many times the conditional operator is used to supply a value.
number = x > y ? 10 : 5;
• This is functionally equivalent to:
if(x > y)
number = 10;
else
number = 5;
• See example: ConsultantCharges.java
The Increment and Decrement Operators
• There are numerous times where a variable must simply be
incremented or decremented.
number = number + 1;
number = number – 1;

• Java provide shortened ways to increment and decrement a variable’s


value.
• Using the ++ or -- unary operators, this task can be completed
quickly.
number++; or ++number;
number--; or --number;

• 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

• If left out, the test section defaults to true.


Running Totals
• Loops allow the program to keep running totals while evaluating data.
• Imagine needing to keep a running total of user input.
• Example: TotalSales.java
Logic for Calculating a Running Total
Sentinel Values
• Sometimes the end point of input data is not known.
• A sentinel value can be used to notify the program to stop acquiring input.
• If it is a user input, the user could be prompted to input data that is not normally
in the input data range (i.e. –1 where normal input would be positive.)
• Programs that get file input typically use the end-of-file marker to stop acquiring
input data.
• Example: SoccerPoints.java
Nested Loops
• Like if statements, loops can be nested.
• If a loop is nested, the inner loop will execute all of its iterations for
each time the outer loop executes once.
for(int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
loop statements;

• The loop statements in this example will execute 100 times.


• Example: Clock.java
The break Statement
• The break statement can be used to abnormally terminate a loop.
• The use of the break statement in loops bypasses the normal
mechanisms and makes the code hard to read and maintain.
• It is considered bad form to use the break statement in this manner.
The continue Statement
• The continue statement will cause the currently executing iteration
of a loop to terminate and the next iteration will begin.
• The continue statement will cause the evaluation of the condition
in while and for loops.
• Like the break statement, the continue statement should be
avoided because it makes the code hard to read and debug.
Deciding Which Loops to Use
• The while loop:
• Pretest loop
• Use it where you do not want the statements to execute
if the condition is false in the beginning.
• The do-while loop:
• Post-test loop
• Use it where you want the statements to execute at least
one time.
• The for loop:
• Pretest loop
• Use it where there is some type of counting variable that
can be evaluated.

You might also like