Java Programming Language
Java Programming Language
History of Java
3
Java, Web, and Beyond
• Java can be used to develop Web
applications.
• Java Applets
• Java Web Applications
• Java can also be used to develop
applications for hand-held devices such as
Palm and cell phones
4
https://www.invensis.net/blog/applications-java-p
ogramming-language/
https://spectrum.ieee.org/the-top-programming-languages-2023#toggle-gdpr
http://www.tiobe.com/tiobe-index/
What will you need to create a java program
11
Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.
12
Creating, Compiling, and Running Programs
Result
13
If runtime errors or incorrect result
animation
15
animation
16
animation
17
How to compile in java :
https://netbeans.org/kb/docs/java/quickstart.html
20
Layout of a Simple Java Program
import <name_of_package>;
Anything inside the double quote is printed exactly as given when the
program is run.
Ex. System.out.println(“Hello World”);
When a variable name appear inside the parenthesis after println and not in
double quote the content of the variable is printed.
Ex. System.out.println(sum);
SYNTAX
System.out.println(Item_1 + Item_2 + ... + Last_Item);
EXAMPLE
System.out.println("Welcome to Java.");
System.out.println(“The sum of two numbers is = " +
(firstnumber+secondnumber);
Sample Program #1
Output:
Hello World
Sample Program #2
public class word{
public static void main(String[] args){
System.out.println(" J A V V A ");
System.out.println(" J A A V V A A ");
System.out.println(" J J A A A V V A A A ");
System.out.println(" J J A A V A A ");
}
}
Lab Activity 1:
28
Program Output
Identifiers - are used for naming variables, constants, methods, classes, and
packages
ex. main, input, n1,n2, and sum
Initializing variables
Syntax:
Single variable declaration
data_type variable_name = expression;
ex. int number = 3;
Multiple variable declaration
data_type variable_name1, variable_name2,…;
ex. double number1 =3, number2=4 , sum=0;
Determine whether statement is a valid variable Write Valid if the statement is a valid
declaration. variable declaration and if the it is
invalid give the reason why it is not a
valid variable declaration.
int x;
float double;
int _abc;
double 1num;
Int $abc;
double abc-def;
Assignment Statement
Assignment Statement is a way to change the value of a variable. In java, the
used equal sign as an assignment operator. An assignment statement always
consists of a variable on the left-hand side of the assignment operator (the
equal sign) and an expression on the right-hand side. An assignment
statement ends with a semicolon. The expression on the right-hand side of
the equal sign may be a variable, a number, or a more complicated expression
made up of variables, numbers, operators, and method invocations. An
assignment statement instructs the computer to evaluate (that is, to compute
the value of) the expression on the right-hand side of the equal sign and to set
the value of the variable on the left-hand side equal to the value of that
expression.
SYNTAX
Variable = Expression;
EXAMPLE
distance = rate * time;
count = count + 2;
Data Types
animation
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}
35
animation
// Assign a radius
radius = 20;
allocate memory
// Compute area for area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}
36
animation
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}
37
animation
// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}
38
animation
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius
"+
radius + " is " + area);
}
}
39
Concatenation
The first plus sign is used to concatenate the first string (the
sum of two numbers is) to the sum of num1 and num2.
Program Output
43
Naming Conventions, cont.
• Class names:
– Capitalize the first letter of each word in
the name. For example, the class name
ComputeArea.
• Constants:
– Capitalize all letters in constants, and use
underscores to connect words. For
example, the constant PI and
MAX_VALUE
44
Proper Indentation and Spacing
• Indentation
– Indent two spaces.
• Spacing
– Use blank line to separate segments of the code.
45
Block Styles
Use end-of-line style for braces.
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
46
Arithmetic Operations
Precedence of Arithmetic Operator
System.out.println(5+4-3*2/1); 3
System.out.println(5-4+6/2*1); 4
System.out.println((5+(4-3))*(2/1)); 12
System.out.println(5%3+(4/2*1)); 4
Arithmetic and Java Expression
𝟐
Algebra: Area = 𝝅 𝒓
Java: Area = 3.1416*r*r ;
Algebra: c=
Java: c = Math.sqrt(a*a-b*b);
volume_of_sphere =
4.0/3.0*Math.pi*r*r*r;
a = Math.sqrt(b*b+c*c-2*b*c*Math.cos(angle*Math.PI/180);
1. Write a program that convert a temperature in
Degree Celsius to Degree Fahrenheit. Given
temperature = 37°.
F=
n1= input.nextInt();
nextInt is method that reads one int value typed on the keyboard.
Aside form the method nextInt() you can also use the
methods next(), nextByte(), nextShort(), 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 input = new Scanner(System.in);
double d = input.nextDouble();
57
Program Example 1
import java.util.Scanner;
public class AreaCircle{
public static void main(String[] args){
double pi=3.1416;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number for radius");
double radius = input.nextDouble();
double area = radius * radius * pi;
System.out.println("The area for circle of the radius " + radius + " is " +
area);
}
}
import java.util.Scanner;
public class AreaRectangle{
public static void main(String[] args){
double length=0, width=0, area=0;
Scanner input = new Scanner(System.in);
System.out.println("Enter the length and width");
length = input.nextDouble();
width = input.nextDouble();
area = length * width;
System.out.println("The area of the rectangle is” + area);
}
}
Series Rt = R1+R2+R3
Parallel
import java.util.Scanner;
public class Electrical {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double r1,r2, r3,r4, r5, r6;
double totalresistance;
System.out.println("Enter the value of each resitor:");
r1=input.nextDouble();
r2=input.nextDouble();
r3=input.nextDouble();
r4=input.nextDouble();
r5=input.nextDouble();
r6=input.nextDouble();
totalresistance = r1+r2+((r4+r5+r6)*r3)/(r3+r4+r5+r6);
System.out.println("The total resistance is: "+ totalresistance);
}
}
More Sample for ME
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double density,height, pressure;
System.out.print("Enter the density of the water: ");
density = input.nextDouble();
System.out.print("Enter the height of the cylindrical tank: ");
height = input.nextDouble();
pressure=density*height/144.0;
System.out.println("The pressure at the bottom of the tank is: "+pressure);
}
}
More Sample for IE
66
import java.util.Scanner;
Write a program that will input a 3 digit number and display the digits together with
their digit location.
import java.util.Scanner;
public class data{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-digit number: ");
int number = input.nextInt();
int hdreds = number/100;
int tens = (number-hdred*100)/10;
int ones = (number-hdred*100 – tens*10);
System.out.println("the hundreds digit is " + hdreds);
System.out.println("the tens digit is " + tens);
System.out.println("the ones digit is " + ones);
}
}
import java.util.Scanner;
public class data{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-digit number: ");
int number = input.nextInt();
int ones = number%10;
int tens = number/10%10;
int hdreds = number/100;
System.out.println("the hundreds digit is " + hdreds);
System.out.println("the tens digit is " + tens);
System.out.println("the ones digit is " + ones);
}
}
Write a program that will input hours and display its
equivalent in Years, Days and Hours.
Sample Output:
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter hours: ");
int hours = input.nextInt();
int years = hours/8766;
int yearsremain = hours%(8766);
int days = yearsremain/24;
int daysremain = yearsremain%(24);
System.out.println("There are " + years + " years, " + days + " days and " +
daysremain + " hours in " + hours + " hours");
}
}
import java.util.Scanner;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter hours: ");
int hours = input.nextInt();
int years = hours/8766;
int yearsremain = hours%(8766);
int days = yearsremain/24;
int daysremain = yearsremain%(24);
System.out.println("There are " + years + " years, " + days + "
days and " + daysremain + " hours in " + hours + " hours");
}
}
Midterm
Algorithm
Algorithm – a procedure for solving a problem in terms of the actions to
execute and the order in which these actions execute
– solution to a problem
Sample Algorithm for Adding two numbers A Java Program for adding two numbers
Example
if(a>b){
if(a>c){
System.out.println("The largest is" + a);
}else{
System.out.println("The largest is" + c);
}
}else if(b>c){
System.out.println("The largest is" + b);
}else{
System.out.println("The largest is" + c);
Selection = 1 ?
C= 2*pi*r A= pi*r*r
Write C Write A
End
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter the radius");
int radius = input.nextInt();
System.out.println("Enter the selection");
int selection = input.nextInt();
if(selection ==1){
double C = 2*Math.PI*radius;
System.out.println("The circumference "+ C);
}else{
double A = Math.PI*radius*radius;
System.out.println("The Area "+ A);
}
}
Draw a flow chart that will input
Start radius and selection. If selection is
equal to 1 it will display the
A
circumference of the circle, if 2 it
will display the area of the circle. If
Read radius not it will display Try Another
Read selection Number.
Selection = 2?
Selection = 1 ?
A= pi*r*r
C= 2*pi*r
A End
import java.util.Scanner;
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter the radius");
int radius = input.nextInt();
System.out.println("Enter the selection");
int selection = input.nextInt();
if(selection ==1){
double C = 2*Math.PI*radius;
System.out.println("The circumference "+ C);
}
if(selection ==2){
double A = Math.PI*radius*radius;
System.out.println("The Area "+ A);
}
System.out.println("Try another number");
}
}
Chapter 3 Selection Statements
Selection Statements
performs block statements depending on the
condition.
If Statement
If-else Statement
Nested if-else Statement
Switch
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
100
The ‘ if ’ construct
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct
if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}
(a) (b)
103
Write a program that will input a number and display whether
the number is positive, negative or zero?
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
if(number>0) {
System.out.println("Positive");
}
if(number<0) {
System.out.println(“Negative");
}
if(number==0) {
System.out.println(“Zero");
}
}
}
Write a program that will input a number and display
whether the number is odd or even?
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
if(number%2==0) {
System.out.println("Even");
}
if(number%2!=0) {
System.out.println("Odd");
}
}
}
Write a program that will input date in mm dd yyyy
format and convert it into month dd yyyy format.
import java.util.Scanner; if(month == 8)
public class date{ System.out.print("August "+ day+ ", " + year);
public static void main(String[] arg){ if(month == 9)
Scanner input = new Scanner(System.in); System.out.print("September "+ day+ ", " + year);
System.out.println("Enter month: "); if(month == 10)
int month = input.nextInt(); System.out.print("October "+ day+ ", " + year);
System.out.println("Enter day:"); if(month == 11)
int day = input.nextInt(); System.out.print("November "+ day+ ", " + year);
System.out.println("Enter year:"); if(month == 12)
int year = input.nextInt(); System.out.print("December "+ day+ ", " + year);
System.out.println(); if(month > 12)
if(month == 1) System.out.print("Enter a number from 1-12");
System.out.print("January "+ day+ ", " + year); }
if(month == 2) }
System.out.print("February "+ day+ ", " + year);
if(month == 3)
System.out.print("March "+ day+ ", " + year);
if(month == 4)
System.out.print("April "+ day+ ", " + year);
if(month == 5)
System.out.print("May "+ day+ ", " + year);
if(month == 6)
System.out.print("June "+ day+ ", " + year);
if(month == 7)
System.out.print("July "+ day+ ", " + year);
Write a program that input 5 numbers and display
the largest number among the input numbers using
if-statements.
import java.util.Scanner;
public class highest {
public static void main(String[] args){
Scanner input = new Scanner(System.in); if(num3>largest){
int largest = -999999; largest = num3;
System.out.println(); }
System.out.print("Enter 5 numbers:"); if(num4>largest){
int num1 = input.nextInt(); largest = num4;
int num2 = input.nextInt(); }
int num3 = input.nextInt(); if(num5>largest){
int num4 = input.nextInt(); largest = num5;
int num5 = input.nextInt(); }
if(num1>largest){ System.out.println("The largest number is "+
largest = num1; largest);
} }
if(num2>largest){ }
largest = num2;
}
The ‘if else’ construct
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
if(number%2==0) {
System.out.println("Even");
}else {
System.out.println("Odd");
}
}
}
Program Output
121
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
122
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
123
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
124
animation
Trace if-else statement
Suppose score is 70.0 grade is C
125
Note
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)
126
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.
127
Common Errors
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.
This error often occurs when you use the next-line block style.
128
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
129
CAUTION
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
130
Program Output
if (a<b)
smallest = a;
largest = b;
else if(b<c)
smallest = a;
largest = c;
if (b<a)
smallest = b;
largest = a;
else if(a<c)
smallest = b;
largest = c;
if (c<a)
smallest = c;
largest = a;
else if(a<b)
smallest = c;
largest = b;
137
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random rand= new Random();
int a = rand.nextInt(10);
int b = rand.nextInt(10);
int difference = a-b;
System.out.print("What is "+a+" - "+b+" ?");
int x = input.nextInt();
if (x == difference) {
System.out.println("Correct");
}
else {
System.out.println("Incorrect");
}
}
}
Problem: Body Mass Index
BMI Interpretation
139
import java.util.Scanner;
public class ComputeBMI {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final double KILOGRAMS_PER_POUND = 0.45359237;
final double METERS_PER_INCH = 0.0254;
System.out.print("Enter weight in pounds: ");
double weight = input.nextDouble();
System.out.print("Enter height in inches: ");
double height = input.nextDouble();
double weightInKilogram = weight * KILOGRAMS_PER_POUND;
double heightInMeters = height * METERS_PER_INCH;
double bmi = weightInKilogram /(heightInMeters * heightInMeters);
System.out.printf("Your BMI is %5.2f\n", bmi);
if (bmi < 16)
System.out.println("You are seriously underweight");
else if (bmi < 18)
System.out.println("You are underweight");
else if (bmi < 24)
System.out.println("You are normal weight");
else if (bmi < 29)
System.out.println("You are overweight");
else if (bmi < 35)
System.out.println("You are seriously overweight");
else
System.out.println("You are gravely overweight");
}}
Problem: Computing Taxes
The US federal personal income tax is calculated based
on the filing status and taxable income. There are four
filing statuses: single filers, married filing jointly,
married filing separately, and head of household. The
tax rates for 2009 are shown below.
Your Status: 0
Enter your salary: 8000
146
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, gender = 'F')
false false false (age > 18) && (gender == 'F') is true, because (age
false true false > 18) and (gender == 'F') are both true.
true false false (age > 18) && (gender != 'F') is false, because
(gender != 'F') is false.
true true true
147
Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, gender = 'F')
false false false (age > 34) || (gender == 'F') is true, because (gender
false true true == 'F') is true.
true false true (age > 34) || (gender == 'M') is false, because (age >
true true true 34) and (gender == 'M') are both false.
148
Sample Program #1
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Score in Exam: ");
int exam = input.nextInt();
System.out.print("Enter Score in Quiz: ");
int quiz = input.nextInt();
if (exam>60 && quiz>60)
System.out.println("Passed");
else if (exam>60 || quiz>60)
System.out.println("Removal");
else
System.out.println("Failed");
}
}
Sample Program #1
import java.util.*;
public class Sample {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number= input.nextInt();
if(number%2==0&&number>0)
System.out.print(“The number is both positive and even");
}
}
if(number%2==0||number>0)
System.out.print(“The number is either positive or even or
both");
Problem: Body Mass Index
BMI Interpretation
151
Program Output
155
Problem #3
Write a program that will input your grade and determine equivalent.
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
158
switch Statement Flow Chart
status is 0
Compute tax for single filers break
status is 1
Compute tax for married file jointly break
status is 2
Compute tax for married file separatly break
status is 3
Compute tax for head of household break
default
Default actions
Next Statement
159
switch Statement Rules
The switch-expression
must yield a value of char,
switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression. case valueN: statement(s)N;
The resulting statements in the
break;
case statement are executed when
the value in the case statement default: statement(s)-for-default;
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.
160
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
case value1: statement(s)1;
of each case in order to
terminate the remainder of the break;
switch statement. If the break case value2: statement(s)2;
statement is not present, the
next case statement will be break;
executed. …
case valueN: statement(s)N;
break;
The default case, which is
default: statement(s)-for-default;
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.
161
animation
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
162
animation
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
163
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
164
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
165
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
166
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
Next statement;
167
animation
Trace switch statement
Suppose ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
168
animation
Trace switch statement
ch is 'a':
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
169
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
170
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
171
animation
Trace switch statement
switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Next statement;
172
import java.util.Scanner;
public class date{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter month: ");
int month = input.nextInt();
System.out.println("Enter day:");
int day = input.nextInt();
System.out.println("Enter year:");
int year = input.nextInt();
System.out.println();
switch (month){
case 1: System.out.print("January "+ day+ ", " + year); break;
case 2: System.out.print("February "+ day+ ", " + year); break;
case 3: System.out.print("March "+ day+ ", " + year); break;
case 4: System.out.print("April "+ day+ ", " + year); break;
case 5: System.out.print("May "+ day+ ", " + year); break;
case 6: System.out.print("June "+ day+ ", " + year); break;
case 7: System.out.print("July "+ day+ ", " + year); break;
case 8: System.out.print("August "+ day+ ", " + year); break;
case 9: System.out.print("September "+ day+ ", " + year); break;
case 10: System.out.print("October "+ day+ ", " + year); break;
case 11: System.out.print("November "+ day+ ", " + year); break;
case 12: System.out.print("December "+ day+ ", " + year); break;
default: System.out.print("Enter a number from 1-12");
}}}
Chapter 4 Loops
Loops cause program to execute the certain block of code
repeatedly until test condition is false. Loops are used in
performing repetitive task in programming. Consider
these scenarios:
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100 System.out.println("Welcome to Java!");
times System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
176
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
177
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
178
animation
179
animation
180
animation
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
181
animation
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 1 now
182
animation
183
animation
184
animation
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1
count is 2 now
185
animation
186
animation
187
do-while Loop
do {
// Loop body; Statement(s)
Statement(s);
(loop body)
} while (loop-continuation-condition);
true Loop
Continuation
Condition?
false
188
animation
189
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
Print Welcome to Java
190
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
Increase count by 1
count is 1 now
191
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
192
animation
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2)
193
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2)
Increase count by 1
count is 2 now
194
animation
int count = 0;
do{
System.out.println("Welcome to Java!");
count++;
} while (count < 2) ;
195
animation
196
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) { System.out.println(
// loop body;
"Welcome to Java!");
Statement(s);
} }
Initial-Action i=0
Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");
Action-After-Each-Iteration i++
(A) (B)
197
animation
198
animation
199
animation
200
animation
201
animation
202
animation
203
animation
204
animation
Trace for Loop, cont.
Execute adjustment statement
i now is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
205
animation
206
animation
207
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. They are rarely used in
practice, however.
for (int i = 1; i < 100; System.out.println(i++));
}
208
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.
Nevertheless, it is better to use the equivalent loop in (b)
to avoid confusion:
209
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic Error
210
Caution, cont.
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
211
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is,
you can write a loop in any of these three forms. For example, a while loop in (a) in the following
figure can always be converted into the following for loop in (b):
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
212
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.
213
public class Sample {
Write a program public static void main(String[] args) {
int x=1;
that will display the while(x<=10){
numbers from 1-10. System.out.println(x);
x++;
}}
import java.util.Scanner;
public class Sample { import java.util.Scanner;
public static void main(String[] args) { public class Sample {
int x=2; public static void main(String[] args) {
do{ for(int x=2; x<=100;x=x+2)
if(x%2==0){ System.out.println(x);
System.out.println(x); }}
x++;
}else{
x++;
}
}while(x<=100);
}}
Program Output
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
int x=2; import java.util.Scanner;
do{ public class Sample {
if(x%2==0){ public static void main(String[] args) {
System.out.println(x); for(int x=0,y=2; x!=20;x++,y=y+2)
x++; System.out.println(y);
}else{ }}
x++;
}
}while(x<=40);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("How many Hello World you want to display");
int x= input.nextInt();
for(int i=0;i<x;i++)
System.out.println(“Hello World”);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int x= input.nextInt();
for(int i=1;i<x;i++)
System.out.println(i);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println(“Enter a number");
int x= input.nextInt();
for(int i=1;i<=10;i++)
System.out.println(i*x);
}}
import java.util.*
public class Sample{
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
System.out.println("Enter two number");
int x= input.nextInt();
int y= input.nextInt();
for(int i=x;i<y;i++)
System.out.println(i);
}}
More Assignment Statement
There is a shorthand notation that combines the assignment operator (=) and
an arithmetic operator (+ , - , * , / , %).
Syntax
Variable Op = Expression
which is equivalent to
Variable = Variable Op Expression
where Op is can be + , - , * , / , %
Example
Enter a number: 6
6! = 720
6!=6*5*4*3*2*1
Edit the previous program so that it will produce this
output
Write a program that will input two numbers. The
first number will be the base and the second number
the exponent.
The program will display the base^exponent of the
number entered.
Note: Your program must not contain Math.pow().
import java.util.*;
public class Sample {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int sum=0,number;
System.out.print("How many numbers you want to ADD? ");
int x = input.nextInt();
while(x>0){
System.out.print("Enter a number: ");
number= input.nextInt();
sum=sum+number;
x--;
}
System.out.println("The sum of the numbers is:" + sum);
}}
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.
232
import java.util.Scanner;
236
import java.util.Scanner;
if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
System.out.println("Your guess is too high");
else
System.out.println("Your guess is too low");
} // End of loop
}
}
Problem: An Advanced Math Learning Tool
238
import java.util.Scanner;
public class SubtractionQuizLoop {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; // Number of questions
int correctCount = 0; // Count the number of correct answers
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = ""; // output string is initially empty
Scanner input = new Scanner(System.in);
241
import java.util.Scanner;
243
import java.util.Scanner;
public class Sample {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
for(int i =0; i<2;i++){
for(int j=0; j<3;j++)
System.out.print("*");
System.out.println();
}
}}
OUTPUT
0<2 True
(1) (2)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
0<3 True
(3) (4)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(5) (6)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
1<3 True
(7) (8)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
2<3 True
(9) (10)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(11) (12)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
3<3 False
(13) (14)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
1<2 True
(15) (16)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
0<3 True
(17) (18)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(19) (20)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(25) (26)
for(int i =0; i<2;i++){ for(int i =0; i<2;i++){
for(int j=0; j<3;j++) for(int j=0; j<3;j++)
System.out.print("*"); System.out.print("*");
System.out.println(); System.out.println();
} }
(31)
for(int i =0; i<2;i++){
for(int j=0; j<3;j++)
System.out.print("*");
System.out.println();
}
Next Statement
Edit Slide 244 by replacing for-for by
dowhile-dowhile.
public class MultiplicationTable {
/** Main method */
public static void main(String[] args) {
// Display the table heading
System.out.println(" Multiplication Table");
System.out.println("\n-----------------------------------------");
262
Opening Problem
263
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
264
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
265
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
266
Defining Methods
267
Method Signature
268
Formal Parameters
269
Actual Parameters
270
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method Invoke a method
271
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
272
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
273
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
274
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
275
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
276
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
277
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
278
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
279
animation
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
280
Write a program that will ask how many data
will be entered and display the standard
deviation of the entered data.
Factorial
Sum of 1 to N
•public class ReverseNumber {
•
• public static void main(String[] args) {
•
• //original number
• int number = 1234;
• int reversedNumber = 0;
• int temp = 0;
•
• while(number > 0){
•
• //use modulus operator to strip off the last digit
• temp = number%10;
•
• //create the reversed number
• reversedNumber = reversedNumber * 10 + temp;
• number = number/10;
•
• }
•
• //output the reversed number
• System.out.println("Reversed Number is: " + reversedNumber);
• }
•}
import java.util.*;
public class Sample {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int z=0,number,x=1,y=0;
System.out.print("enter a number");
number= input.nextInt();
do{
z=y+x;
x=x+y;
Lab Activity System.out.print(z) ;
Factors y++;
1x12=12 }while(y<number);
2X6=12 }}
base
Fibonacci
Cells
And investment