1
Basic Concepts Of Java
Why Java?
2
1-First Step For Programming
2-Books in Data Structure & Design Pattern , …
3-Using in Mobile Development ,Backend ,Desktop app,etc..
4-White-box Testing & Test Automation (Testing)
About Java
3
• Object-oriented
• Compiled and Interpreted
• Secure
• Multi-threaded
• Garbage collected
• No support for multiple inheritance
How to use Java?
4
1-Download Java
Download Java for Windows
2-Download an IDE
Eclipse Downloads | The Eclipse Foundation
Apache NetBeans Releases
Download IntelliJ IDEA: The Capable & Ergonomic Java IDE by JetBrains
Or any other IDE
Java Hierarchy
5
• A package is a group of Classes
• Each java program contains at least one class
• Each program should include only one main method
• Class
Package
• Class
• Class
Main Method
6
• Public: anyone can access it
• Static: method can be run without creating an instance of
the class containing the main method
• Void: Method doesn’t return any value
• Main: the name of the method
• Main parameters: is an array of strings called args
Every Command in Java must end with Semicolon
8
First Java Program
Displaying Messages on Screen
9
• System is a class
• Out is a stream
• Println is a method that prints a line of text to the screen
Comments
10
• Comments are used to explain what the code is doing
Single-line vs. multi-line comments
11
Single-line Multi-line
comments comments
Exercise
12
• Write a program to print an error message to the user
“username or password is not correct, please try again.”
Exercise
13
• Write a program that prints two sentences to welcome
the user, each sentence is in a new line.
Variables
14
• Variables are containers for storing data values.
• Variable declaration: int age ;
• Variable initialization: age = 20 ;
Code Convention
15
• Variables - Functions >> camelCase
• Classes >> PascalCase
Data types
16
• Byte
• 8-bit
• Example: byte a = 10
Data types
17
• Short
• 16-bit
• Example: short s = 10000
Data types
18
• int
• 32-bit
• Example: int a = 100000
Data types
19
• long
• 64-bit
• Example: long a = 100000;
Data types
20
• float
• 32-bit
• Example: float f1 = 234.5f;
Data types
21
• double
• 64-bit
• Example: double d1 = 123.4;
Data types
22
• boolean
• Boolean represents one bit of information
• Has only two possible values [true & false]
• True = 1 , False = 0
• Example: boolean one = true
Data types
23
• char
• Used to store single characters
• Example: char letter = ‘A’;
Data types
24
• String
• Used to store more characters
• Example: String str = ‘Ahmed Ashraf’;
**Note**
25
• Final
• Used to store constants can be assigned only once
• Example: final int x = 10 ;
Data types
26
Primitive Non-Primitive(Reference)
• Limited • Not Limited
• Byte • String
• Short • Arrays
• Int • Objects
• Long
• Float
• Double
• Char
• Boolean
Exercise
27
• Write a program which creates three variables: student
name, graduation year, & letter grade. Then print the
three values.
Getting input from user
28
Exercise
29
• Write a program which takes the user name and year of
birth, and outputs a message welcoming the user and
telling him his age.
Mathematical operations
30
• Java provides a rich set of operators to use in manipulating variables. A value
used on either side of an operator is called an operand.
• Java arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulo
Exercise
31
• A student scored 45 in subject 1 and 53 in subject 2.
• Write a program that prints the total score of the two
subjects and the average score of the student in the two
subjects.
Increment & Decrement
32
• Increment is used to increase the value by one
• Decrement is used to decrease the value by one
Example:
int x = 5 ;
x=x+1;
Can be replaced with this code:
int x = 5 ;
x++ ;
Prefix & Postfix
33
• ++X & --Y are examples of prefix
• X-- & Y++ are examples of postfix
• Example 1: • Example 2:
int x = 34; int x = 34;
int y = ++x; int y = x++;
Assignment Operators 34
(+=) (-=) (*=) (/=)
int num1 = 2 ;
num2 + = num1 ;
35
Conditionals
If Statement
36
If the if statement’s condition expression evaluates to true, the block of code
inside the if statement is executed
Comparison Operators
Less than <
Greater than >
Not equal to !=
Equal to ==
Less than or equal to <=
Greater than or equal to >=
If Statement
37
If - Else Statement
If – Else If Statements
Nested if Statements
40
Combining more than one condition
! NOT Reverse the condition from true to false or
false to true
42
Switch Statement
control statement allows us to make a
Switch statement decision from the number of choices
43
If don’t match with any case .. Default case will run
Example 44
Write a program that asks the user to enter two numbers.
Then it displays the following menu, then acts accordingly:
Enter your choice:
1-Add two numbers
2-Get the Subtract of two numbers
3-Get the multiply of two numbers
(With If Statement & Switch Statement)
**The program should show an error message for invalid inputs**
45
Loops
46
Important Note
Count start from 0 in programming
For Loop
47
• The most popular looping methods
Example
48
1-Write a program that prints out numbers from 0 to 10 in ascending order
2-Write a program that prints out numbers from 0 to 10 in descending order
While Loop
49
Some times we need to repeat some tasks.
Ex: Print numbers from 1 to 100.
While Loop
50
51
Do .. While Loop
• Do at least one iteration even condition is false
Nested Loops
52
If a loop exists inside the body of another loop, it's called a nested loop
Example
53
Use the nested loop to iterate through each day of a week for 3 weeks
Break & Continue
54
1-Break Statement
The break statement is typically used to exit early from a loop ( for , while , do while)
55
2-Continue Statement
The continue statement skips the remaining statements and go to the next iteration
Example
56
Write a program to print the numbers from 1 to 10 using:
-While Loop
-For Loop
-Do…While loop
Examples
57
1-Write a program to calculate the sum of first 10 natural number.
2-Write a program that prints the sum of the even and odd integers.
3-Write a do-while loop that asks the user to enter two numbers. The numbers should be
added and the sum displayed. The loop should ask the user if he wishes to perform the
operation again. If so, the loop should repeat; otherwise it should terminate
58
Functions(Methods)
Function
59
Block of statements that perform a specific task.
Why Function ?
60
1-Avoid rewriting the same code over and over.
2-Easy maintenance for programs.
Tips
1- Function should be for only one specific task
2-Don’t write functions that are called only once.
Function Definition
61
62
63
64
Write a function that adds two integers
and returns their sum
65
66
Write a function that compares three numbers
and returns the smallest one of them
67
68
Write a function that takes three numbers and
returns their average
69
70
Write a function that takes any number of values
and returns their average
71
Function Types
72
Built-in Functions User-Defined Functions
abs (int number ) • Value returning functions : have a return type
pow (double base , double exponent ) • Ex : int sum (int x,int y);
floor (double number • Void functions : do not have a return type
sqrt (double number • Ex: void printInfo ();
…. etc.
Note:
Parameter Arguments
• In function declaration • In function call
abs method
73
Returns the absolute value of a number
ceil method
74
returns the double value that is greater than or equal to the
argument and is equal to the nearest mathematical integer
floor method
75
returns the double value that is less than or equal to the
argument and is equal to the nearest mathematical integer
round method
76
returns the closest long to the argument
sqrt method
77
Returns the square root of the number
pow method
78
used to calculate a number raise to the power of some other number
random method
79
used to calculate a number raise to the power of some other number
(random()*((max-min)+1))+min;
int r = (int) (random()*((max-min)+1))+min;
max method
80
Returns the maximum value of two values
max(3,5)
max(2,(max(3,5))
Method Overloading
81
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
82
In this example, we have three
methods withs the same name,
but three different
implementations
83
Use overloading to return the total of customer’s order.
If the order is done using delivery, the delivery cost is added to the total
If the user uses a promocode, he gets a discount of 2 USD
84
85
Scope of a variable
Local variable : declared within a function (or block)
Global variable: declared outside of every function definition.
86
Example
Calculate and print out The sum and the Average of 3 student marks.
calculateSum()
Hint:
calculateAverage()
print ()
87
Arrays
Arrays
88
An object which contains elements of a similar data type
Syntax
data_type [ ] arrayName = new data_type [ Size ]
• Data_type : the data type of the array, which is the same type of all elements in the array.
• arrayName : is the reference variable.
• new : operator for initiation array
• Size : the number of elements in the array (must be int).
Example 89
int [ ] arr = new int [ 5 ]
• int : the data type of the array.
• arr : the name of the array
• new : operator for initialization array
• 5 : the number of elements in the array
90
**Using Constants as Sizes**
91
**Using Expressions as Sizes**
92
Accessing array Elements
arrayName[index]
Example: int list[10] ;
list[5] = 20;
93
Array Initialization
• Arrays can be initialized during declaration : In this case, it is not necessary to specify the size of
the array.
• Example 1: int items [ ] = { 1 , 2 ,3,4,5 }
• Example 2 : int items [ ] = { 5 , 7 , 10 }
**Also you can use the For .. Loop to initialize it with values submitted after declaring the array**
for (int i = 0 ; i < 10 ; i++)
//process list[i];
94
95
Use Loop
96
Example
Write a program that ask the user to enter 10 Employee salaries and store them.
Write a program that ask the user to enter 10 Employee salaries and store them
then add a bonus of 10 for each employee and print out salary after adding
bonus
97
Array as a Parameter to Function
The size of the array is usually passed as a parameter to the function.
98
Example
Write a program that uses a function to search for an item within an
array
99
Two Dimensional Array
It’s look like matrix in math
For Example : to store 4 Marks for 5 students.
mark1 mark2 mark3 mark4
Std1
Std2
Std3
Std4
Std5
Two dimensional Array declaration 100
data_type [][] arrayName = new data_type [rows]
[columns]
Example
float [][] arr = new float [6] [4];
Two dimensional Array Initialization 101
arr [5] [3]=10;
10
Two dimensional Array Initialization 102
• Arrays can be initialized during declaration : In this case, it is not necessary to specify the size of
the array.
• float marks [4 ][3 ] ={{ 20,30,35},
{40,45,65},
{60,65,75},
{80,65,45}};
**Also you can use the two nested For .. Loop to initialize it with values submitted after declaring the
array**
for (int row = 0 ; row < 6;row ++)
for (int col = 0 ; col < 4 ; col++)
//process arr[row][col];
103
Example
Write a program that build a matrix of 5 rows and 3 columns As the use to enter
the values for all the matrix items print out the sum of all matrix items and print
out the sum of the diagonal items
104
Two dimensional Array as a Parameter to Function
The size of the array is usually passed as a parameter to the function.
105
Handling Exceptions
106
107
Handling Exceptions
• An exception is an object that is generated as the result of an error or an unexpected
event.
int x = 5 , y = 0 ;
System.out.println (x/y);
Error
• Java allows you to create exception handlers.
108
Handling Exceptions
• To handle an exception, you use a try statement.
try
{
(try block statements...)
}
catch (ExceptionType ParameterName)
{
(catch block statements...)
}
• A catch clause appears.
• ExceptionType :is the name of an exception class and
• ParameterName :is a variable name which will reference the exception object if the code
in the try block throws an exception.
• The code in the catch block is executed if the try block throws an exception.
109
Exception Handlers
• There can be many polymorphic catch clauses.
110
The finally Clause
• The statements in the finally block execute whether an exception occurs or not.
• finally clause must appear after all of the catch clauses.
try
{
(try block statements...)
}
catch (ExceptionType ParameterName)
{
(catch block statements...)
}
finally
{
(finally block statements...)
}