0% found this document useful (0 votes)
9 views98 pages

CH1 Part I and II

The document provides an introduction to Object-Oriented Programming (OOP) and various programming paradigms, including imperative, procedural, functional, logic, declarative, and event-driven programming. It explains key OOP principles such as objects, classes, encapsulation, inheritance, and polymorphism, as well as an overview of Java programming, its features, and the Java Development Kit (JDK). Additionally, it outlines the structure of a Java program, types of tokens, and naming conventions for identifiers.

Uploaded by

ebra4842
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views98 pages

CH1 Part I and II

The document provides an introduction to Object-Oriented Programming (OOP) and various programming paradigms, including imperative, procedural, functional, logic, declarative, and event-driven programming. It explains key OOP principles such as objects, classes, encapsulation, inheritance, and polymorphism, as well as an overview of Java programming, its features, and the Java Development Kit (JDK). Additionally, it outlines the structure of a Java program, types of tokens, and naming conventions for identifiers.

Uploaded by

ebra4842
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 98

Chapter One

Introduction to Object Oriented


Programming

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

• With the advancement of Java and its widespread popularity, multiple


configurations were built to suite various types of platforms.

Example:
• J2 versions as Java SE

• J2EE for Enterprise Applications,

• J2ME for Mobile Applications.


• Java is guaranteed to be Write Once, Run Anywhere

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

Libraries + JVM + Java Plug-in + Java Web Start


Just-In-Time Compiler)
-Selected portions of bytecode are compiled into executable code
-Only those that will benefit from compilation significant performance boost
8
Overview of Java Programming
Java Application and Java Applets
• Both of these are Java programs
• The java applications are types of stand-alone programs that directly perform
various general operations for their users.
 You can independently execute these without making use of the web browser.
 The execution of these apps requires a main function.
 A Java application is capable of executing various programs via the local system.
 The applications have full access to the local file systems

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.

• Secure: With Java's secure feature, it enables to develop virus-free systems.

• Java Programs run inside virtual machine environment

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

[Documentation] --------- suggested


[package statement] ------ optional
[import statements] ------ optional
[interface statements] ------ optional
[class definitions] ------ optional
[main-method class] ------ Essential
Basics of Java Programming

Creating, Compiling and Running a Java Program

• To create java program, you will:


• Create a source file and write the Java program.
• Compile the source file into a bytecode file
• Run the program contained in the bytecode file.
 The file name should be the same as the • The System and String class are found in
name of the class containing our main- the package java.lang and automatically
method. included in any java program.
 A program can contain one or more class • public (access modifier) makes the item
definitions but only one public class visible from outside the class.
definition. This class is called main-class • static indicates that the main() method is a
because it contains the main method. class method not an instant method.
 If a file contains multiple classes, the file
name must be the class name of the class
that contains the main method.
Basics of Java Programming
Java Program
• Java program = Comments + java statements + white space

• Java statements are also combinations of java Token(s).

• Java tokens:

• Are meaningful words and symbols of java programming language.

• They are the smaller individual units inside a program the compiler
recognizes when building up the program
Basics of Java Programming

Types of Tokens in Java

• 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

• Java programming language is case sensitive language. Example: name, Name,


NAME etc… are different identifiers/variables.
Basics of Java Programming
Identifiers’ naming conventions

• Class names: starts with capital letter and should be inter-capital

• Variable names: start with lower case and should be inter-capital

• Method names: start with lower case and should be inter-capital

• 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)

double Variables of this kind can have a value from:


4.9e(-324) to 1.7e(+308)

Other Primitive Data Types


char Variables of this kind can have a value from:
A single character
boolean Variables of this kind can have a value from:
True or False
Basics of Java Programming
What is a Variable?
• Variables are places where information can be stored while a program is running.
• Their values can be changed at any point over the course of a program
Creating Variables
• To create a variable, declare its name and the type of
information that it will store.
• The type is listed first, followed by the name.
• Example: a variable that stores an integer representing the
highest score on an exam could be declared as follows:
int highScore ;
String message;
type name
Basics of Java Programming
Creating Variables (continued)
• Now you have the variable (highScore), you will want to
assign a value to it.

• Example: the highest score in the class exam is 98.

highScore = 98;

• Examples of other types of variables:

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

• It is good practice to select variable names that give a good indication


of the sort of data they hold
• For example, if you want to record the size of a hat, hatSize is a good choice for
a name whereas qqq would be a bad choice
Basics of Java Programming
• When naming a variable, the following convention is commonly used:

• The first letter of a variable name is lowercase


• Each successive word in the variable name begins with a capital letter
• All other letters are lowercase

• Here are some examples:

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

Integer Real Character String


constants constants constants constants
• We can use Symbolic constants which are names given to numbers
instead of using the numbers in programs directly

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.

• All statements in Java are separated by semicolons ;

• 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

• The above example is an Expressions


Basics of Java Programming
The Operator Groups
• There are 6 different groups of operators:
• Arithmetic 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

• The result of integer division is just the


Basics of Java Programming

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++;

++ is called the increment operator.

count = count - 1;
can be written as:
--count; or count--;

-- is called the decrement operator.


Basics of Java Programming
The increment/decrement operator has two forms:

• The prefix form ++count, --count


first adds 1 to the variable and then continues to any other operator in the expression

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6

• The postfix form count++, count--


first evaluates the expression and then adds 1 to the variable

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

• Produces a boolean value (true or false) depending on the relationship

operation is true when . . .


a > b a is greater than b
a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a <= b a is less than or equal to b
a < b a is less than b
Basics of Java Programming
Examples of Relational Operations
int x = 3;
int y = 5;
boolean result;

1) result = (x > y);


now result is assigned the value false because
3 is not greater than 5

2) result = (15 == x*y);


