Professional Documents
Culture Documents
Fundamentals of Programming
Contents
Introduction
History of Java
Java Technology
Java Development Kit (JDK)
JDK Editions
JDK Versions
Java Runtime Environment (JRE)
Why Java?
The five phases of Java
Example Java Programs
Compiling and running java programs
Programs
Computer programs, known as software, are
instructions to the computer.
…
ADDF3 R1, R2, R3
Assembler …
1101101010011010
…
…
Programming Languages
Machine Language Assembly Language High-Level Language
Java
• Was created in 1991 and formally
announced in 1995 by James Gosling et al. of Sun
Microsystem.
class_Name
Is the name of a class. A Java class name is an identifier.
By convention class names should start with capital
letters
Java is case Sensitive
A Simple Java Program…
37
Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.
38
Compiling and Running Java programs
Using Command line
If you are using a text editor which is not specially
designed as Java IDE , java program are compiled and
run using command line.
• To Compile
Javac […\]Welcome.Java
• To Run
Java […\]Welcome
Result
Display
Most Java applications use windows or a dialog
box
We have used command window
Class JOptionPane allows us to use dialog
boxes
Displaying Text in a Message Dialog Box…
Packages
Set of predefined classes for us to use
Groups of related classes called packages
Group of all packages known as Java class library or
Java applications programming interface (Java API).
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
“Display Message",
JOptionPane.INFORMATION_MESSAGE);
44
Two Ways to Invoke the Method
There are several ways to use the showMessageDialog
method. For the time being, all you need to know are two
ways to invoke it.
One is to use a statement as shown in the example:
JOptionPane.showMessageDialog(null,
x,y,JOptionPane.INFORMATION_MESSAGE);
where x is a string for the text to be displayed, and y is a
string for the title of the message dialog box.
The other is to use a statement like this:
JOptionPane.showMessageDialog(null, x);
where x is a string for the text to be displayed.
45
import javax.swing.JOptionPane;
public class Welcome {
public static void main( String args[])
{
JOptionPane.showMessageDialog( null,
Welcome\nto\nJava\nProgramming!" );
}
}
import declarations
48
Message dialog type Icon Description
JOptionPane.ERROR_MESSAGE Displays a dialog that indicates
an error to the user.
50
Identifiers…..
datatype variableName;
53
Variable Declaration….
int x; // Declare x to be an
// integer variable;
char a; // Declare a to be a
// character variable;
Assignment Statements
After a variable is declared, you can assign a value to it by using
an assignment statement. In java, the equal sign(=) is used as the
assignment operator.
The syntax for assignment statement is as follows:
variable = expression;
55
Variable Declaration and initialization
Declaring and Initializing can be done in one step
int x = 1
String str = “Hi”;
boolean b = (1 > 2);
58
Primitive Data Type
There are around 8 primitive data types in java.
These are
byte
short
int
long
float
double
boolean
char
59
Numeric Data Type
Example:
char letter = ‘A’;
char numChar = ‘4’;
Casting
Is converting from one data type to another
63
Casting…..
Example:
double x =9.997; int n = (int) x; n is now 9
double x = 9.997; int n = (int) Math.round(x); n is
now 10
int i = 'a'; // same as int i = (int)'a'; i = 97
char c = 97; // same as char c = (char)97; c is a
int i = (int)’A’; System.out.println(i); // i is 65
Casting to the wrong type may cause compilation errors
or runtime errors.
The String Type
The char type only represents one character.
To represent a string of characters, use the data type
called String.
Exampe:
String message = “Welcome to Java”
Example:
String s = “Chapter” + 2; // s becomes Chapter2
The String Type …..
If neither of the operand is a string , the plus sign (+)
is the addition operator that adds two numbers.
The shorthand += operator can be also used for string
concatenation.
Example:
String message = “ Welcome to Java”;
message += “ and Java is fun”;
System.out.print(“ i + j is ” + (i + j));
Java Operator
Arithmetic operators
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Remainder 20 % 3 2
Java Operator ….
When performing a binary operation involving two
operands of different types, Java automatically converts
the operand based on the following rules:
1. If one of the operands is double, the other is converted
into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.
Shortcut Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
72
Increment and Decrement Operators
Operator Name Description
73
Increment and Decrement Operators
75
Java Operator…
Logical operators
&& for the logical “and” operator and
|| for the logical “or” operator
76
Java Operator…
Relational operators
== (equal),
!= (not equal)
< (less than),
> (greater than),
78
Java Operator…
Example:
80
Obtaining Input
81
Getting Input from Input Dialog Boxes
You can use the showInputDialog method in JoptionPane
class to get input at run time.
String input = JOptionPane.showInputDialog(
null,“Prompting Message”,“Dialog Title”,
JOptionPane.QUESTION_MESSAGE);
82
Two Ways to Invoke the Method
There are several ways to use the showInputDialog method. For
the time being, you only need to know two ways to invoke it.
One is to use a statement as shown in the example:
83
Converting Strings to Integers
The input returned from the input dialog box is a string.
If you enter a numeric value such as 123, it returns
“123”.
To obtain the input as a number, you have to convert a
string into a number.
To convert a string into an int value, you can use the
static parseInt method in the Integer class as follows:
int intValue = Integer.parseInt(intString);
where intString is a numeric string such as “123”.
84
Converting Strings to Doubles
To convert a string into a double value, you can use the
static parseDouble method in the Double class as
follows:
85
Getting Input Using Scanner
Java uses System.out to refer to the standard output
device , and System.in the standard input device.
87
Getting Input Using Scanner Examples
import java.util.Scanner;
public class TestScanner {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
90
Control Flows….
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
91
Control Flows….
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
92
Control Flows….
The & and | Operators
93
Control Flows
There are three basic types of program flows
Sequential
In Sequential execution statements in a program are
executed one after the other in sequence.
Selection
Selection or conditional execution executes part of the
code based on the condition.
Iteration
In iterative program flow statements inside looping
statement are executed repeatedly as long as a condition is
true
94
Selection/conditional Statement
Java has the following Conditional statements
if Conditions
if Statement
If…else Statement
if …else if…else Statement
Conditional Operators (?:)
switch Statements
95
if Statements
if (radius >= 0) {
if (booleanExpression) { area = radius * radius * PI;
statement(s); System.out.println("The area"
}
+ " for the circle of radius "
+ radius + " is " + area); }
false false
Boolean (radius >= 0)
Expression
true true
(A) (B)
96
if Statements ….
Note
Outer parentheses required Braces can be omitted if the block contains a single
statement
if ((i > 0) && (i < 10)) { Equivalent if ((i > 0) && (i < 10))
System.out.println("i is an " + System.out.println("i is an " +
+ "integer between 0 and 10"); + "integer between 0 and 10")
}
(a) (b)
97
if Statements ….
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation
error or a runtime error, it is a logic error.
98
The if...else Statement
These selection statement is used if there are exactly two selections
Syntax:
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}
99
The if...else Statement…..
true false
Boolean
Expression
Statement(s) for the true case Statement(s) for the false case
The if...else Statement, example
if (radius >= 0)
{
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else
{
System.out.println("Negative input");
}
101
Conditional Operators (?:)
Conditional statement can be used instead of if…else
statement
if (x > 0)
y = 1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
Syntax
(booleanExp) ? exp1 : exp2
102
if …else if…else Statement
if…else if…else statement is important if there are
more than two conditions.
Syntax:
if(booleanExpression1) {
statement(s);
}
else if booleanExpression2){
statement(s);
}
……
else {
statement(s);
}
103
if …else if…else Statement, example
•The following code snippet depicts how nested if else
statement is used to calculate letter grade from a score
out of 100
104
Multiple Alternative if Statements
105
Trace if-else statement
Suppose score is 70.0 The condition is false
106
Trace if-else statement…
Suppose score is 70.0 The condition is false
107
Trace if-else statement…
Suppose score is 70.0 The condition is true
108
Trace if-else statement
Suppose score is 70.0 grade is C
109
Trace if-else statement
Suppose score is 70.0 Exit the if statement
110
The else clause matches the most recent if clause in the
same block.
int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; int k = 3;
Equivalent
if (i > j) if (i > j)
if (i > k) if (i > k)
System.out.println("A"); System.out.println("A");
else else
System.out.println("B"); System.out.println("B");
(a) (b)
111
Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you must
add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
112
if …else if…else Statement, example
The example in preceding slide can be done by
using sequence of if statements
if(score>=90)
grade =‘A’
if (score>=80)
grade = “B”
if (score >=70)
grade = ‘C’
if (score>=60)
grade = ‘D’
…
113
if …else if…else Statement, example
Problem: Write a program that solves quadratic
equation
114
switch Statements
The if/else construct can be cumbersome when you have
to deal with multiple selections with many alternatives.
Example: To set up Menu System
Syntax
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
………
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
} 115
switch Statements flow chart
Case 1
St atement(s) break
Case 2
St atement(s) break
sCase 3
St atement(s) break
Case N
St atement(s) break
default
St atement(s)
Next St at ement
116
switch Statements…
The switch-expression must yield a value of char, byte,
short, or int type and must always be enclosed in
parentheses.
The value1, ..., and valueN must have the same data type
as the value of the switch-expression.
The resulting statements in the case statement are executed
when the value in the case statement matches the value of
the switch-expression.
Note that value1, ..., and valueN are constant
expressions, meaning that they cannot contain
variables in the expression, such as 1 + x.
117
switch Statements…
The keyword break is optional, but it should be used at the
end of each case in order to terminate the remainder of the
switch statement.
If the break statement is not present, the next case statement
will be executed.
The default case, which is optional, can be used to perform
actions when none of the specified cases matches the switch-
expression.
The case statements are executed in sequential order, but the
order of the cases (including the default case) does not matter.
However, it is good programming style to follow the logical
sequence of the cases and place the default case at the end.
118
switch Statements, Example
while loop
do…while loop
for loop
for each loop
120
while Loop
Syntax: int count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to
(loop body) Java!");
count++;
121
(A) (B)
while Loop….
Each loop contains a loop continuation condition, a
Boolean expression that controls the execution of the
body.
123
animation
124
animation
125
animation
126
animation
127
animation
128
animation
129
animation
130
animation
131
Controlling a loop with Confirmation Dialog
Examples:
134
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined.
You may use an input value to signify the end of the
loop. Such a value is known as a sentinel value.
Exercise:
Write a program that reads and calculates the sum of an
unspecified number of integers. The input 0 signifies the
end of the input.
do-while Loop
Syntax:
do {
Statement(s)
// Loop body; (loop body)
Statement(s);
true Loop
} while (condition); Continuation
Condition?
136
For loop
Syntax
for ( initialization; loopContinuationCondition; increment )
{
Statement (s);
}
137
For loop…
138
animation
139
animation
140
animation
141
animation
142
animation
143
animation
144
animation
145
animation
146
animation
147
animation
148
Note
The initial-action in a for loop can be a list of zero or
more comma-separated expressions.
The action-after-each-iteration in a for loop can be a list
of zero or more comma-separated statements.
Therefore, the following two for loops are correct.
for (int i = 1; i < 100; System.out.println(i++));
150
Note….
The while loop and for loop are called pre-test
loops because the continuation condition is checked
before the loop body is executed.
*
**
***
****
*****
152
Nested for loop Example
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
System.out.print("*");
System.out.println();
153
Recommendations
Use the one that is most intuitive and comfortable for you.
In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times.
A while loop may be used if the number of repetitions is
not known, as in the case of reading the numbers until the
input is 0.
A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition.
154
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error
155
Caution….
Similarly, the following loop is also wrong:
int i=0; Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct
156
break and continue Statements
Two statements, break and continue, can be used in loop
statements to provide the loop with additional control.
157
break Example
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100)
break;
}
continue Example
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if(number == 10 || number == 11)
continue;
sum += number;
}
Statement Labels and Breaking with Labels
outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
break outer;
}
}
Statement Labels and Breaking with Labels..
outer:
for(int i=1; i<10;i++){
inner:
for(int j=1; j<10; j++){
if(i*j>50)
continue outer;
}
}
For-each Loop
The basic for loop was extended in Java 5 to
make iteration over arrays and other collections
more convenient.
This newer for statement is called the enhanced
for or for-each (because it is called this in other
programming languages).
162
For-each Loop example
• The for-each loop is used to access each successive value
in a collection of values.
• Here is a loop written as both a for-each loop and a basic
for loop to add all elements of an array
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
// i indexes each element successively.
for (int i = 0; i < ar.length; i++) {
Sum += ar[i];
}
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
// d gets successively each value in ar
for (double d : ar)
{
sum += d; 163