CH1 Part I and II
CH1 Part I and II
1
Programming Paradigms
Programming paradigms are fundamental styles or approaches to structuring
and organizing code, influencing how programmers think about and solve
problems.
A way of conceptualizing how tasks to be carried out on the computer should
be structured ,organized and it is the description of the process of computation
Types of programming Paradigm:
Imperative Programming:
Specifies how the program should execute, step-by-step
Uses statements to manipulate the state of the program.
Emphasizes control flow and sequential execution.
Procedural Programming:
Organizes code into procedures or functions that perform specific tasks.
Decomposes problems into smaller, modular units.
2
Programming Paradigms
Object-Oriented Programming (OOP):
Organizes code around "objects" that contain data (attributes) and methods
(functions).
Emphasizes data encapsulation, inheritance, and polymorphism.
Uses objects to model real-world entities and their interactions
Functional Programming
• Treats computation as the evaluation of mathematical functions and avoids
changing state and mutable data
• Emphasizes immutability and pure functions (functions that always return
the same output for the same input).
3
Programming Paradigms
Logic Programming:
Uses logical statements and rules to represent knowledge and solve
problems.
Uses facts and rules to derive conclusions
Declarative Programming:
Describes what the program should do, rather than how
Focuses on the desired outcome, leaving the implementation details
to the system.
Often used for tasks like data querying
Event-Driven Programming:
The flow of execution is determined by events, such as user actions or
messages from other programs
4
Overview of OO Principles
Objects and Classes
• Object: an identifiable thing or individual containing
• characteristic behaviour (i.e. functionality) and
• states reflected in the attributes (data) held about the object
• class: A collection of objects
• Data Abstraction and Encapsulation
• Encapsulation: The wrapping up of data and methods into a class. It also means
that the data inside a class is hidden from everything outside the class.
• Abstraction: refers to the way in which a class represents only the essential
features of the set of objects it models – a class does not include background or
extra details that are not relevant to the system.
5
Overview of OO Principles
Inheritance
• Inheritance is the way in which objects of one class get the properties of objects of
another class. This includes the data/ attributes and the methods.
Polymorphism
• The word polymorphism means the ability to take more than one form/structure.
• A particular operation/method may behave differently for different number of
inputs.
6
Overview of Java Programming
• Java is a general-purpose, high-level programming language
Example:
• J2 versions as Java SE
7
Overview of Java Programming
High-level conceptual
c
JR
E
diagram of Java language
o +
JR mp
co E il
le mp +
de rs i
+
ge bug
rr
de + s
bu
er g g
9
Overview of Java Programming
Cont…
• Java Applets were small programs written in Java that ran inside a web browser
• It is a type of Java program that a user can easily embed in a web page.
• One can easily include a Java applet along with various HTML documents.
• Execution of these applets does not require any main function.
• The execution of the applets needs a web browser (Java-based)
• One requires a Java applet for performing small tasks.
• Note: java.applet package has been deprecated in Java 9 and later versions, as
applets are no longer widely used on the web
10
Parameters Java Application Java Applet
Meaning and Basics A Java Application is a type of program that can get A Java Applet is a small program that makes use
independently executed on a computer. of another application program so that we can
execute it.
Main() Method The execution of the Java application begins with the The Java applet initializes through the init(). It
main() method. The usage of the main() is a prerequisite does not require the usage of any main()
here. method.
Execution It cannot run alone, but it requires JRE for its execution. It cannot run independently but requires APIs
for its execution (Ex. APIs like Web API).
Installation One needs to install a Java application priorly and A Java applet does not require any prior
explicitly on a local computer. installation.
Communication It is possible to establish communication with the other It cannot really establish communication with
among other Servers servers. the other servers.
Read and Write The Java applications are capable of performing the read A Java applet cannot perform these applications
Operations and write operations on various files present in a local on any local computer.
computer.
Restrictions These can easily access the file or data present in a These cannot access the file or data
computer system or device. available on any system or local computers.
Security Java applications are pretty trusted, and thus, come Java applets are not very trusted. Thus, they
with no security concerns. require security.
11
Types of Java Applications
• There are mainly 4 types of applications that can be created using java programming:
1) Standalone Application
It is also known as desktop application /window-based application.
An application that need to install on every machine.
AWT and Swing are used in java for creating standalone applications.
2) Web Application
• An application that runs on the server side and creates dynamic page. Currently, servlet, jsp, struts, jsf
etc. technologies are used for creating web applications in java.
3) Enterprise Application
• An application that is distributed in nature, such as banking applications .
• It has the advantage of highlevel security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
4) Mobile Application
• An application that is created for embedded and mobile devices in the IOT.(micro-Controller,
Sensory, Mobile Phones)
• Currently Android and Java ME(micro edition) are used for creating mobile applications.
12
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a java programming platform.
It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc.
It includes topics of OOPs, Multithreading, I/O Stream, Networking, AWT, Swing,
2) Java EE (Java Enterprise Edition)
It is an enterprise platform which is mainly used to develop web and enterprise applications.
It is built on the top of Java SE platform.
It includes topics like Servlet, JSP, EJB.
3) Java ME (Java Micro Edition)
It is a micro platform which is mainly used to develop mobile applications.
4) Java Fx:It is used to develop rich internet applications(RIA).
Those web applications which provide similar features and experience as that of desktop applications.
They offer a better visual experience when compared to the normal web applications to the users.
Delivered as browser plug-ins to transform traditional applications into more enhanced, fluid, animated and
engaging applications.
Therefore we have three main technologies using which we can develop an RIA
• Adobe Flash
• Microsoft Silverlight
• JavaFX 13
Features of Java Programming
• Object Oriented: In Java, everything is an Object.
• Simple: Java is designed to be easy to learn. If you understand the basic concept of
OOP, Java would be easy to master.
14
Features of Java Programming
• Robust: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
• Some of the reasons for Java is called as a robust language:
• Strongly Typed Language a. Java checks the code at compile time.
• Automatic Memory Management (Garbage collection)
• In C/C++, the programmer will manually allocate and free all dynamic
memory. This sometimes leads to problems, because programmer will forget
to free the memory.
• In Java, memory de-allocation is done automatically through Garbage
Collection.
• Error Handling
• Java provides object-oriented exception handling to handle the errors in java
program.
• Using exception handling, all run time errors should be managed by the
program.
15
Features of Java Programming
Cont…
• Architectural-neutral: Java compiler generates an architecture-
neutral object file format, which makes the compiled code to be
executable on many processors, with the presence of Java runtime
system
• Multithreaded: With Java's multithreaded feature, it is possible to
write programs that can do many tasks simultaneously. This design
feature allows developers to construct smoothly running interactive
applications.
• High Performance: With the use of Just-In-Time compilers, Java
enables high performance.
• Dynamic: Java is considered to be more dynamic than C or C++ since
it is designed to adapt to an evolving environment.
16
Features of Java Programming
• Distributed: Java is designed for the distributed environment of the internet.
• Compiled and interpreted: java is both compiled and interpreted.
• The Java compiler translates the program into an intermediate language called Java byte-
codes.
• Java byte-codes are platform-independent – this means they can be run on different
operating systems (e.g. Windows, Linux, Mac...). There are different Java interpreters
for different platforms. These interpreters parse and run each of the Java byte-code
instructions to each machine code in which the machine can understand. The interpreters
are usually called java Virtual Machine.
• It is called a Virtual Machine because it is like a computer that does not physically exist
• the JVM exists only within the memory of the computer. The Java byte-codes are like a
set of machine code instructions for the JVM.
• Compilation only needs to happen one time, whereas interpretation happens every time
the program is executed
17
Compiling and interpreting of a Java program
Machine-code
Byte-code
18
Compiling and interpreting of a Java program
Java program can be compiled once and then run on different platforms
19
Java Development Environment
• Java environment includes a large number of development tools and
hundreds of classes & methods.
• The development tools are part of the system known as java development
kit (JDK).
• The set of classes and methods are part of the Java Standard Library(API),
also known as Application Programming Interface(API).
20
Main Java API packages include:
• The Java API consists of many built-in classes and methods that we can use
in our code. These classes and methods/functions are again grouped into a
form packages. Package is a collection of related classes together. Some of
the most commonly used packages are the following:
• Language support package (java.lang) – classes required for implementing
basic features of Java.
• Utilities package (java.util) – classes that provide various utility functions
such as date and time functions.
• Input/Output package (java.io) – classes required for manipulation of input/output
to/from programs
• Networking Package (java.net) – classes used for communicating with other
programs/PCs over networks and internet
• Applet Package (java.applet) – classes that are used to create Java applets.
21
Java Development Kit (JDK)
• Comes with a collection of tools that are used for developing and running
java programs. They include
• javac --- java compiler
• java --- java interpreter
• jdb --- java debugger etc...
• So, to develop java programs, we need to install jdk. And then we can use
our own text editor to write java source code. Or instead of using our own
text editor, another option we can use is installing other tools or APIs like
Net-beans and Eclipse to easily code, compile and run java programs.
22
Basics of Java Programming
Structure of java Program
• Java tokens:
• They are the smaller individual units inside a program the compiler
recognizes when building up the program
Basics of Java Programming
• Reserved keywords
• Identifiers
• Literals
• Operators
• separators.
Basics of Java Programming
1. Reserved keywords
• Words with special meaning to the compiler.
• They could not be used as constant or variable/identifier names.
• The following keywords are reserved in the Java language.
• They can never be used as identifiers:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
Basics of Java Programming
2. Identifiers
• Identifiers are programmer defined tokens.
• They include names used to identify classes, methods, variables, objects etc
• Constants: often written in all capital and use underscore if you are
using more than one word.
Basics of Java Programming
Data types
• Data type are “item type to be stored in memory”.
• They are used to identify
• Amount of memory size that should be assigned to a given data/item and
• Kinds of operations that could be made on the item.
• All kinds of data that can be stored in computer do not take the same space and
the same operations cannot be made on them
• Based on java programming language, data types are categorized as
primitive/built-in and derived/user-defined.
31
Basics of Java Programming
32
Basics of Java Programming
Primitive Data Types
The following tables show all of the primitive data types along with
their sizes and formats:
Integers
Data Type Description
byte Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memory
short Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memory
int Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in memory
long Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and occupy
64 bits in memory
Basics of Java Programming
Real Numbers
Data Type Description
float Variables of this kind can have a value from:
1.4e(-45) to 3.4e(+38)
highScore = 98;
String studentName;
boolean gameOver;
Basics of Java Programming
Naming Variables
• The name that you choose for a variable is called an identifier.
• In Java, an identifier can be of any length, but must start with:
a letter (a – z),
a dollar sign ($),
or, an underscore ( _ ).
• The rest of the identifier can include any character except those used as
operators in Java such as + , - , * .
In addition, there are certain keywords reserved (e.g., "class") in the
Java language which can never be used as identifiers.
Basics of Java Programming
Naming (Continued)
• Java is a case-sensitive language – the capitalization of letters in
identifiers matters.
A rose is not a Rose is not a ROSE
pageCount
loadFile
anyString
threeWordVariable
Basics of Java Programming
Exercise
• Which of the following are valid variable names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7) System
Basics of Java Programming
Java Constant
• Constants are fixed values that do not change during the execution of a program.
Java
constants
Numeric Non-numeric
constants constants
41
Basics of Java Programming
• Symbolic constants
• Should be in capital letters
• Re-assigning after declaration is illegal
• Are declared as:
• Syntax: final var_type symbolic_name= value;
• Eg: final float PI=3.14;
42
Basics of Java Programming
Statements
• A statement is a command that causes something to happen.
• Example:
System.out.println(“Hello World”);
Basics of Java Programming
3. Literals
• Literals are values to be stored in variables.
• They are a sequence of characters (digits, letters, & other characters).
4. separators
• Separators are symbols used to indicate where groups of codes are
divided and arranged.
• They define the shape and function of our code.
Eg, parenthesis, brace,bracket semicolon,coma
Basics of Java Programming
5. Operators
• Are a symbol that take one or more arguments (operands) and
operates on them to produce a result
• Operators are special symbols used for
– mathematical functions
– assignment statements
– logical comparisons
• Examples:
3+5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, * operators
• Assignment operator
• Increment/Decrement operators
• Relational operators
• Logical operators
• Conditional operators
Basics of Java Programming
Arithmetic Operators
• Java has 5 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
Basics of Java Programming
Integer Division Example
• int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1
• double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8
Assignment Operator
• The basic assignment operator (=) assigns the value of expr to var
var = expr ;
• Java allows you to combine arithmetic and assignment operators into a
single operator.
• Examples:
x = x + 5; is equivalent to x += 5;
y = y * 7; is equivalent to y *= 7;
Basics of Java Programming
Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;
count = count - 1;
can be written as:
--count; or count--;
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
Basics of Java Programming
Relational (Comparison) Operators
• Relational operators compare two values
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
Basics of Java Programming
Logical Operators
Symbol Name
&& AND
|| OR
! NOT
• logical operators can be referred to as boolean operators,
because they are only used to combine expressions that have a
value of true or false.
Basics of Java Programming
(x || y) evaluates to true
(true && x) evaluates to true
Conditional Operators
• It is also known as ternary operator and used to evaluate Boolean expression
• Syntax: exp1?exp2:exp3
If exp1 condition is true? Then value exp2: otherwise value exp3
Example : int x, y=12,z=3
x=y>z?y:z
Basics of Java Programming
2. Exponents
61
Basics of Java Programming
Obtain User Input
• The Scanner Class can read data from different source.
• If we want it to read data from the keyboard, then we must pass in the System.in object
as an argument that will serve as the data source.
63
Basics of Java Programming
Exercise:
• Write a java program that will accepts the length and width of a rectangle and
display its area?
• Write a program that reads the diameter of a circle and display it area and
perimeter?
• Write a program that accepts three numbers and display the smallest one?
64
Control Statements in Java
• The statements in the java code are executed according to the order in which they appear.
• However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements.
• Loop statements
• Jump statements
65
Control Statements in Java
Decision-Making statements:
• If statement
• if-else statement
• if-else-if statement,
• switch statement.
66
Control Statements in Java
1) if statement:
• It evaluates a Boolean expression and enables the program to enter a block of
code if the expression evaluates to true.
• Syntax:
if(condition) {
statement 1; //executes when condition is true
}
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
} 67
Control Statements in Java
2)if-else statement
• The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block.
• The else block is executed if the condition of the if-block is evaluated as false.
int x = 10;
• Syntax: int y = 12;
if(x+y < 10) {
if(condition) { System.out.println("x + y is less than 10");
statement 1; //executes when condition is true }
} else {
System.out.println("x + y is greater than 20");
else{
}
statement 2; //executes when condition is false
}
68
Control Statements in Java
3) if-else-if statement
• The if-else-if statement contains the if-statement followed by multiple else-if statements,
where the program may enter in the block of code where the condition is true.
• We can also define an else statement at the end of the chain.
Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
69
Control Statements in Java
String city_name="Debre Berhan";
if("Addis Ababa".equals(city_name))
System.out.println("city is Addis Ababa");
else if(city_name=="BahirDar")
System.out.println("city is Bahir Dar");
else if(city_name=="Dessie")
System.out.println("city is Dessie");
else if(city_name=="Hawassa")
System.out.println("city is Hawassa");
else
72
Control Statements in Java
The syntax:
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement; 73
Control Statements in Java
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(“number is” + num);
}
Output:
74
Control Statements in Java
enum Status{ low,medium,high}
public class SwitchDemo {
public static void main(String[] args) {
Status st=Status.medium;
switch (st) {
case low:
System.out.println("low level");
break;
case medium:
System.out.println("Medium level");
break;
case high:
System.out.println("high level");
break;
default:
System.out.println("invalid Enumeration Selection"); output:
}
}
}
75
Control Statements in Java
Repetition/Loop Statements
• Loop statements are used to execute the set of instructions in a repeated order.
• for loop
• while loop
• do-while loop
76
Control Statements in Java
Java for loop
77
Control Statements in Java
int sum = 0;
for(int i = 1; i<=10; i++) {
sum = sum + i;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
78
Control Statements in Java
Java for-each loop
• Java provides an enhanced for loop to traverse the data structures like array or
collection.
• In the for-each loop, we don't need to update the loop variable.
• The syntax :
for(data_type var : array_name){
//statements
}
Example:
String[] language = {"C","C++","Python","Java",};
System.out.println("Content of the array:");
for(String ln:language)
System.out.println(ln); 79
Control Statements in Java
Java while loop
• Used to iterate over the number of statements multiple times.
• However, if we don't know the number of iterations in advance, it is
recommended to use a while loop.
• It is also known as the entry-controlled loop since the condition is checked at the
start of the loop.
• If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
• The syntax:
while(condition){
//looping statements
}
80
Control Statements in Java
• Example:
int i = 0;
System.out.println("Printing the list of first 10 positive even numbers");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
81
Control Statements in Java
Java do-while loop
• The do-while loop checks the condition at the end of the loop after executing the
loop statements.
• When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
• It is also known as the exit-controlled loop since the condition is not checked in
advance.
• The syntax:
do
{
//statements
} while (condition);
82
Control Statements in Java
int i = 0;
System.out.println("Printing the list of first 10 even numbers ");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
83
Control Statements in Java
Exercise:
1. Write a program that read a number from the user and print whether
it is even or odd ?
2. Write a program that accept a positive number N from the user and
display the sum of 1 up to N.
3. Write a program that prompt the user for an integer number and
display whether the number is prime or not?
84
Control Statements in Java
Jump Statements
• In other words, jump statements transfer the execution control to the other part of
the program.
85
Control Statements in Java
Java break statement
• The break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement.
• However, it breaks only the inner loop in the case of the nested loop.
• The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
86
Control Statements in Java
87
Control Statements in Java
• break statement example with labeled for loop
public static void main(String[] args) {
a:
for(int i = 0; i<= 5; i++) {
b: Output
for(int j = 0; j<=10;j++) {
c:
for (int k = 0; k<=15; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
} 88
Control Statements in Java
Java continue statement
• Unlike break statement, the continue statement doesn't break the loop, whereas, it skips
the specific part of the loop and jumps to the next iteration of the loop immediately.
for(int i = 0; i<= 2; i++) {
• Output:
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
} 89
Java Arrays
• 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.
• 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.
• The length member allows us to obtain the array's length.
• Java allows us to create single- or multi-dimensional arrays, just like C/C++ does.
90
Java Arrays
Advantages
•Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
•Random access: We can get any data located at an index position.
Disadvantages
•Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
91
Java Arrays
Types of Array in java
• Multidimensional Array
92
Java Arrays
Single-Dimensional Array in Java
• dataType arr[];
• arrayRefVar=new datatype[size];
• dataType []arrayRefVar[];
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
System.out.println();
}
96
Exercise
• Write a program that will initialize the array elements 2,3,12,6,9,8 and
display the elements in reverse order?
• Write a program that accepts five numbers from the keyboard and
display it content using array ?
• Write a program that will accepts numbers for 2 by 3
multidimensional array and display the sum of the array elements?
97
The End
98