now result is assigned the value true because the product of
3 and 5 equals 15

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

Truth Table for Logical Operators


x y x && y x || y !x

True True True True False

True False False True False

False True False True True

False False False False True


Basics of Java Programming
Examples of Logical Operators
boolean x = true;
boolean y = false;
boolean result;

1. Let result = (x && y);

now result is assigned the value false

2. Let result = ((x || y) && x);

(x || y) evaluates to true
(true && x) evaluates to true

now result is assigned the value true


Basics of Java Programming

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

• Order of Operations (PEMDAS)


1. Parentheses

2. Exponents

3. Multiplication and Division from left to right

4. Addition and Subtraction from left to right


Basics of Java Programming
Exercise
What will be the output of the following Program?
public class operator {
public static void main(String args[]){
int A=15, B=5, D, E;
--A;
B = ++B + A++;
D = --B - ++A;
D+=(A%B);
E = D/A;
System.out.println("A = "+A); Output
System.out.println("B = "+B);
System.out.println("D = "+D);
System.out.println("E = "+E);
}
} 59
Basics of Java Programming
Type Conversion/Casting
• It is the process of converting one datatype into another.
Types of Type Casting:
Widening/Implicit Type Casting:
• A lower datatype is transformed into a higher one, It occur naturally, no chance of data loss
• Widening type casting occur when:
• The target type must be larger than the source type
• Both data types must be compatible with each other
• The numeric data types are compatible with each other but no automatic conversion is
supported from numeric type to char or boolean.
• Also, char and Boolean are not compatible with each other
• Syntax : larger datatype variable name=Smaller datatype variable;
• Eg. int x=10;
• long y=x Increasing order of Size 60
Basics of Java Programming
Narrowing or Explicit Conversion
• The process of downsizing a bigger data type into a smaller one
• It does not happened by itself, if we don’t explicitly do that , a compile time error
occur
• If we want to assign a value of a larger data type to a smaller data type we perform
explicit type casting or narrowing.
• Syntax:
• Smaller datatype variable name=(smaller data type)larger datatype variable name;
• Eg. double a=10.25;
int b=(int)a;

61
Basics of Java Programming
Obtain User Input
• The Scanner Class can read data from different source.

• E.g. the console, files

• 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.

• To use Scanner class ,we have to:

• import import java.util.Scanner;

• Create a Scanner object reference

• like Scanner c = new Scanner (System.in);

• Calling a method on an object referenced by a variable 62


Basics of Java Programming
List of methods
Method Description
nextInt() To Reads int type data from keyboard
nextDouble() To Reads double type data from keyboard
nextFloat() To Reads float type data from keyboard
nextBoolean() To Reads boolean type data from
keyboard
nextLong() To Reads long type data from keyboard
nextByte() To Reads byte type data from keyboard
next() Reads one "token". Tokens are separated
by spaces or presses of the enter key
nextLine() Reads an entire line

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.

• Java provides three types of control flow statements:

• Decision Making statements

• Loop statements

• Jump statements

65
Control Statements in Java
Decision-Making statements:

• Decision-making statements decide which statement to execute and when.

• Decision-making statements evaluate the Boolean expression and control the


program flow depending upon the result of the condition provided.

• Some of decision-making statements in Java:

• 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

System.out.println("city is " +city_name);


70
Control Statements in Java
4. Nested if-statement
In nested if-statements, the if statement can contain an if or if-else statement inside
another if or else-if statement.
Syntax:
if(condition 1)
{ statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
71
Control Statements in Java
5)Switch Statement:
• The switch statement contains multiple blocks of code called cases and
a single case is executed based on the variable which is being
switched.
• In switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is
also supported since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• The case expression will be of the same type as the variable.

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

• In programming, sometimes we need to execute the block of code repeatedly


while some condition evaluates to true.

• Loop statements are used to execute the set of instructions in a repeated order.

• In Java, we have three types of loops:

• for loop

• while loop

• do-while loop
76
Control Statements in Java
Java for loop

• In Java, for loop is similar to C and C++.


• It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code.
• We use the for loop only when we exactly know the number of times, we want to
execute the block of code.
Syntax:
for(initialization; condition; increment/decrement) {
//block of statements
}

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

• Used to transfer the control of the program to the specific statements.

• In other words, jump statements transfer the execution control to the other part of
the program.

• There are two types of jump statements in Java,

• i.e., break and continue.

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

• The break statement example with for loop


for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}

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

• There are two types of array.

• Single Dimensional Array

• Multidimensional Array

92
Java Arrays
Single-Dimensional Array in Java

• A single-dimensional array in Java is a linear collection of elements of the same data


type.

• It is declared and instantiated using the following syntax:

• dataType[] arr; (or)

• dataType arr[];

• Instantiation of an Array in Java

• arrayRefVar=new datatype[size];

• Example: int num[]=new int[5];


93
Java Arrays
Example:
int num[]=new int[5];
num[0]=10;//initialization
num[1]=20;
num[2]=70;
num[3]=40;
num[4]=50;
for(int i=0;i<num.length;i++){//length is the property of array
System.out.println(num[i]);
}
• NB: In Java, you can declare, instantiate, and initialize an array in a single line
Example: int num[]={10,20,70,40,50};
94
Java Arrays
Multidimensional Array in Java

• A multidimensional array in Java is an array of arrays where each element can be an


array itself.

• It is useful for storing data in row and column format.

Syntax to Declare Multidimensional Array in Java


• dataType[][] arrayRefVar; (or)

• dataType arrayRefVar[][]; (or)

• dataType []arrayRefVar[];

• Example:int[][] arr=new int[3][3];//3 row and 3 column 95


Java Arrays

int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix

// Printing the 2D array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(arr[i][j] + " ");

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

You might also like