Kasirul Rashtawi Institute
Computer Science Faculty
Network dept
Java Programming
Lecturer: Najibullah Zirak Zazai
Contact/WhatsApp: +93772192018
E-Mail: nzirak.zazai2019@[Link]
YouTube Channel: Najibullah Zirak
Student Full Name:
Call: 9 August 2023
History of Java
Java was conceived by James Gosling and his team at Sun Micro
Systems, Inc in 1991. This language was initially called “Oak” after an
oak tree that stood outside Gosling's office and in 1995 it was
renamed as “Java”. Java supports Application programs and Applet
programs. An Application program is one that can be run on your
computer with its operating system. Sun released the first public
implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular
platforms.
Java team members (also known as Green Team).
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 3
There are given significant points that
describe the history of Java.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the
Java language project in June 1991. The small team of sun engineers
called Green Team.
Initially designed for small, embedded systems in electronic
appliances like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling, and the file
extension was .gt.
After that, it was called Oak and was developed as a part of the Green
project.
Why Java named "Oak"?
Why Oak? Oak is a symbol of strength and chosen as a national tree
of many countries like the U.S.A., France, Germany, Romania, etc.
In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 4
Why Java Programming named "Java"?
Why had they chosen java name for Java language? The team gathered to
choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that
reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along with
Silk". Since Java was so unique, most of the team members preferred Java
than other names.
Java is an island of Indonesia where the first coffee was produced (called
java coffee). It is a kind of espresso bean. Java name was chosen by James
Gosling while having coffee near his office.
Notice that Java is just a name, not an acronym.
Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
In 1995,Time magazine called Java one of the Ten Best Products of 1995.
JDK 1.0 released in(January 23, 1996). After the first release of Java, there
have been many additional features added to the language. Now Java is
being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc. Each new version adds the
new features in Java.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 5
What is Java?
A high-level programming language that allows an intent (a program) to
be expressed in a human-readable format that can be translated in the
binary code executable by a computer.
Java is a high level, robust, secured and object-oriented programming
language.
Platform: Any hardware or software environment in which a program
runs, is known as a platform.
Java is a powerful object oriented programming language developed by
Sun Microsystems Inc. in1991. Java was developed for consumer
electronic devices but later it was shifted towards Internet. Now Java
has become the widely used programming language for the Internet.
Java is a platform neutral language (Machine Independent). Program
developed by Java can run on any hardware or on any operating system
in this world.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 6
Features of Java
Java was developed by James Gosling, who is known as the father of Java, in
1995.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 7
Usage of Java
In many more places java is being used.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 8
Top Java Applications
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 9
Bytecode
Java needs a compiler and an interpreter. The java source
program is passed to a compiler and the output of the java
compiler is a bytecode. The bytecode is a highly optimized set of
instructions designed to be executed by the java run-time system,
which is the Java Virtual Machine (JVM). The bytecode can be
executed by any interpreter. It is machine independent and
architecture neutral ie byte can be executed by IBM interpreter, SUN
interpreter, SPARC interpreter …etc.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 10
What is JDK & why do we need it?
The Java Development Kit (JDK) is a software development tools used
for developing Java applications.
It includes JRE, interpreter, a compiler (javac), an archiver (jar), a
documentation generator (javadoc) and other tools needed in Java
development
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 11
Continue…
JDK includes a Java compiler and JVM. The task of the
compiler is to read a .java file that contains the text of the
program written in Java (called source code) and transform
(compile) it into a bytecode stored in a .class file. The JVM
can then read the .class file, interpret the bytecode in a
binary code, and send it to the operating system for
execution. Both the compiler and JVM have to be invoked
explicitly from the command line.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 12
What is JVM & what it does?
JVM (Java Virtual Machine) is a virtual machine. It is a specification
that provides runtime environment in which java bytecode can be
executed.
JVM is a program that reads a compiled Java program and interprets it
into the binary code that is executable by a computer.
The JVM performs following operations:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 13
JVM Architecture
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 14
Java commands
The most important Java commands are the following:
javac:This reads a .java file, compiles it, and creates one or
more corresponding .class files, depending on how many
Java classes are defined in the .java file.
java:This executes a .class file.
These are the commands that make programming possible. Each
Java programmer must have a good understanding of their
structure and capabilities. But if you are new to Java
programming and use an IDE (see the How to install and run an
IDE section), you do not need to master these commands
immediately. A good IDE hides them from you by compiling a
.java file automatically every time you make a change to it. It also
provides a graphical element that runs the program every time
you click it.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link],WhatsApp: +93772192018 15
Selecting an IDE for Java
There are several IDEs available for a Java programmer, such as
NetBeans, Eclipse, IntelliJ, IDEA, BlueJ, DrJava, JDeveloper, JCreator,
jEdit, JSource, jCRASP, and jEdit, to name a few.
The most popular ones are NetBeans, Eclipse, and IntelliJ IDEA.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 16
Simple Java Program
public class HelloWorld {
public static void main (String args []) {
[Link] (“Hello, My first Java program!");
}
}
Next slide…
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 17
Continue…
Save the file as [Link]
The name of the program has to be similar to the filename. Please note that
Java is case-sensitive. You cannot name a file “[Link]” and then in
the program you write “public class helloworld”. It is good practice to insert
comments at the start of a program to help you as a programmer
understand quickly what the particular program is all about. This is done by
typing “/*” at the start of the comment and “*/” when you finish or // for
each [Link] predicted output of this program is:
Hello, My first Java program!
In order to get the above output we have to first compile the program and
then execute the compiled class.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 18
Continue…
[Link] – compiles the program
[Link] – the interpreter used to execute the compiled program
In order to compile and execute the program we need to switch to the
command prompt. On windows systems this can be done by clicking
Start>Run>cmd
At this point one needs some basic DOS commands in order to get to the
directory (folder), where the java class resides:
cd\ (change directory)
cd\[folder name] to get to the required folder/directory
When you get to the required destination you need to type the following:
c:\[folder name]\javac [Link]
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 19
Continue…
The above command will compile the java file and prompt the user with
any errors. If the compilation is successful a new file containing the
bytecode is generated: [Link]
To execute the program, we invoke the interpreter by typing:
c:\[folder name]\java HelloWorld
The result will be displayed in the DOS window.
Hello, My first Java program!
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 20
Data Type
Data type is used to define a variable.
Data type represents the type of information present in a variable.
Data types are the keywords, which are used for assigning a type to a
variable.
When you define a variable in Java, you must inform the compiler what
kind of a variable it is. That is, whether it will be expected to store an
integer, a character, or some other kind of data. This information tells the
compiler how much space to allocate in the memory depending on the
data type of a variable.
There are two data types available in Java:
1. Primitive
2. Non-Primitive
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 21
Primitive Data Type
There are eight primitive data types supported by Java. Primitive data
types are predefined by the language and named by a keyword.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 22
Data Type with default size & value
byte
Byte data type is an 8-bits / 1-byte
Minimum value is -128
Maximum value is 127
Default value is 0
short
Short data type is a 16-bits
Minimum value is -32,768
Maximum value is 32,767
Short data type can also be used to save memory as byte data
type. A short is 2 times smaller than an int
Default value is 0.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 23
Data Type with default size & value
int
Int data type is a 32-bit / 4-byte
Minimum value is - 2,147,483,648
Maximum value is 2,147,483,647
The default value is 0
long
Long data type is a 64-bit / 8-byte
Minimum value is -9,223,372,036,854,775,808
Maximum value is 9,223,372,036,854,775,807
This type is used when a wider range than int is needed
Default value is 0L
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 24
Data Type with default size & value
float
Float data type is a single-precision 32-bit / 4-byte
Float is mainly used to save memory in large arrays of floating
point numbers.
Default value is 0.0f
Float data type is never used for precise values such as currency
double
double data type is a double-precision 64-bit / 8-byte.
This data type is generally used as the default data type for
decimal values, generally the default choice.
Double data type should never be used for precise values such as
currency.
Default value is 0.0d
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 25
Data Type with default size & value
boolean
boolean data type represents one bit of information.
There are only two possible values: t rue and false.
This data type is used for simple flags that track true/ false conditions.
Default value is false
char
char data type is a single 16-bit / 2 byte
Minimum value is '\u0000'
Maximum value is '\uffff‘
Char data type is used to store any character
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 26
What is Variable?
A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
Variable is a name of memory location.
Variable is a location in the computer memory which can store
data and is given a symbolic name for easy reference.
Variables are containers for storing data values.
Variables are used to store values. variable name is the
name of memory location where value is stored.
When you create a variable you reserve some space in memory.
A variable is a symbolic name for a memory location in which
data can be stored and subsequently recalled.
Variables are used for holding data values so that they can be
utilized in various computations in a program.
A variable is a name for a location in memory used to store a
data value.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 27
Types of Variable
There are three types of variables in Java:
1) local variable
2) Instance variable
3) Static variable
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 28
Continue…
Local Variable:
A Local variable is declared inside a method and it is visible only within
method. Access modifiers (private, public and protected) cant be use
with it.
Instance Variable
A variable which is created inside the class but outside the method is
known as an instance variable. Instance variable doesn't get memory at
compile time. It gets memory at runtime when an object or instance is
[Link] is why it is known as an instance variable.
Access modifiers (private, public and protected) can be use with it. It
is not declared as static.
Static variable
It is declared with a keyword static preceding . It cannot be local. Static
variables can be accessed by calling with the class
name [Link]
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 29
Operators in Java
Operator in Java is a symbol which is used to perform operations.
For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Arithmetic Operator
o Relational Operator
o Logical Operator
o Assignment Operator
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 30
Arithmetic Operator
Arithmetic Operator: These are used to perform mathematical
calculations like addition, subtraction, multiplication, division, etc.
Operator Meaning int a, b, result;
a=20; b=10;
+ Addition result = a + b;
- Subtraction result = a – b;
* Multiplication result = a * b;
/ Division result = a / b;
% Modulo (Remainder) result = a % b;
Modulo is the operation that gives the remainder of a division of two
values. For example, if we write: a = 11 % 3;
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 31
Arithmetic Operator Example
public class Add {
public static void main(String[] args) {
int a=15, b=8;
int c = a + b;
int c1 = a - b;
int c2 = a * b;
int c3 = a / b;
int c4 = a % b;
[Link](c);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);
}
}
32
Comparison (Relational) Operators
These operators are used to compare the value of two
variables.
Operator Meaning Int a, b; Result
a = 20; b =15;
== Equal to a == b; False
!= Not Equal to a != b; True
< Less Than a < b; False
> Greater Than a > b; True
<= Less Than or Equal to a <= b; False
>= Greater Than or Equal to a >= b; True
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 33
Comparison operators example
public class ComparisonOperators{
public static void main(String[] args) {
int a=15, b=8;
int c = a != b; int c1 = a == b;
int c2 = a<b; int c3 = a>b;
[Link](c); [Link](c2);
[Link](c1); [Link](c3);
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 34
Logical Operators
Logical operators are used to determine the logic
between variables or values.
Operator Meaning Description Example
Logical Returns true if both
&& AND
x < 5 && x < 10
statements are true
Logical Returns true if one of
|| OR
x < 5 || x < 4
the statements is true
Reverse the result,
Logical
! NOT
returns false if the !(x < 5 && x < 10)
result is true
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 35
Logical operators example
public class LogicalOperators{
public static void main(String args[]){
String name="afghanafghan@[Link]";
String pass="afghan111";
if (( name ==“afghanafghan@[Link]") && (pass=="afghan111")){
[Link]("Login Successfully!");
}else{
[Link]("SORRY, Login Field!");
}
}
} Output:
LogIn Successfully!
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 36
Assignment operator(s)(=)
These are used to assign the values for the variables.
The assignment operator (=) assigns a value to a variable.
a=5;
Operator Meaning
+= age += 14; age = age +14;
–= age -= 14; age = age - 14;
*= age *= 14; age = age * 14;
/= age /= 14; age = age / 14;
%= age %= 14; age = age % 14;
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 37
Assignment operator(s)(=) example
public class AssignmentOperators{
public static void main(String args[]){
int a = 15, b = 8;
int c = a = b;
[Link](a);
}
}
Before output a value is 15 and b value is 8.
After the assignment a value is equals to 8;
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 38
Assignment operator(s) example
public class AssignmentOperators{
public static void main(String args[]){
int a = 15;
a = a + 10;
[Link](a);
}
}
Now a value will be 25.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 39
Java Control Statements
In java, the default execution flow of a program is a
sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may
want to jump from line to another line, we may want to
skip a part of the program, or sometimes we may want to
execute a part of the program again and again. To solve this
problem, java provides control statement
Control statement in java is a statement that determines
whether the other statements will be executed or not. It
controls the flow of a program.
In simple words, the control statements help users
specify the order of execution of the instructions present in
a program.
The control flow statements in Java allow you to run or
skip blocks of code when special conditions are met.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 40
Java Control Statements
In java, control statements can be divided under the
following three categories:
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 41
Conditional Statements
What are conditional statements?
With which commands do you implement conditional
statement in Java?
Ans: Conditional construct are specific statements that
allow us to check a condition and execute certain parts of
code depending on whether the condition is true or false.
Conditional statements in Java are : if, if- else, if – else if –
else and switch case.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 42
Selection Statements
Like all high-level programming languages, Java provides
selection statements: statements that let you choose
actions with alternative courses. The program can decide
which statements to execute based on a condition.
Selection statements use conditions that are Boolean
expressions. A Boolean expression is an expression that
evaluates to a Boolean value: true or false.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 43
boolean Data Type
The boolean data type declares a variable with the value
either true or false. How do you compare two values,
such as whether a radius is greater than 0, equal to 0, or
less than 0? Java provides six relational operators (also
known as comparison operators), shown in Table 3.1, which
can be used to compare two values (assume radius is 5 in
the table)
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 44
If statement
Java has several types of selection statements: one-way if
statements, two-way if-else statements, nested if
statements, multi-way if-else statements, switch
statements, and conditional operators.
In java, we use the if statement to test a condition and
decide the execution of a block of statements based on
that condition result. The if statement checks, the given
condition then decides the execution of a block of
statements. If the condition is True, then the block of
statements is executed and if it is False, then the block of
statements is ignored. The syntax and execution flow of if
the statement is as follows.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 45
Continue…
Syntax:
if(condition){
if-block of statements
}
statements of if block
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 46
Example of if
int num=2;
if(num==2) {
[Link](“Two is EVEN.");
}
Equivalent
if (num==2) { if (num==2)
[Link](“Two is Even.”) [Link](“Two is Even.”)
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 47
Two-Way if-else Statements
An if-else statement decides the execution path based on
whether the condition is true or false.
A one-way if statement performs an action if the specified
condition is true. If the condition is false, nothing is done.
But what if you want to take alternative actions when the
condition is false? You can use a two-way if-else.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 48
Continue…
Syntax
if (condition){
true block of statements;
}
else
{
false block of statements;
}
statements after if block;
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 49
Example
int a=23;
if (a%2==0) {
[Link]("The number " + a + " is Even.");
[Link]("______+++++++++______");
[Link]("I am inside the TRUE block.");
}else {
[Link]("The number " + a + " is Odd.");
[Link]("______+++++++++______");
[Link]("I am inside the FALSE block.");
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 50
Nested if
An if statement can be inside another if statement to form
a nested if statement. The statement in an if or if-else
statement can be any legal Java statement, including another
if or if-else statement. The inner if statement is said to be
nested inside the outer if statement. The inner if statement
can contain another if statement; in fact, there is no limit to
the depth of the nesting. For example, the following is a
nested if statement:
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 51
Nested if example
int i=110, k=20, j=11;
if(i>k) {
if(i>j) {
[Link]("I value ( " + i + " )" + " is the
largest than k and j values.");
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 52
if-else-if
This statement is executed when if statements become fail.
So the compiler checks for the else if statement. Same if the
first else if statement become fail again it will check for the
third else if statement, same action will be perform. If none
of the if and else if statement become true then the last
bock else block will be execute.
53
if-else-if example
int score = 90;
if(score>=90) {
[Link]("Grade A");
}else if(score >=80) {
[Link]("Grade B");
}else if(score>=70) {
[Link]("Grade C");
}else if(score >=60) {
[Link]("Grade D");
}else {
[Link]("Grade E");
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 54
switch Statements
Using the switch statement, one can select only one
option from more number of options very easily. In the
switch statement, we provide a value that is to be
compared with a value associated with each option.
Whenever the given value matches the value associated
with an option, the execution starts from that option. In the
switch statement, every option is defined as a case.
The switch statement has the following syntax and
execution flow diagram.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 55
int a=6;
Continue… switch(a=6) {
case 1:
[Link]("Today is Saturday.");
Syntax: break;
case 2:
switch (expression) [Link]("Today is Sunday.");
break;
{
case 3:
case value1: [Link]("Today is Monday.");
statement1; break;
break; case 4:
case value2: [Link]("Today is Tuesday.");
statement2; break;
break; case 5:
case valueN: [Link]("Today is Wednesday.");
statementN; break;
case 6:
break;
[Link]("Today is Thursday.");
default: break;
statementDefault; default:
} [Link]("Today is Friday.");
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 56
Iteration Statements
Java’s iteration statements are for, while, and do-while.
These statements create what we commonly call loops. As
you probably know, a loop repeatedly executes the same
set of instructions until a termination condition is met. As
you will see, Java has a loop to fit any programming need.
Loop Types
while loop
for loop
do while loop
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 57
5 Hello Messages
With out loop if we want to print Hello Message 5 times, write it 5
times; look below.
public class HelloMessage{
public static void main(String args[]){
[Link](“1 Hello Zirak!");
[Link](“2 Hello Zirak!");
[Link](“3 Hello Zirak!");
[Link](“4 Hello Zirak!");
[Link](“5 Hello Zirak!");
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 58
Loop
public class Loop{
public static void main(String args[]){
for(int a=1; a<=5; a++) {
[Link]("Hello Zirak!");
}
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 59
Loops
Loops can execute a block of code as long as a specified condition is
reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
It is used when a set of instructions is to be executed multiple times or
for a fixed number of times until a particular condition is satisfied.
Loops are used in programming to repeat a specific block until some end
condition is met.
In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true.
There are three type of loops in Java programming:
Loop Types
while loop
for loop
do while loop We can also use nested loop.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 60
Output
while Loop
The while loop is Java’s most fundamental loop
statement. It repeats a statement or block while its
controlling expression is true.
General Syntax: While Example:
int a = 1;
while (a <= 10) {
while (condition) [Link]("I am number “ + a);
{ a++;
}
// body of loop
} int i = 1, n = 5;
while(i <= n) {
[Link]("I am number " + i);
i++;
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 61
int i = 1, n = 5;
Continue… while(i <= n) {
[Link]("I am number " + i);
i++;
Here is how this program works. }
Iteration Variables Condition: I <= n Action
i=1 1 is printed.
1st n=5 true
i is increased to 2.
i=2 2 is printed.
2nd n=5 true
i is increased to 3.
i=3 3 is printed.
3rd n=5 true
i is increased to 4.
i=4 4 is printed.
4th n=5 true
i is increased to 5.
i=5 5 is printed.
5th n=5 True
i is increased to 6.
i=6
6th n=5 false The loop is terminated.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 62
do-while Loop
The do...while loop is similar to while loop. However, the
body of do...while loop is executed once before the test
expression is checked.
1. The body of the loop is executed at first. Then the
condition is evaluated.
2. If the condition evaluates to true, the body of the loop
inside the do statement is executed again.
3. The condition is evaluated once again.
4. If the condition evaluates to true, the body of the loop
inside the do statement is executed again.
5. This process continues until the condition evaluates to
[Link] the loop stops.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 63
Continue…
General Syntax:
do {
// body of loop
}while (condition)
do-while Example:
int i = 1, n = 5;
do {
[Link]( i );
i++;
} while(i <= n);
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 64
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 65
Another example of do-while loop
import [Link];
public class LogicalOperator {
public static void main(String[] args) {
// Java program to find the sum of positive numbers
int sum=0;
int num=0;
Scanner input=new Scanner([Link]);
// do...while loop continues
// until entered number is positive
do {
// add only positive numbers
sum += num;
[Link]("Enter a number");
num = [Link]();
} while(num >= 0);
[Link]("Sum = " + sum);
} }
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 66
Continue…
Here, the user enters a positive number, that number is
added to the sum variable. And this process continues until
the number is negative. When the number is negative, the
loop terminates and displays the sum without adding the
negative number.
Here, the user enters a negative number. The test condition
will be false but the code inside of the loop executes once.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 67
Java for loop
Java for loop is used to run a block of code for a certain number of times.
The syntax of for loop is:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
initialization condition Increment/ decrement
1) The statement 1 initializes and/or declares variables and executes only
once.
2) The condition is evaluated. If the condition is true, the body of the for
loop is executed.
3) The statement 3 updates the value of statement 1.
4) The condition is evaluated again. The process continues until the
condition is false.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 68
Continu….
public class ForLoop {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; ++i) {
[Link]("Java code is fun!");
Output
}
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 69
For-Each Loop (Enhanced For Loop)
This was introduced in Java 5. This loop is basically used to traverse
the array or collection elements.
A for-each loop by using the keyword for-each, Java adds the for-
each capability by enhancing the for statement. The advantage of this
approach is that no new keyword is required, and no pre-existing
code is broken. The for-each style of for is also referred to as the
enhanced for loop.
General Syntax: Example of For Loop
for (parameter : arrayName) {
//statements
}
Output
String ProNames[] = {"Khost", "Paktia", "Logar", "Kabul"};
for (String cities : ProNames) {
[Link](cities + ": is the province of Afg.");
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 70
Jump Statements
jump: Java supports three jump statement: break,
continue and return. These three statements transfer
control to other part of the program.
While working with loops, it is sometimes desirable to skip
some statements inside the loop or terminate the loop
immediately without checking the test expression.
The break statement in Java terminates the loop
immediately, and the control of the program moves to the
next statement following the loop. Here is the syntax of the
break statement in Java:
break;
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 71
Example of break
int n=10;
for ( int i = 0 ; i < n ; i++) {
if (i == 5 ) //if the value of i is 5 then the loop terminates.
break;
[Link]( "i: " + i);
}
[Link]("i equals 5, so terminated the loop.");
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 72
continue;
After the continue statement, the program
moves to the end of the loop.
continue;
Example
int n=10;
for ( int i = 1 ; i < n ; i++ ) {
if (i == 5 ) //if the value of i is 5 then the loop terminates.
continue;
[Link]( i );
}
output
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 73
What is Array?
An array is a collection of similar type of elements which is
stored in a contiguous memory location.
Java array is an object which contains elements of a similar
data type. Additionally, The elements of an array are stored
in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed
set of elements in a Java array.
Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index
and so on.
int a [ ] = new int [10];
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 74
Creating Array
Array must be declared and created in computer memory
before they are used. Creation of array involves three steps:
1) Declare the array
2) Create memory locations
3) Put values into the locations
Declaration of Arrays
Array in java may be declared in two forms.
◦ Form1: Datatype Arrayname[ ];
◦ Form2: Datatype[ ] Arrayname; Example:
• int number [ ];
• float [ ] average;
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 75
Continue…
Creation of Arrays
After declaring the array, we need to create it in the memory.
Java allows us to create arrays using new operator only, as
below :
arrayname = new datatype [size];
Example:
number = new int [5]; average = new float [10];
these lines creates sufficient memory space for array number
and average. It is also possible to combine two steps –
declaration and creation into one ,shown below :
int number [ ] = new int [5];
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 76
Continue…
Initialization of Array [ put values into array ]
Putting the values into the array is known as initialization.
This is done using the array subscript as shown below.
Arrayname [Subscript] = value;
Ex.
Number[0]=5;
Number[1]=40;
Number[2]=60;
We can also initialize array automatically in the same wayas
the ordinary variable when they are declared, as shown
below:
Datatype arrayname [ ] = { list of values };
Values separated by commas and surrounded by curly braces.
Ex. int number[ ] = {100,90,40,70,66};
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 77
Creation of Array in 2 steps
Look once again at the two lines that you can use to create
an array:
int marks[];
marks = new int[10];
int marks[]; This first line is a declaration. The declaration
reserves the array name (a name like marks) for use in the
rest of the program.
marks = new int[10]; This second line is an assignment
statement. The assignment statement reserves space in the
computer’s memory for ten int values.
int marks[] = new int[10];
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 78
Program to demonstrate one dimensional array
public class LogicalOperator {
public static void main(String[] args) {
int number[ ] = {100,90,40,70,66};
//printing array
for(int i=0;i<[Link];i++){
[Link]("index " + i + " : " + number [i]);
} Output
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 79
Let's create a program that takes a single-
dimensional array as input.
int n;
Scanner sc=new Scanner([Link]);
[Link]("Enter the number of elements you want to store: ");
n=[Link]();
int array[] = new int[10];
[Link]("Enter the elements of the array: ");
for(int i=0; i<n; i++){
array[i]=[Link](); //reading array elements from the user
}
[Link]("Array elements are: ");
for (int i=0; i<n; i++){ // accessing array elements using the for loop
[Link](array[i]);
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 80
Two Dimensional array
Two dimensional array requires two subscript one for Row
and another for Column. Data in two dimensional arrays
are stored in tabular form (in row major order).
Declaration of 2D array: int a[];
a = new int[3][4];
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12
elements of type int. int [ ][ ] a = new int [3][4];
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 81
Initialization of 2D array :
int a[ ][ ] = { {1,2,4}, {5,6,7}, {9,10,11} };
or
int a[ ][ ] = {
{1,2,4},
{5,6,7},
{9,9,7}
};
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 82
String Array
Strings represent a sequence of character.
Java String array is basically an array of objects.
Java String Array Declaration Below code shows different ways for
string array declaration in java.
String[ ] strArray; //declare without size
String[ ] strArray1 = new String[3]; //declare with size
Note that we can also write string array as String
strArray[ ] but above shows way is the standard and recommended
way.
Java String Array Initialization Let’s look at different ways to
initialize string array in java.
//inline initialization
String[ ] strArray1 = new String[] {"BMW","Ford","AUDI"};
String[] strArray2 = {"BMW","Ford","AUDI"};
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 83
Continue…
//initialization after declaration
String [ ] strArray3 = new String [3];
strArray3[0] = "BMW";
strArray3[1] = "FORD";
strArray3[2] = "AUDI";
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 84
OOPs short for
O: Object
O: Oriented
P: Programming System
Object Oriented
Programming
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 85
OOPs
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 86
Continue…
Object means a real-world entity such as a pen, chair, table,
computer, watch, etc.
Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects.
It simplifies software
development and
maintenance by
providing some concepts:
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 87
Class in Java
A class is a blueprint/templete from which individual objects
are created.
A class is a template for manufacturing objects. You declare
a class by specifying the class keyword followed by a non-
reserved identifier that names it.
A class is a group of objects which have common
properties. It is a template or blueprint from which objects
are created. It is a logical entity. It can't be physical.
We can have multiple classes in diferent Java files or single
Java file. If you define multiple classes in a single Java source
file, it is a good idea to save the file name with the class
name which has main() method.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 88
Continue…
A class in Java can contain:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
Class Syntax:
class <class_name> {
field;
method;
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 89
Continue…
By convention, the first letter of a class's name is
uppercased and subsequent characters are lowercased (for
example, Employee). If a name consists of multiple words,
the first letter of each word is uppercased (such as
SavingsAccount). This naming convention is called
CamelCasing.
The following examples declares a class named Book:
class Book { public class Book {
// class body // class body
} }
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 90
A sample of a class
public class Dog {
String breed;
int age;
String color;
void barking(){
}
void hungry(){ methods
}
void sleeping(){
}
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 91
What is an object in Java
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 92
Continue…
An entity that has state and behavior is known as an
object e.g., chair, bike, marker, pen, table, car, etc. It can be
physical or logical (tangible and intangible). The example of
an intangible object is the banking system.
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external
user. However, it is used internally by the JVM to identify
each object uniquely.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 93
Object
For Example, Pen is an object. Its name is Reynolds; color is
white, known as its state. It is used to write, so writing is its
behavior.
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 94
Class and Object
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 95
Inheritance
Inheritance is an important concept of OOP. It is the
mechanism in java by which one class is allows inheriting
the fields and methods of another class.
Inheritance facilitates code reusability to reuse the fields
and methods of the existing class.
The class from which a new class is created is called as a
parent, base or super class and the new class or inheriting
class is also called as child, derived or sub class.
When the properties of the one class is transferred into
another class then it’s said to be an inheritance.
The process of acquiring properties from one class to
another class is called Inheritance concept.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 96
Continue…
In the terminology of Java, a class which is inherited is called
a parent or superclass, and the new class is called child or
subclass.
The relationship between classes are made by “extends”
keyword.
The extends keyword indicates that you are making a
new class that derives from an existing class. The meaning
of "extends" is to increase the functionality.
Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.
The main advantage of inheritance is reduction of code, and
preventing the duplication of data members.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 97
Continue…
There are 5 types of inheritance, and they are listed below.
1) Single inheritance
2) Multilevel inheritance
3) Hierarchical inheritance
4) Multiple inheritance
5) Hybrid inheritance
Only the first three types are supported by java.
The syntax of Java Inheritance:
class Subclass-name extends Superclass-name {
// methods and fields
}
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 98
Types of Inheritance in Java
Supported by Java.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 99
Continue…
In short, these two types are not supported by Java.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 100
Java Inheritance Example
As displayed in the right side figure,
Programmer is the subclass and
Employee is the superclass. The
relationship between the two classes
is Programmer IS-A Employee. It
means that Programmer is a type of
Employee.
See next slide for practical example.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 101
Continue…
class Employee {
int salary=35000;
}
public class Programmer extends Employee{
int bonus=5000;
public static void main(String[] args) {
Programmer p=new Programmer ();
int s=[Link];
int b=[Link];
int total=s+b;
[Link]("Programmer salary is: "+ [Link]);
[Link]("Programmer bonus is: " + [Link]);
[Link]("Total salary is: " + total);
}
} In the above example, Programmer object can access the field
of own class as well as of Employee class i.e. code reusability.
Lecturer: Najibullah Zirak Zazai, nzirak.zazai2019@[Link] WhatsApp: +93772192018 102