Java Programming - Course 1
Java Programming - Course 1
Course 1
Algorithm:
Step-by-step problem-solving process
3
What Is Programming and Program Development Life Cycle ?
• Step 2: Implement the algorithm
– Implement the algorithm in code
– Verify that the algorithm works
• Step 3: Maintenance
– Use and modify the program if the problem domain changes
4
Example
• Write a program to find the Area of a rectangle
Input :
Rectangle Length , Rectangle Width.
Processing :
Area = Rect Length * Rect Width.
Output :
Print Out The area.
5
To sum It up…….
Then
Think Write Code
6
See you Next Video
7
Java Programming For Beginners
Course 1
10
Java Programming For Beginners
Course 1
12
Processing a Java Program
Create/Modify Source Code
Result
13
Programming Errors
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result
14
Comments
• /*
Mulitple Lines
• */ to comment multiple lines
15
Java Programming For Beginners
Course 1
17
Interacting With User: Displaying Messages on Screen
18
See you Next Video
19
Java Programming For Beginners
Course 1
Accepting Input From
User
Part 2
Java Programming For Beginners
Course 1
Receiving Input From
User
Java Data Types
Character or small signed: -128 to 127
char 1byte
integer. unsigned: 0 to 255
22
Interacting With User: Accept Input From User
• A variable is a location in the computer’s memory where a value can be stored for use by a program.
• All variables must be declared with a name and a data type before they can be used in a program.
• Declaration : DataType Identifier
23
Example 1
• Write a program to find the Area of a rectangle
Input :
Rectangle Length , Rectangle Width.
Processing :
Area = Rect Length * Rect Width.
Output :
Print Out The area.
24
Working With Variable
area 50
Scanner input = new Scanner(System.in);
Length = input.nextInt();
Width = input.nextInt();
25
Example 2
• Write a program to find the perimeter and area of a
square
The perimeter and area of the square are given by the following formulas:
perimeter = Side Length * 4
area = Side Length * Side Length
Input:
Square Side Length
Processing:
perimeter = Side Length * 4
area = Side Length * Side Length
Output:
Print Out The Perimeter and Area.
26
See you Next Video
27
Java Programming For Beginners
Course 1
Arithmetic Operators – Part
2
Arithmetic Operations
+ Addition 34 + 1 35
% Remainder 20 % 3 2
29
Precedence of arithmetic operations
31
Precedence of arithmetic operations
• ? = 1 + 2 * (3 + 4)
32
Data Type of an Arithmetic Expression
• Data type of an expression depends on the type of its operands
– Data type conversion is done by the compiler
33
Increment and Decrement Operators
• Examples :
++K , K++ k= K+1
--K , K-- K= K-1
34
Increment and Decrement Operators
• If the value produced by ++ or – – is not used in an expression, it does not matter whether it is a
pre or a post increment (or decrement).
• When ++ (or – –) is used before the variable name, the computer first increments (or
decrements) the value of the variable and then uses its new value to evaluate the expression.
• When ++ (or – –) is used after the variable name, the computer uses the current value of the
variable to evaluate the expression, and then it increments (or decrements) the value of the
variable.
x = 5;
Print(++x);
x = 5;
35
Print (x++);
special assignment statements
+= , -= , *= , /= , %=
• Example:
X +=5 ; means x = x + 5;
x *=10; means x = x * 10;
x /=5; means x = x / 5;
36
See you Next Video
37
Java Programming For Beginners
Course 1
Selection - IF Statement
Control Statements
• Normally, statements in a program are executed one after the other in the order in which they’re written.
• This is called sequential execution.
• There are control statements enable you to specify that the next statement to be executed may be other than
the next one in sequence.
• This is called transfer of control.
40
Selection Statements : If Statement
• Selection statements are used to choose among alternative courses of action.
• For example, suppose the passing mark on an exam is 60. The pseudocode statement
– If student’s marks is greater than or equal to 60 Then
Print “Passed”
In Java, The syntax for the If statement
if ( grade >= 60 )
System.out.println (“Passed”);
42
Relational Expression and Relational Operators
• Relational expression is an expression which compares 2 operands and returns a TRUE or FALSE
answer.
• Relational expressions are used to test the conditions in selection, and looping statements.
Operator Means
== Equal To
!= Not Equal To
< Less Than
<= Less Than or Equal To
43
Selection Statements : If Statement
Example : write a program that accept an integer from the user and in case this integer is even print out
the following message
“This number is even “ .
44
Selection Statements : If .. Else Statement
• The IF…Else selection statement allows you to specify that there is a course of actions are to be performed
when the condition is true and another course of actions will be executed when the condition is false.
else
Print “Failed”
In Java, The syntax for the If…Else statement
if ( Expression)
action statement ;
Else
action statement ;
if ( Expression)
{
action statements 1 ;
.
action statement n ;
}
Else
{
action statements 1 ;
.
action statement n ;
}
if ( grade >= 60 )
System.out.println("Passed“);
Else 46
Selection Statements : If – else Statement
Example : write a program that accept an integer from the user and
print out whether it is Positive or Negative number.
47
Java Programming For Beginners
Course 1
Selection - IF Statement
Nested If
• Nested If : means to write an if statement within another if statement.
Example : write a program that accept an integer number from the user ,
in case the number is Positive , check and print out whether it is Even or Odd number.
int main()
{
int number;
System.out.println("Please Enter any number “) ;
Number = input.nextInt();
if ( number >=0)
if (number % 2 == 0)
System.out.println(" This is an Even number
“);
else
System.out.println("This is an Odd number“);
} 49
IF – Else IF statement
• For example, write a program that ask the user to Enter 2 numbers and print out whether they are equal or there is one which is
main()
{
int num1, num2;
System.out.println("Enter Number 1 , Number2 “);
Num1= input.nextInt();
Num2= input.nextInt();
if ( num1 == num2 )
System.out.println ("Both Are Equal “);
else if (num1 > num2 )
System.out.println("Number 1 is greater than number 2 “);
else
System.out.println ("Number 2 is greater than number 1 “);
} 50
IF – Else IF
• For example, the following code will print
– if ( grade >= 90 )
System.out.println( "A“) ;
else if ( grade >= 80 )
System.out.println( "B”);
else if ( grade >= 70 )
System.out.println("C”);
else if ( grade >= 60 )
System.out.println("D”);
else
System.out.println("F“) ; 51
Combining more than one condition
• To combine more than one condition we use the logical operators.
52
Combining more than one condition
Example, print out the student grade according to the following formulas:
A for exam marks greater than or equal 90 and less than or equal
100 ,
B for exam marks greater than or equal 80 and less than 90 ,
C for exam marks than or equal to 70 and less than 80 ,
D for exam marks than or equal to 60, and less than 70 ,
F for all other marks.
53
Example : A company insures its Employees in the following cases:
– Employee is married.
– Employee is an Single male above 30 years of age.
– Employee is an Single female above 25 years of age.
– Conditions :
54
See you Next Video
55
Java Programming For Beginners
Course 1
Selection – Switch
Statement
Part 2
Selection statements: Switch Statement.
The switch control statement allows us to make a decision from the number of
choices
Switch (Expression )
SwitchIt(10.0);
Expression could be an integer
{
6
3
See you Next Video
64
Java Programming For Beginners
Course 1
• For example :
– To calculate the Average grade for 10 students ,
– To calculate the bonus for 10 employees or
– To sum the input numbers from the user as long as he/she enters positive numbers.
• There are three methods by way of which we can repeat a part of a program. They are:
– (a) Using a while statement
– (b) Using a do-while statement
– (C) Using a for statement
66
Opening Problem
Problem
System.out.println("Welcome to Java!");
: System.out.println("Welcome to Java!");
int count = 0;
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
while System.out.println("Welcome
(count < 100) { to Java!");
100
System.out.println("Welcome
System.out.println("Welcome to Java!"); to Java");
timescount++;
…
} …
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
67
1- The While Loop
While ( continuation condition)
{
Action statement 1 ;
Action statement 2 ;
.
.
Action statement n ;
}
69
• Example : Write a program that calculates and prints out the Average grade for 6 students .
int counter = 1;
int grade=0 , sum=0;
while (counter <=6)
{
System.out.printf(" Enter grade for student no %d" , counter);
grade = input.nextInt( );
sum += grade;
counter ++;
}
System.out.printf(" Average Grade is %f“ , sum/counter );
70
• Example : Write a program that calculates and prints out the Average grade for 5 students or
ends the program by entering -1.
71
Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts
the user to enter a number continuously until the number matches the randomly generated number. For
each user input, the program tells the user whether the input is too low or too high, so the user can choose
the next input intelligently. Here is a sample run:
72
See you Next Video
73
Java Programming For Beginners
Course 1
75
2- The do-while Loop
76
2- The do-While Loop
• Example : Write a program that calculates and prints out the Average grade for 6 students .
int counter = 1;
int grade=0 , sum=0;
do
{
System.out.println("Enter grade for student no “+ counter);
Grade= input.nextInt( );
sum += grade;
counter ++;
}
while (counter <=6) ;
77
78
See you Next Video
79
Java Programming For Beginners
Course 1
• The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) testing the loop counter to detect whether its value reached the number of repetitions desired.
(c) increasing the value of loop counter each time the program segment
within the loop has been executed.
3- The For Loop.
• Example : Write a program that calculates and prints out the Average grade for 6 students .
82
3- The For Loop.
• Example : Write a program that prints out numbers from 0 to 10;
83
3- The For Loop.
• Example : Write a program that accepts 10 numbers from the user and prints out the sum of even
numbers and the sum of odd numbers.
84
int i = 1 ; int i ;
for ( ; i <= 10 ; i + + ) for ( i = 0 ; i++ < 10 ; )
System.out.println ( i); System.out.println ( i);
int i = 1 ; int i ;
for ( ; i <= 10 ; ) for ( i = 0 ; ++ i < 10 ; )
{ System.out.println ( i);
System.out.println ( i);
i ++;
}
85
3- The For Loop.
• Example : Write a program that calculates the Factorial for any given positive number.
Ex : Factorial (5) = 5 * 4 * 3 * 2 * 1
86
Nested Loops
• Example : Write a program that calculates the Factorial for numbers from 1 to 10;
87
See you Next Video
88
Java Programming For Beginners
Course 1
Repeation – Break &
continue Statements
THE break STATEMENT
The break statement is typically used To exit early from a loop (for, while, do…while)
After the break statement, the remaining of the statements inside the loop are skipped. Then,
execution continues starting at the first statement after the loop.
92
Java Programming For Beginners
Course 1
Revision on
Conditional and loop
statements
2. ANALYSIS
INPUT & OUTPUT
Saudi Airlines permit each passenger to hold one bag. The
maximum weight allowed for the bag depends on the class of the
passenger which is: 30 Kg for First class ('F'), 25 Kg for Business
('B') and 20 Kg for Economy ('E'). If the weight of the bag
excesses the allowed one, the passenger should pay 10 SR for
each Kg.
?
Write a program that calculates the excess baggage charge for
the passenger. All input data should be read by the user. Solve
the problem using the switch statement.
Charge depends on?
Passenger PassClas Allowed
Class s Weight
(Given) (Given)
First Class ‘F’ 30 Kg
Business Class ‘B’ 25 Kg
94
2. ANALYSIS
INPUT
For a specific passenger, we want to know:
o Passenger’s Class Entered by the user.
o Baggage Weight Entered by the user.
OUTPUT
o Charge to excess weight:
• Excess weight = Actual Weight – Allowed Weight
(depending on his class)
95
5. CODE (1)
1 // import necessary libraries
2 import java.util.*;
3 public class passenger
4 {
5 // instantiate Scanner object
6 static Scanner read = new Scanner(System.in);
7 public static void main (String[] args)
8 {
9 // Declaration section
10 char passClass; // passenger’s class
11 double bagWeight; // passenger’s bag weight
12 double excessWeight = 0.0;// passenger’s excess weight
13 double charge = -1.0; // charge on excess weight
14 // Input section
15 System.out.print (“Please enter passenger’s class”);
16 passClass = read.next().charAt(0); // read passenger’s class
17 System.out.print (“Please enter passenger’s baggage weight”);
18 bagWeight = read.nextDouble(); // read baggage weight
19 // Processing section: charge depends on passClass
20 switch (passClass)
21 {
22 case ‘F’: excessWeight = bagWeight – 30;
23 break; 96
5. CODE (2)
19 // Processing section: charge depends on passClass
20 switch (passClass)
21 {
22 case ‘F’: if (bagWeight > 30)
23 excessWeight = bagWeight – 30;
24 break;
25 case ‘B’: if (bagWeight > 25)
26 excessWeight = bagWeight – 25;
27 break;
28 case ‘E’: if (bagWeight > 20)
29 excessWeight = bagWeight – 20;
30 break;
31 } //end switch
32 charge = excessWeight * 10;
33 // Output Section
System.out.printf (“Charge = %5f”, charge);
} //end main
} //end class
97
5. CODE (3)
WITH USER INPUT VALIDATION
19 // Processing section: charge depends on passClass
20 switch (passClass)
21 {
22 case ‘f’:
23 case ‘F’: if (bagWeight > 30) {excessWeight = bagWeight –
24 30;
25 charge =
26 excessWeight * 10;}
27 break;
28 case ‘b’:
29 case ‘B’: if (bagWeight > 25) {excessWeight = bagWeight –
30 25;
31 charge =
32 excessWeight * 10;}
33 break;
34 case ‘e’:
35 case ‘E’: if (bagWeight > 20) {excessWeight = bagWeight –
36 20;
37 charge = excessWeight * 10;}
38 break;
39 default: System.out.println (“Invalid passenger class”);
40 } //end switch 98
// Output Section
See you Next Video
99
Java Programming For Beginners
Course 1
• Experience has shown that the best way to develop and maintain a large program is to construct it from
smaller pieces or modules, each of which is more manageable than the original program.
• Using a function is something like hiring a person to do a specific job for you.
101
In Real Life
In Programming
Task 4
Task 1
Function ( )
Function ( )
Task 2 Task 3
Important Tips
1- Don’t try to cram the entire logic in one function. It is a very bad style of programming.
2- Instead, break a program into small units and write functions for each of these isolated subdivisions.
103
Calculate and print out The
sum and the Average of 3
student marks.
Task 4
Task 1
Get_Marks( )
Print_out ( )
Task 2 Task 3
Calc_sum( )
104 Calc_Average ( )
Functions
Function Definition
106
Java Programming For Beginners
Course 1
112
Java Programming For Beginners
Course 1
int main ()
{
int n1 , n2 , n3 ;
System.out.println("Please Enter 3 integer numbers “ );
n1= input.nextInt();
n2= input.nextInt();
n3= input.nextInt();
System.out.println(" The sum of the 3 number is “ || sum (n1, n2,n3) );
System.out.println(" The average of the 3 number is " || average (n1, n2,n3) );
}
Public static int sum (int num1 , int num2, int num3)
{
return num1+num2+num3;
}
Public static double average (int num1, int num2, int num3 )
{
return sum (num1 , num2 , num3)/3 ;
}
114
Scope of a variable
scope is the context within a program in which a variable is valid and can be used.
result = x + y;
return result; }
} }
115
Scope of a variable
Global variable: declared outside of every function definition.
– Can be accessed from any function that has no local variables with the same name. In case the
function has a local variable with the same name as the global variable ,
static Int z ; GLOBAL
int main ( )
{
{
}
}
int sum (int x , int y )
{
116
Scope of a variable
Static int x = 100 ; GLOBAL
int main ( )
{
int x= 10; Local
{
int z , x ; Local
z=100;
y=100;
x= 250;
System.out.println(" inner block " << x ;
}
}
117
See you Next Video
118
Java Programming For Beginners
Course 1
Examples:
public int Sum(int x, int y)
public int Sum(int x, int y , int z)
public double Sum(double x, double y, double z)
public int Sum(int x, double y)
public int Sum(double y, int x) 120
The following methods are incorrectly overloaded; the compiler generates an
error:
Example (1): The following methods are incorrectly overloaded because they have
the same method name and same formal parameter lists:
Example (2): Changing the names of the formal parameters, does not allow
overloading of the previous counter-example:
public void methodABC (int x, double y)
public int methodABC (int num1, double num2)
Counter-example (3): Adding the modifier static does not allow
overloading of the previous example:
public static void methodABC (int x, double y)
public int methodABC (int num1, double num2)
Note that the method type and modifiers are not part of the
overloading rules 121
See you Next Video
122
Java Programming For Beginners
Course 1
One Dimensional Arrays – Part
1
ARRAY DECLARATION
SYNTAX dataType[ ] arrayName = new datatype [intExp];
In Java, an array is an object that must be instantiated using the new operator.
arrayName is the reference variable.
dataType is the data type of the array; which is the same type of all elements in the
array.
intExp is any expression that evaluates to a positive int type.
intExp represents the size of the array: this is the number of elements in the array.
ARRAY DECLARATION
EXAMPLES
Consider the following array declaration:
int[] num = new int [5];
From the above statement:
o num is the array name Address Value Index
o num consists of 5 elements num 0 0
o The type of the elements is int 0 1
The memory layout will be as follows: 0 2
0 3
As shown, the array name points to the first element in the 0 4
array.
The five elements of the array are adjacent in the memory.
ARRAY DECLARATION
USING CONSTANTS AS SIZES
int i = 8;
int[] num = new int[i*2-1];
1
2
ARRAY DECLARATION
SPECIFYING SIZES DURING EXECUTION
It is not necessary to know the size of the array at compile
time.
During program execution, the user may be prompted to enter the size of
the array. The object (array) is then instantiated using this value.
Consider the following example:
When initializing arrays during declaration, the size of the array is determined by the
number of initial values in the initializer list within the braces.
When instantiating an array object, the initial values depend on the array type:
o For numeric types (int, double, etc…) the elements take the value zero by
default.
o For char type, the elements take the value null character (‘’).
o For boolean type, the elements take the value false.
Arrays
• Accessing array Elements
Arrayname [element index].
list[5] = 34;
131
Example - Write a program that finds the sum and the average of positive integers stored in an
array of integers.
132
See you Next Video
133
Java Programming For Beginners
Course 1
One Dimensional Arrays – Part
2
Passing Arrays as a method
Parameters
Passing Array as a parameter to a
method
To pass an array argument to a method, specify the name of the array without
any brackets.
For example, if array ids is declared as
int [] ids = new int[50];
then the method call search ( ids , 100 );
passes the reference of array salaries to method search.
Main()
{
Int [ ] employee_ids = new int[10];
Int position = Search(imployee_ids , 30);
}
Passing Array as a parameter to a
method
public static void fillArray(double[ ] list)
{
for (int i=0; i<list.length; i++)
{
System.out.println (“Enter next element: “); public static void main(String[] args)
list[i] = read.nextDouble(); {
} //end for double[] sales = new double[100];
} //end fillArray fillArray (sales);
printArray (sales);
public static void printArray(double[] list) }
{
int i;
for (i=0; i < list.length; i++)
System.out.print (list[i] + “ “);
System.out.println();
} //end of printArray
See you Next Video
137
Java Programming For Beginners
Course 1
Fahd A A+ B B-
Ahmed A+ A- C B+
Faisal C+ D A- D+
1 sales[0][0] = 15.0;
2
3 sales[1][2] = 12.0;
4 sales[2][1] = 21.0;
Output
Number of rows = 20
Number of columns = 15
INITIALIZATION
The two-dimensional array may be initialized as follows:
2 1 3
3 5 2
4 2 2
Let us initialize the elements of row #2 to 7:
int col;
for (col = 0; col < matrix[2].length; col++)
matrix[2][col] = 7;
When processing a row using a loop, the condition is “the number of columns”,
which is matrix[2].length in this example.
The number of the row is fixed, and the number of the column varies from 0
to matrix[2].length col is the loop counter.
int row;
for (row = 0; row < matrix.length; row++)
matrix[row][1] = 5;
• Example : Write a program that build a matrix of 5 rows and 3 columns . Ask the use to
enter the values for all the matrix items , print out the sum of all matrix items.
145
See you Next Video
146
Two dimensional Array as a Parameter to
Function
when declaring a two-dimensional array as a formal parameter, you can omit
the size of the first dimension, but not the second;
that is, you must specify the number of columns.