0% found this document useful (0 votes)
4 views152 pages

Java U1

The document outlines a course on Object-Oriented Programming (OOP) using Java, detailing the teaching and examination scheme, syllabus, and key concepts related to Java programming. It covers topics such as Java installation, features, components, and the execution of Java programs, emphasizing Java's platform independence and robustness. Additionally, it includes assignments and interview questions to assess understanding of the material.

Uploaded by

venishaambasana
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)
4 views152 pages

Java U1

The document outlines a course on Object-Oriented Programming (OOP) using Java, detailing the teaching and examination scheme, syllabus, and key concepts related to Java programming. It covers topics such as Java installation, features, components, and the execution of Java programs, emphasizing Java's platform independence and robustness. Additionally, it includes assignments and interview questions to assess understanding of the material.

Uploaded by

venishaambasana
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/ 152

Object-Oriented Programming

2301CS201

Object Oriented
Programming

Prof. Swati R Sharma


Computer Engineering
Department
Darshan University, Rajkot
[email protected]
Teaching and Examination Scheme
OOP Java is the easiest, scoring and my favorite subject

Teaching Scheme (Contact Hours) Examination Scheme


Lecture Tutorial Lab Credit Theory Marks Practical Marks Total
Marks
SEE CIA SEE CIA
4 0 2 5 40 30 20 10 100
SEE - Semester End Examination, CIA - Continuous Internal Assessment (It consists of
Assignments/Seminars/Presentations/MCQ Tests, etc.)

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 2


OOP Java is the easiest, scoring and my favorite subject

Syllabus
Syllabus
OOP Java is the easiest, scoring and my favorite subject

Sr. Content T W%

Hrs

1 Introduction to JAVA 10 20

2 Object Oriented Concepts 15 20

3 Inheritance and Abstraction 12 20

4 Package, Exception Handling and Multithreading 13 20

5 IO Programming and Collection Framework 10 20

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 4


Object-Oriented Programming
Using Java
2305CS102

Unit-1
Introduction to
java

Prof. Swati R Sharma


Computer Engineering
Department
Darshan University, Rajkot
[email protected]
 Looping
What we will learn OOP Java is the easiest, scoring and my favorite subject

Evolution of Java
Features of JAVA,
JDK, JRE, JVM, Byte Code
Installing and configuring JAVA
Basic Structure of Java program
Compiling and Running Java files

Unit-1
OOP Java is the easiest, scoring and my favorite subject

Introduction
Welcome to the world of Programming
What is Language?
 A language is a system of communication used by a particular country or
community. OOP Java is the easiest, scoring and my favorite subject

 It is a structured system of communication used by humans, based on


speech and gesture (spoken language), sign or often writing.
 Both person should understand each other’s language.

Hello! કેમ છો!


你好 મજામાં

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 8


Programming Language
 A programming language is a computer language that is used by
programmers (developers) to communicate with computers.
OOP Java is the easiest, scoring and my favorite subject

 It is a set of instructions written in a specific language to perform a


specific task.
 It allow us to give instructions to a computer in a language the computer
understands.
 5000+ programming languages are there, notably used are approximate
250.
 E.g. C, C++, C#, Java, Python, PHP, Pascal, etc.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 9


Types of Programming Languages
1. Low-level programming language
 It is a machine-dependent (hardware specific) programming language.
OOP Java is the easiest, scoring and my favorite subject

 It consists of a set of instructions that are either in the binary form (0 or


1) or in a symbolic and human-understandable mnemonics (ADD, MOV,
SUB).
 E.g. Machine level language, Assembly language, etc.
2. High-level programming language
 It is closer to human languages than machine-level languages.
 It is easy to read, write, and maintain as it is written in English like
words.
 It allows to write the programs which are independent of a particular
type of machine (hardware).
 A compiler is required to translate a high-level language into a low-level
language.
 E.g. Python, Java, JavaScript, PHP, C#, LISP, FORTRAN, etc.
3. Middle-level programming language
 Middle-level programming language lies between the low-level and high-
level programming language.
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 10
OOP Java is the easiest, scoring and my favorite subject

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 11


Applications implemented in Java

OOP Java is the easiest, scoring and my favorite subject

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 12


OOP Java is the easiest, scoring and my favorite subject

Introduction to
JAVA Installation
 Java is a general-purpose computer-programming language
that is open source, platform independent, object- OOP Java is the easiest, scoring and my favorite subject

oriented and specifically designed to have as few


implementation dependencies as possible.
 Java was originally developed by James Gosling at Sun
Microsystems and released in 1995.
 Java was initially named as Oak language and renamed to
JAVAVersion
Current in 1995. Java SE 22 (as of September, 14th 2021)
Version we will use Java SE 22 (LTS)
Setup size 149 MB (Linux), 152 MB (Windows x64)
Download Link https://www.oracle.com/in/java/technologies/javase-jdk11-dow
nloads.html
Official Website https://java.com
Integrated 1. Eclipse NetBeans
Development 2. IntelliJ IDEA Community Edition
Environment 3. BlueJ
(IDE)

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 14


JAVA Installation: help
 Download JDK for Windows platform (.exe) from
 https://www.oracle.com/technetwork/java/javase/downloads/index.html
OOP Java is the easiest, scoring and my favorite subject

 Install the executable of JDK


 Set the path variable of System variables by performing following steps
 Go to "System Properties" (Right click This PC → Properties →
Advanced System Settings)
 Click on the "Environment variables" button under the "Advanced" tab
 Then, select the "Path" variable in System variables and click on the
"Edit" button
 Click on the "New" button and add the path where Java is installed,
followed by \bin. By default, Java is installed in C:\Program Files\
Java\jdk-11.0.1 (If nothing else was specified when you installed it).
In that case, You will have to add a new path with: C:\Program Files\
Java\jdk-11.0.1\bin
 Then, click "OK", and save the settings
Prof.
AtSwati
last, open Command
R Sharma Prompt
#2301CS201(OOP) (cmd.exe)
Unit 01 – Introduction to javaand type java -version
15 to
JAVA Installation : Setting Path Variable

1 OOP Java is the easiest, scoring and my favorite subject

2
3
4

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 16


Features of JAVA
Simple: Java inherits C/C++ syntax and many object-oriented features
OOP Java is the easiest, scoring and my favorite subject

of C++.

Object Oriented: “Everything is an object” paradigm, which possess


some state, behavior and all the operations are performed using
these objects.

Robust: Java has a strong memory management system. It helps


in eliminating error as it checks the code during compile and runtime.

Multithreaded: Java supports multiple threads of execution, including


a set of synchronization primitives. This makes programming with
threads much easier.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 17


Features of JAVA (Cont.)
Architectural Neutral: Java is platform independent which means
OOP Java is the easiest, scoring and my favorite subject

that any application written on one platform can be easily ported to


another platform.

Interpreted: Java is compiled to bytecodes, which are interpreted by


a Java run-time environment.

High Performance: Java achieves high performance through the use


of bytecode which can be easily translated into native machine
code. With the use of JIT (Just-In-Time) compilers, Java enables high
performance.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 18


Features of JAVA (Cont.)

Distributed: Java provides a feature which helps to create distributed


OOP Java is the easiest, scoring and my favorite subject

applications. Using Remote Method Invocation (RMI), a program can


invoke a method of another program across a network and get the
output. You can access files by calling the methods from any
machine on the internet.

Dynamic: Java has ability to adapt to an evolving environment which


supports dynamic memory allocation due to which memory
wastage is reduced and performance of the application is increased.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 19


Components of Java
 Java Virtual Machine (JVM)
JDK  Java Runtime
OOP Java is the easiest, scoring and my favorite subject

Environment (JRE)
 Java Development Kit
Compiler Java
(javac.exe) Packages
(JDK)
Java (math, util, JVM
Application awt etc…)

Launcher
(java.exe), Runtime
AppletViewer Libraries
, etc..)
Development JRE
tools

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 20


Java Development Kit (JDK)
 JDK contains tools needed ,
 To develop the Java programs
OOP Java is the easiest, scoring and my favorite subject

and
 JRE to run the programs.
 The tools include
 compiler (javac.exe),
 Java application launcher
(java.exe),
 Appletviewer, etc…
 Java application launcher
(java.exe) opens a JRE, loads the
class, and invokes its main
method.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 21


Java Runtime Environment (JRE)
 The JRE is required to run java applications.
OOP Java is the easiest, scoring and my favorite subject

 It combines the Java Virtual Machine (JVM),


platform core classes and supporting libraries.
 JRE is part of the Java Development Kit (JDK), but
can be downloaded separately.
 It does not contain any development tools such as
compiler, debugger, etc.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 22


Java Virtual Machine (JVM)
 JVM is a virtual machine that enables a computer
to run Java programs as well as programs written in OOP Java is the easiest, scoring and my favorite subject

other languages and compiled to Java Bytecode.


 Bytecode is a highly optimized set of instructions
designed to be executed by the Java Virtual
Machine(JVM).
 Byte code is intermediate representation of java
source code.
 Java compiler provides byte code by compiling Java
Source Code.
 Extension for java class file or byte code is
‘.class’, which is platform independent.
 JVM is virtual because , It provides a machine
interface that does not depend on the operating
system and machine hardware architecture.
 Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 23
How Java become Platform Independent?
Source
code .java file
OOP Java is the easiest, scoring and my favorite subject

(Program)

Compil
er

Bytecode .class file

JVM
JVM JVM
(Window
(Linux) (Mac)
s)

Machine Machine Machine


Code Code Code

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 24


Bytecode: Java’s Magic
 Bytecode is a highly optimized set of Source
code .java file
instructions designed to be executed by the JVM OOP Java is the easiest, scoring and my favorite subject

(Program)
 Here, JVM is an interpreter for bytecode.
Compil
 Translating a Java program into bytecode helps er
makes it much easier to run a program in a
wide variety of environments. Byteco .class file
i.e “WRITE ONCE RUN ANYWHERE” de
 Thus, the interpretation of bytecode is the
easiest way to create truly portable programs.
 Interpreted Java program are highly secured,
because the execution of every Java program is
under the control of the JVM.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 25


Java Interview Question
1. Difference between JRE and JVM?
OOP Java is the easiest, scoring and my favorite subject

2. Difference between interpreter and JIT compiler?


3. Justify Java is platform independent.
4. Justify Java gives high performance.
5. Justify Java is Robust language.
6. What are Java bytecodes?
7. JVM vs. JRE vs. JDK

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 26


OOP Java is the easiest, scoring and my favorite subject

First Java Program


Hello World Java Program
File must be saved as
public class HelloWorld HelloWorld.java
Main method from where execution
OOP Java is the easiest, scoring and my favorite subject

{ will start
public static void main(String[] args)
{ String must start with capital
letter
System.out.println("Hello World");
} System must start with
} capital letter

 We have to save this in HelloWorld.java file as it has public class named


HelloWorld.
 String and System are inbuilt Java Classes.
 Classes in java are always written in Camel case.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 28


How to execute Java Program?
1. Save the program with the same name as the public class with .java
extension. OOP Java is the easiest, scoring and my favorite subject

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 29


How to execute Java Program?
2. Open command prompt (cmd) / terminal & navigate to desired directory /
folder. OOP Java is the easiest, scoring and my favorite subject

3. Compile the “.java” file with javac command.

4. Execute the “.class” file with java command without extension.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 30


Assignment-1
1. Differentiate JRE,JDK and JVM.
OOP Java is the easiest, scoring and my favorite subject

2. Why Java is platform independent?

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 31


Object-Oriented Programming
2305CS102

Unit-1(part-II)
Data types,
Variables &
Operators
Prof. Swati R Sharma
Computer Engineering
Department
Darshan University, Rajkot
[email protected]
 Looping
What we will learn OOP Java is the easiest, scoring and my favorite subject

Primitive data types


String
Variables
Type casting
Command line arguments
Operators
Operator precedence

Unit-1(part-II)
OOP Java is the easiest, scoring and my favorite subject

Tokens
Tokens
 The smallest individual unit of a language / program is known as a token.
 Tokens are basic building blocks of any language.
OOP Java is the easiest, scoring and my favorite subject

“Jane bakes tasty cookies.”


 Jane is noun
 bakes is verb
 tasty is adjective
 cookies is noun
 ‘.’ is special character to end the sentence.

 Each and every word and punctuation is a token.


 We divide sentence into tokens to understand the meaning of a sentence.
 Similarly, the compilers of programming language breaks a program into
the tokens and proceeds to the various stages of the compilation.
 However, collection of tokens in appropriate sequence makes a
meaningful sentence. #2301CS201(OOP) Unit 01 – Introduction to java
Prof. Swati R Sharma 35
Classification of Tokens
Sr. Token Description OOP Java is the easiest, scoring and my favorite subject
Examples
void, int, float,
1 Keywords Predefined reserved words
for, if
User-defined combination of alphanumeric
a, i, sum,
2 Identifiers characters.
number, pi
Name of a variable, function, class, etc.
3 Constants Fixed values that do not change 17, -25.50, 82, 0

4 Strings A sequence of characters “Darshan”, “Hi!”


Special
5 Symbols that have special meaning #, $, @, %, =, :, ;
Symbols
A symbol that performs operation on a value or
6 Operators +, -, *, /
a variable

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 36


OOP Java is the easiest, scoring and my favorite subject

Identifiers
Identifiers
 They are used for class names, method names and variable names.
OOP Java is the easiest, scoring and my favorite subject

 An identifier may be any descriptive sequence of


 uppercase(A…Z) and lowercase(a..z) letters
 Numbers(0..9)
 Underscore(_) and dollar-sign($) characters
 Examples for valid Identifiers,
 AvgTemp
 count
 a4
 $test
 this_is_ok
 Examples for invalid Identifiers,
 2count(Identifiers can not start with digit)
 High-temp
(Identifiers can not contain dash)
 Ok/NotOK
(Identifiers can not contains slash)
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 38
Identifier Name Valid or Invalid?

for Rajkot _Name If Roll Number


OOP Java is the easiest, scoring and my favorite subject
Rs.

_________a int student _7 Identifier Valid

C C++ Java C# Compiler ___8__a__8

7Student Who? v.a.l.u. A_B_C_D_E i if

Int A2020 2021 sum a,b,c i;

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 39


Data Types
OOP Java is the easiest, scoring and my favorite subject

Java Datatypes

Primitiv Non-
e primitive

Floating-
Integer Charact Boolea
point Class
s ers n
numbers

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 40


Primitive Data Types
Data Type Size Range Example
OOP Java is the easiest, scoring and my favorite subject
byte 1 Byte -128 to 127 byte a = 10;
short 2 Bytes -32,768 to 32,767 short a = 200;
int 4 Bytes -2,147,483,648 to int a = 50000;
2,147,483,647
long 8 Bytes - long a = 20;
9,223,372,036,854,775,80
float 4 Bytes 1.4e-045
8 to to 3.4e+038 float a = 10.2f;
9,223,372,036,854,775,80
7
double 8 Bytes 4.9e-324 to 1.8e+308 double a = 10.2;

char 2 Bytes 0 to 65536 (Stores ASCII char a = ‘a’;


of character)
boolean Not true or false boolean a = true;
defined

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 41


Escape Sequences
 Escape sequences in general are used to signal an alternative
interpretation of a series of characters. OOP Java is the easiest, scoring and my favorite subject

 For example, if you want to put quotes within quotes you must use the
escape sequence, \", on the interior quotes.
System.out.println("Good Morning \"World\"");

Escape Sequence Description


\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New Line
\t Tab

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 42


OOP Java is the easiest, scoring and my favorite subject

Variables in Java
Variables in Java
 The variable is the basic unit of storage in a Java program.
OOP Java is the easiest, scoring and my favorite subject

 A variable is defined by the combination of an identifier, a type, and an


optional initializer.
 Variables have a scope, which defines their visibility, and a lifetime.

Declaringtype
a Variable
identifier [ = value][, identifier [=
value] ...] ;
It is Java’s atomic
name of
types, or the name
the
of a class or
variable
interface.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 44


Type Casting
 Assigning a value of one type to a variable of another type is known as
Type Casting. OOP Java is the easiest, scoring and my favorite subject

 In Java, type casting is classified into two types,


 Widening/Automatic Type Casting (Implicit)

 Narrowing Type Casting(Explicitly done)

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 45


Automatic Type Casting
 When one type of data is assigned to other type of variable , an automatic
type conversion will take place if the following two conditions are satisfied:
OOP Java is the easiest, scoring and my favorite subject

 The two types are compatible


 The destination type is larger than the source type
 Such type of casting is called “widening conversion”.
 Example:
int can always hold values of byte and short
public static void main(String[] args) {
byte b = 5;
// √ this is correct
int a = b;
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 46


Casting Incompatible Types
 To create a conversion between two incompatible types, you must use a
cast OOP Java is the easiest, scoring and my favorite subject

 A cast is an explicit type conversion.


 Such type is called “narrowing conversion”.
 Syntax:
(target-type) value
 Example:
public static void main(String[] args) {
int a = 5;
// × this is not correct
byte b = a;
// √ this is correct
byte b = (byte)a ;
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 47


OOP Java is the easiest, scoring and my favorite subject

Operator
Perform definite operation
Operators
1. Arithmetic Operators
OOP Java is the easiest, scoring and my favorite subject

2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Conditional / Ternary Operator
7. Instance of Operator

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 49


Operators
 An operator is a symbol to perform specific mathematical or logical
functions. OOP Java is the easiest, scoring and my favorite subject

 We use operators in maths to perform certain operations, e.g. +, -, *, /,


etc.
 Unary operators (++, --) take one operand, Binary operators (+, -, *, /)
take two operands.
Sr. Operator Examples
 Programming languages
1 Arithmetic
areOperators +, -, *, /, which
rich in operators % can be divided in
following categories,
2 Relational Operators <, <=, >, >=, ==, !
=
3 Logical Operators &&, ||, !
4 Assignment Operators =, +=, -=, *=, /=
5 Increment and Decrement ++, --
Operators
6 Conditional Operator ?:
7 Bitwise Operators &, |, ^, <<, >>

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 50


Arithmetic Operators
 An arithmetic operator performs basic mathematical calculations such as
addition, subtraction, multiplication, division etc on numerical values
OOP Java is the easiest, scoring and my favorite subject

(constants and variables).

Exampl
Operator Meaning Description
e
+ Addition a+b Addition of a and b
- Subtraction a–b Subtraction of b from a
* Multiplication a*b Multiplication of a and b
/ Division a/b Division of a by b
Modulo division-
% a%b Modulo of a by b
remainder

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 51


Relational Operators
 A relational operators are used to compare two values.
OOP Java is the easiest, scoring and my favorite subject

 They check the relationship between two operands, if the relation is true,
it returns 1; if the relation is false, it returns value 0.
 Relational expressions are used in decision statements such as if, for,
while, etc…
Operator Meaning Example Description
< is less than a<b a is less than b
<= is less than or equal to a <= b a is less than or equal to b
> is greater than a>b a is greater than b
>= is greater than or equal a >= b a is greater than or equal to b
to
== is equal to a == b a is equal to b
!= is not equal to a != b a is not equal to b

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 52


Relational Operators Note : A = 10 &
B = 20

Operator Description Example


OOP Java is the easiest, scoring and my favorite subject

== Equals (A == B) is not
true.
!= Not Equals (A != B) is true.

> Greater than (A > B) is not


true.
< Less than (A < B) is true.

>= Greater than equals (A >= B) is not


true.
<= Less than equals (A <= B) is true.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 53


Bitwise Operators Note : A = 60 &
B = 13
Operato
Description Example
r OOP Java is the easiest, scoring and my favorite subject

A & B = 12 which is 0000


& Binary AND Operator
1100
A | B = 61 which is 0011
| Binary OR Operator
1101
A ^ B = 49 which is 0011
^ Binary XOR Operator
0001
~A = -61 which is 1100
Binary Ones Complement 0011 in 2's complement
~
Operator form due to a signed
binary number.
A << 2 = 240 which is
<< Binary Left Shift Operator
1111 0000
A >> 2 = 15 which is
>> Binary Right Shift Operator.
1111
A >>>2 = 15 which is
>>> Shift right zero fill operator.
0000 1111
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 54
Logical Operators
 Logical operators are decision making operators.
OOP Java is the easiest, scoring and my favorite subject

 They are used to combine two expressions and make decisions.


 An expression containing logical operator returns either 0 or 1 depending
upon whether expression results false or true.
Opera Example (Let’s assume c=5
Meaning
tor and d=2)
Logical AND. True only if all operands expression ((c==5) && (d>5))
&&
are true equals to 0.
Logical OR. True only if either one expression ((c==5) || (d>5))
||
operand is true equals to 1.
a if the
Logical NOT. True only b operand
a && b is a || b
! expression !(c==5) equals to 0.
false 0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 55
Logical Operators Note : A = true & B =
false

Operator Description Example


OOP Java is the easiest, scoring and my favorite subject

&& Logical AND operator (A && B) is false.

|| Called Logical OR Operator (A || B) is true.

! Called Logical NOT Operator !(A && B) is true.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 56


Assignment Operators
 Assignment operators are used to assign a new value to the variable.
 The left side operand of the assignment operator is a variable and right
OOP Java is the easiest, scoring and my favorite subject

side operand of the assignment operator is a value or a result of an


expression.
 Meaning of = in Maths and Programming is different.
 Value of LHS & RHS is always same in Math.
 In programming, value of RHS is assigned to the LHS
Operat Meaning
or
= Assigns value of right side to left side. Suppose a=5 and b=10. a=b
means now value of a is 10.
+= a += 1 is same as a = a + 1
-= a -= 5 is same as a = a – 5
*= a *= b is same as a = a * b Shorthand Assignment Operators
/= a /= c is same as a = a / c
%= a %= 10 is same as
Prof. Swati R Sharma a = a % 10
#2301CS201(OOP) Unit 01 – Introduction to java 57
Assignment Operators
Operator Description Example
OOP Java is the easiest, scoring and my favorite subject
C = A + B will assign
= Simple assignment operator
value of A + B into C
C += A is equivalent to C
+= Add AND assignment operator
=C+A
Subtract AND assignment C -= A is equivalent to C =
-=
operator C-A
C *= A is equivalent to C
*= Multiply AND assignment operator
=C*A
C /= A is equivalent to C =
/= Divide AND assignment operator
C/A
C %= A is equivalent to C
%= Modulus AND assignment operator
=C%A
Left shift AND assignment C <<= 2 is same as C = C
<<=
operator << 2
Right shift AND assignment C >>= 2 is same as C = C
>>=
operator >> 2
C &= 2 is same as C = C &
&= Bitwise AND assignment operator
Prof. Swati R Sharma #2301CS201(OOP) 2
Unit 01 – Introduction to java 58
Increment / Decrement Operators
 Increment and decrement operators are unary operators that add or
subtract one, to or from their operand. OOP Java is the easiest, scoring and my favorite subject

 the increment operator ++ increases the value of a variable by 1, e.g. a+


+ means a=a+1
 the decrement operator -- decreases the value of a variable by 1. e.g. a––
means a=a–1
 If ++ operator is used as a prefix (++a) then the value of a is
incremented by 1 first then it returns the value.
 IfExpressio
++ operator is used as a postfix (a++) then the value of a(Let’s
Evaluation is returned
say a=10,
Evaluation (Let’s say a=10, c=15) Expression
firstnthen it increments value of a by 1. c=15)
b = --a + c++
Value of b would be 10 and value of a b = 24
b = a++
would be 11. b = a++ + +
+c b = 26
b = ++a Value of b & a would be 11.
b = ++a - + b = –5
Value of b would be 10 and value of a +c
b = a--
would be 9.
b Prof.
= --aSwati R Value
Sharma of b & a would#2301CS201(OOP)
be 9. Unit 01 – Introduction to java 59
Conditional Operator (Ternary)
 Conditional Operator ( ? : )
 Syntax:
OOP Java is the easiest, scoring and my favorite subject

variable x = (expression) ? value if true : value if false


 Example:
b = (a == 1) ? 20 : 30;

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 60


OOP Java is the easiest, scoring and my favorite subject

Operators Precedence
& Associativity
Priority matters!
Operator Precedence & Associativity
 How does java evaluate 1 + 10 * 9 ?
 (1 + 10 ) * 9 = 99
OOP Java is the easiest, scoring and my favorite subject

OR 1 + (10 * 9) = 91
 To get the correct answer for the given problem Java came up with
Operator precedence.
 Multiplication have higher precedence than addition so correct answer will
be 91 in this case.
 For Operator, associativity means that when the same operator appears in
a row, then to which direction the expression will be evaluated.
 How does java evaluate 1 * 2 + 3 * 4 / 5 ???
2 + 12 / 5
2 + 2.4
4.4

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 62


Operators Precedence & Associativity
 Operators Precedence and Associativity are two
characteristics of operators that determine the OOP Java is the easiest, scoring and my favorite subject

evaluation order of sub-expressions in absence of


brackets.
 Operator precedence determines which operation is
performed first in an expression with more than one
operators with different precedence.
 a=10 + 20 * 30 is calculated as 10 + (20 * 30) and
not as (10 + 20) * 30 so answer is 610.
 Operators Associativity is used when two operators of
same precedence appear in an expression. Associativity
can be either Left to Right (L to R) or Right to Left (R to
L).
 a=100 / 10 * 10
 If Left to Right means (100 / 10) * 10 then answer
is 100
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 63
Precedence of Java Operators
Category Operator Associativity
OOP Java is the easiest, scoring and my favorite subject

Postfix () [] . (dot operator) Left to right


Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= Right to left
^= |=
Comma , Left to right
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 64
Operators Precedence and Associativity
1) Associativity is only used when there are two or more operators of
same precedence. OOP Java is the easiest, scoring and my favorite subject

2) All operators
Priori Opera
ty tor
Description with the same precedence have
Associati
vity
Priori
ty same
Operator associativity
Description
Associati
vity
() left-to- is equal to/is not equal left-to-
Parentheses (function call) 7 == != right
[] right to
Brackets (array subscript)
1 . left-to-
Member selection via object name 8 & Bitwise AND
a++ right
Postfix increment/decrement
a—
left-to-
Prefix increment/decrement right-to- 9 ^ Bitwise exclusive OR
++a right
Unary plus/minus left
—a left-to-
Logical negation/bitwise complement 10 | Bitwise OR
+– right
Cast (convert value to temporary
!~
2 value of type) left-to-
(type) 11 && Logical AND
De-reference right
*
Address (of operand)
& left-to-
Determine size in bytes on this 12 || Logical OR
sizeof right
implementation
right-to-
left-to- 13 ?: Ternary conditional
3 * / % Multiplication/division/modulus left
right
= Assignment right-to-
left-to- left
4 + – Addition/subtraction += -= *= /= Shorthand Assignments
right
%= &= Bitwise
<< left-to- 14 ^= |= exclusive/inclusive
5 Bitwise
Prof. Swati shift
R Sharma left, Bitwise shift right
#2301CS201(OOP) Unit 01 – Introduction to java 65
Exercise
Sr. Exercise Answer
OOP Java is the easiest, scoring and my favorite subject
1. int i=1; 4
i=2+2*i++;
2. int a=2,b=7,c=10; 0
c=a==b;
3. int a=2,b=7,c=10; 1
c=a!=b;
4. int a=100 + 200 / 10 - 3 * 10 90
5. int a = 2, b = 6, c = 12, d; 14
d = a * b + c / b;
System.out.println("The value of d ="+d);

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 66


Interview Questions
1. What is the default value of local variables in Java?
OOP Java is the easiest, scoring and my favorite subject

2. Can you compare a boolean with an int variable in Java?


3. Difference between double and float variables in Java.
4. Determine Output
class Main {
public static void main(String args[]) {

int t;
System.out.println(t);
}
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 67


Assignment
1 int i = 11;
. i = i++ + ++i;
OOP Java is the easiest, scoring and my favorite subject
24

2 int a=11, b=22, c; a=13


. c = a + b + a++ + b++ + + b=24
c=103
+a + ++b;
3 int i=0;
i=0
. i = i++ - --i + ++i - i--;

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 68


Object-Oriented Programming
2305CS102

Unit-1(Part-III)
Array and
Control
Statements
Prof. Swati R Sharma
Computer Engineering
Department
Darshan University, Rajkot
[email protected]
 Looping
What we will learn OOP Java is the easiest, scoring and my favorite subject

if, else, nested if, if-else ladder


switch
Looping Statement: while, do-while, for, foreach,
break and continue statement
Single and Multidimensional Array

Unit-1
OOP Java is the easiest, scoring and my favorite subject
Decision Making
 Compiler executes program statements sequentially.
OOP Java is the easiest, scoring and my favorite subject

 Decision making statements are used to control the flow of program


execution.
 It allows us to control whether a set of program statement should be
executed or not.
 It evaluates condition or logical expression first and based on its result
(true or false), the control is transferred to the particular statement.
 If result is true then it takes one path else it takes another path.
True conditi False
on

… …


Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 72
Decision Making Statements
 Commonly used decision making statements are
 One way Decision:
OOP Java is the easiest, scoring and my favorite subject

if (Also known as simple if)


 Two way Decision: if…else
 Multi way Decision: if…else if…else if…else
 Decision within Decision: nested if
 Two way Decision: ?: (Conditional Operator)
 n-way Decision: switch…case

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 73


OOP Java is the easiest, scoring and my favorite subject

if
One way Decision
if
 if statement is the most simple decision-making statement also known as
simple if. OOP Java is the easiest, scoring and my favorite subject

 An if statement consists of a boolean expression followed by one or more


statements.
 If the expression is true, then 'statement-inside' will be executed,
otherwise 'statement-inside' is skipped and only 'statement-outside' will
be executed.
 It is used to decide whether a block of statements will be executed or not
i.e ifconditio
a certain condition
False is if(condition)
true then a block of statement is executed
otherwise n not. {
// Statements to execute if condition
True
is true
statement-inside }

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 75


WAP to print if a number is positive
1.import java.util.*; OOP Java is the easiest, scoring and my favorite subject

2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5.Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println("number is a
positive");
9. }
10.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 76


Exercise
 Write a program which reads two numbers and based on different
between it prints either of following message DIFFERENCE IS POSITIVE or
OOP Java is the easiest, scoring and my favorite subject

DIFFERENCE IS NEGATIVE.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 77


WAP to print if a number is odd or even
1.import java.util.*; OOP Java is the easiest, scoring and my favorite subject

2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5.Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if( x % 2 == 1 ){
8. System.out.println("number is a odd");
9. }
10. if( x % 2 == 0 ){
11. System.out.println("number is a
even");
12. }
13.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 78


OOP Java is the easiest, scoring and my favorite subject

if…else
Two way Decision
If…else
 For a simple if, if a condition is true, the compiler executes a block of
OOP Java is the easiest, scoring and my favorite subject

statements, if condition is false then it doesn’t do anything.


 What if we want to do something when the condition is false? if…else is
used for the same.
 If the 'expression' is true then the 'statement-block-1' will get executed
else 'statement-block-2' will be executed. if(condition)
{
// statement-block-1
True conditio False // to execute if condition
n is true
}
else
statement- statement-
{
block-1 block-2
// statement-block-2
// to execute if condition
… is false
}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 80
WAP to print if a number is positive or negative
1.import java.util.*;
OOP Java is the easiest, scoring and my favorite subject

2.class MyProgram{
3.public static void main (String[] args){
4.int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if (x > 0){
8. System.out.println("Number is
positive");
9. }//if
10. else{
11. System.out.println("Number is
negative");
12. }//else
13. }//main
14.}//class
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 81
WAP to print if a number is odd or even
1.import java.util.*;
OOP Java is the easiest, scoring and my favorite subject

2.class MyProgram{
3.public static void main (String[] args){
4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if( x % 2 == 1 ){
8. System.out.println("number is a odd");
9. }
10. else{
11. System.out.println("number is a even");
12. }
13.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 82


Exercise
1. Any year is entered through the keyboard, write a program to determine
whether the year is leap or not. OOP Java is the easiest, scoring and my favorite subject

2. Write a program to check whether a triangle is valid or not, when the


three angles of the triangle are entered through the keyboard. A triangle
is valid if the sum of all the three angles is equal to 180 degrees.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 83


OOP Java is the easiest, scoring and my favorite subject

if…else if…else
Multi way Decision
if…else if…else
 if…else if…else statement is also known as if- if(condition 1)
else-if ladder which is used for multi way decision {
OOP Java is the easiest, scoring and my favorite subject

making. statement-block1;
}
 It is used when there are more than two different else if(condition 2)
conditions. {
 It tests conditions in a sequence, from top to statement-block2;
}
bottom.
else if(condition 3)
 If first condition is true then the associated block {
with if statement is executed and rest of the statement-block3;
conditions are skipped. }
else if(condition 4)
 If condition is false then then the next if condition {
will be tested, if it is true then the associated block statement-block4;
is executed and rest of the conditions are skipped. }
Thus it checks till last condition. else
default-statement;
 Condition is tested only and only when all previous
conditions are false.
 TheProf.last
Swati R else
Sharma is the default block Unit
#2301CS201(OOP) which will tobe
01 – Introduction java 85
if-else-if ladder
OOP Java is the easiest, scoring and my favorite subject

if(condition 1) conditio False


{ n1
statement-
block1;
} True conditio False
else if(condition 2)
{ n2
statement-
block2; … True conditio False
}
else if(condition 3) n3
{
statement- … True
block3;
}
else if(condition 4)
{ … …
statement-
block4;
}
else
default-
statement;
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 86
WAP to print if a number is zero or positive or
negative
1.import java.util.*;
2.class MyProgram{ OOP Java is the easiest, scoring and my favorite subject

3.public static void main (String[] args){


4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println(" number is a positive");
9. }
10. else if(x < 0) {
11. System.out.println(" number is a negative");
12. }
13. else{
14. System.out.println(" number is a zero");
15. }
16.}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 87
WAP to print day name from day number
1.public class Demo { OOP Java is the easiest, scoring and my favorite subject

2. public static void main(String[] args) {


3. int d;
4. Scanner sc = new Scanner(System.in);
5. d = sc.nextInt();
6. if (d == 1 ) System.out.println(“Monday”);
7. else if (d == 2) System.out.println(“Tuesday“);
8. else if (d == 3) System.out.println(“Wednesday“);
9. else if (d == 4) System.out.println(“Thursday“);
10. else if (d == 5) System.out.println(“Friday“);
11. else if (d == 6) System.out.println(“Saturday“);
12. else System.out.println(“Sunday“);
13. }
14.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 88


if-else statement: WAP to display Exam Result
1.int marks = 65; OOP Java is the easiest, scoring and my favorite subject

2.if (marks < 60) {


3. System.out.println("fail");
4.} else if (marks >= 60 && marks < 80)
{
5. System.out.println("B grade");
6.} else if (marks >= 80 && marks < 90)
{
7. System.out.println("A grade");
8.} else if (marks >= 90 && marks <
100) {
9. System.out.println("A+ grade");
10.} else {
11. System.out.println("Invalid!");
12.}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 89
Nested If
 A nested if is an if statement that is the target of OOP Java is the easiest, scoring and my favorite subject

if(condition 1)
another if statement. {
if(condition 2)
 Nested if statements mean an if statement inside {
another if statement. nested-block;
}
 The statement connected to the nested if else
statement is only executed when -: {
nested-block;
 condition of outer if statement is true, and }
 condition of the nested if statement is also true. }//if
else if(condition 3)
 Note: There could be an optional else statement {
associated with the outer if statement, which is statement-block3;
}
only executed when the condition of the outer if else(condition 4)
statement is evaluated to be false and in this {
case, the condition of nested if condition won't statement-block4;
}
be checked at all.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 90


Nested If statement:WAP Login
 We can also use if/else if statement inside another if/else if statement, this
is known as nested if statement. OOP Java is the easiest, scoring and my favorite subject

int username = Integer.parseInt(args[0]);


int password = Integer.parseInt(args[1]);
double balance = 123456.25;

if(username==1234){
if(password==987654){
System.out.println("Your Balance is
="+balance);
}
else{
System.out.println("Password is
invalid");
}
}
else{
System.out.println("Username is invalid");
}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 91
Exercise
 In a company an employee is paid as under:
 If his basic salary is less than Rs. 1500, then HRA = 10% of basic
OOP Java is the easiest, scoring and my favorite subject

salary and DA = 90% of basic salary.


 If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500
and DA = 98% of basic salary.
 Employee's salary is input through the keyboard, write a program to
find his gross salary.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 92


OOP Java is the easiest, scoring and my favorite subject

switch…case
n-way Decision
Switch…case
 switch…case is a multi-way decision OOP Java is the easiest, scoring and my favorite subject
switch (expression)
making statement. {
case constant 1:
 It is similar to if-else-if ladder statement. // Statement-1
break;
 It executes one statement from multiple
conditions. case constant 2:
// Statement-2
break;

case constant 3:
// Statement-3
break;

default:
// Statement-default
// if none of the above case
matches then this block would
be executed.
}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 94
Switch…case: WAP to print day based on
number entered
6.switch (d) {
1.public class Demo { 7. case 1:
2. public static void 8.
OOP Java is the easiest, scoring and my favorite subject
System.out.println(“Monday“); break;
main(String[] 9. case 2:
args){ 10. System.out.println(“Tuesday“); break;
3. int d; 11. case 3:
4. Scanner sc= new 12. System.out.println(“Wednesday“); break;
Scanner(System.in); 13. case 4:
5. d = sc.nextInt(); 14. System.out.println(“Thursday“); break;
15. case 5:
16. System.out.println(“Friday“); break;
17. case 6:
18. System.out.println(“Saturday“); break;
19. case 7:
20. System.out.println(“Sunday“); break;
21. default:
22. System.out.println(“Invalid Day“);
23. } //switch
24. }
25.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 95


Switch…case
 switch statement executes one statement from multiple conditions. It is
like if-else-if ladder statement. OOP Java is the easiest, scoring and my favorite subject

public class SwitchExampleDemo {


public static void main(String[] args)
{
int number = 20;
switch (number) {
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
default:
System.out.println("Not 10 or
20");
}
}
}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 96
Exercise
 Write a menu driven program that allows user to enters five numbers and
then choose between finding the smallest, largest, sum or average. Use
OOP Java is the easiest, scoring and my favorite subject

switch case to determine what action to take. Provide error message if an


invalid choice is entered.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 97


Points to remember for switch…case
 The condition in the switch should result in a constant value otherwise it
would be invalid. OOP Java is the easiest, scoring and my favorite subject

 Duplicate case values are not allowed.


 The value for a case must be of the same data type as the variable in the
switch.
 The value for a case must be a constant.
 variables are not allowed as an argument in switch statement.
 The break statement is used inside the switch to terminate a statement
sequence.
 The break statement is optional, if eliminated, execution will continue on
into the next case.
 The default statement is optional and can appear anywhere inside the
switch block.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 98


Exercise
 Write a Java program to get a number from the user and print whether it is
positive or negative. OOP Java is the easiest, scoring and my favorite subject

 Write a program to find maximum no from given 3 no.


 The marks obtained by a student in 5 different subjects are input through
the keyboard.
 The student gets a division as per the following rules:
 Percentage above or equals to 60-first division
 Percentage between 50 to 59-second division
 Percentage between 40 and 49-Third division
 Percentage less than 40-fail
Write a program to calculate the division obtained by the student.
 Write a Java program that takes a number from the user and displays the
name of the weekday accordingly (For example if user enter 1 program
should return Monday) .
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 99
OOP Java is the easiest, scoring and my favorite subject

Introduction to loop
Repeatedly execute a block of statements
Loop
 Sometimes we need to repeat certain actions several times or till the
some criteria is satisfied. OOP Java is the easiest, scoring and my favorite subject

 Loop constructs are used to iterate a block of statements several times.


 Loop constructs repeatedly execute a block of statements for a fixed
number of times or till some condition is satisfied
Flowchart of if Flowchart of while
(true-block executed only once)(true-block executed till condition is true)

conditio False conditio False


n n
True True

true-block true-block

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 101


Looping Statements
 Following are looping statements in any programming language,
 Entry Controlled while, for
OOP Java is the easiest, scoring and my favorite subject

 Exit Controlled do…while


 Unconditional Jump goto (It is advised to never use goto in a
program)

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 102


OOP Java is the easiest, scoring and my favorite subject

while
Entry Controlled Loop
while
 while is a entry controlled loop.
OOP Java is the easiest, scoring and my favorite subject

 It executes a block of statements till the condition is true.

while(condition) Flowchart of while


{ (true-block executed till condition is true)
// true-block
} False
conditio
n
int i = 1;
while (i <= 5) True
{
System.out.println(i); true-block
i++;
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 104


While Loop
 while loop is used to iterate a part of the program several times. while is
entry control loop. OOP Java is the easiest, scoring and my favorite subject

 If the number of iteration is not fixed, it is recommended to use while loop.


//code will print 1 to 9
public class WhileLoopDemo {
public static void main(String[] args) {
int number = 1;
while(number < 10) {
System.out.println(number);
number++;
}
}
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 105


Do-while Loop
 do-while loop is executed at least once because condition is checked after
loop body. OOP Java is the easiest, scoring and my favorite subject

//code will print 1 to 9


public class DoWhileLoopDemo {
public static void main(String[] args) {
int number = 1;
do {
System.out.println(number);
number++;
}while(number < 10) ;
}
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 106


WAP to print odd numbers between 1 to n
1. import java.util.*;
OOP Java is the easiest, scoring and my favorite subject
2. class WhileDemo{
3. public static void main (String[] args){
4. int n,i=1;
5. Scanner sc = new Scanner(System.in);
6. System.out.print("Enter a number:");
7. n = sc.nextInt();
Outp
8. while(i <= n){ ut
Enter a number:10
9. if(i%2!=0) 1
10. System.out.println(i); 3
5
11. i++; 7
12. } 9
13.}}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 107


WAP to print factors of a given number
1. import java.util.*;
OOP Java is the easiest, scoring and my favorite subject
2. class WhileDemo{
3. public static void main (String[] args){
4. int i=1,n;
5. Scanner sc = new Scanner(System.in);
6. System.out.print("Enter a Number:");
7. n = sc.nextInt();
Outp
8. System.out.print(" Factors:"); ut
Enter a Number:25
9. while(i <= n){ Factors:1,5,25
10. if(n%i == 0)
11. System.out.print(i +",");
12. i++;
13. }
14.}}
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 108
Exercise: while
1. WAP to print multiplication table using while loop
OOP Java is the easiest, scoring and my favorite subject

2. Write a program that calculates and prints the sum of the even integers
from 1 to 10.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 109


OOP Java is the easiest, scoring and my favorite subject

for(;;)
Entry Controlled Loop
for
 for is an entry controlled loop
OOP Java is the easiest, scoring and my favorite subject

 Statements inside the body of for are repeatedly executed till the
for(i=1; i <= 5; i+
condition is true
for (initialization; condition; increm int i = 1;
+)
ent while (i <= 5) {
{
/decrement)
{ System.out.print("He
System.out.print("H
// statements ll o World!");
ello World!");
} i++;
}
}
 The initialization statement is executed only once, at the beginning of
the loop.
 Then, the condition is evaluated.
 If the condition is true, statements inside the body of for loop are
executed
 If the condition is false, the for loop is terminated.
 Then, increment / decrement statement is executed
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 111
For Loop
 for loop is used to iterate a part of the program several times.
OOP Java is the easiest, scoring and my favorite subject

 If the number of iteration is fixed, it is recommended to use for loop.


//code will print 1 to 9
public class ForLoopDemo {
public static void main(String[] args)
{
for(int number=1;number<10;number++)
{
System.out.println(number);
}
}
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 112


WAP to print odd numbers between 1 to n
1. import java.util.*;
OOP Java is the easiest, scoring and my favorite subject
2. class MyProgram{
3. public static void main (String[] args)
{
4. int i=1;
5. Scanner sc = new
Scanner(System.in);
6. n = sc.nextInt();
7. for(i=1; i<=n; i++) {
8. if(i%2==1)
9. System.out.println(i);
10. }//for
11. }//
12.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 113


WAP to print factors of a given number
1. import java.util.*;
OOP Java is the easiest, scoring and my favorite subject
2. class MyProgram{
3. public static void main (String[]
args){
4. int i=1;
5. Scanner sc = new
Scanner(System.in);
6. n = sc.nextInt();
7. for(i=1; i<=n; i++){
8. if(n%i == 0)
9. System.out.println(i);
10. }
11. }
12.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 114


Exercise: for
 Write a program to print average of n numbers.
OOP Java is the easiest, scoring and my favorite subject

 Write a program that calculates and prints the sum of the even integers
from 1 to 10.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 115


OOP Java is the easiest, scoring and my favorite subject

do…while
Exit Controlled Loop
do…while
 do…while is an exit controlled loop.
OOP Java is the easiest, scoring and my favorite subject

 Statements inside the body of do…while are repeatedly executed till the
condition is true.
 while
do loop executes zero or more times, do…while loop executes one or
more
{ times. Flowchart of while Flowchart of do…while
// true-
block
conditio False
} true-block
while(condition) n
; True
conditio
true-block True n
False

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 117


WAP to print 1 to 10 using do-while loop
1. import java.util.*;
OOP Java is the easiest, scoring and my favorite subject
2. class MyProgram{
3. public static void main (String[]
args){
4. int i=1;
5. do{
6. System.out.println(i);
7. i++;
8. }while(i <= 10);
9. }
10.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 118


OOP Java is the easiest, scoring and my favorite subject

continue
Skip the statement in the iteration
continue
 Sometimes, it is required to skip the remaining statements in the loop and
continue with the next iteration. OOP Java is the easiest, scoring and my favorite subject

 continue statement is used to skip remaining statements in the loop.


 continue is keyword.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 120


WAP to calculate the sum of positive numbers.
1.import java.util.*;
2.class ContinueDemo{ OOP Java is the easiest, scoring and my favorite subject

3.public static void main(String[] args) {


4.int a,n,sum=0;
5.Scanner sc = new Scanner(System.in);
6.n = sc.nextInt();
7.for(int i=0;i<n;i++){
8. a = sc.nextInt();
9. if(a<0){
10. continue;
11. System.out.println("a="+a);//error:unreachable
statement
12. }//if
13. sum=sum+a;
14.}//for
15. System.out.println("sum="+sum);
16. }
17.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 121


OOP Java is the easiest, scoring and my favorite subject

break
Early exit from the loop
break
 Sometimes, it is required to early exit the loop as soon as some situation
occurs. OOP Java is the easiest, scoring and my favorite subject

 E.g. searching a particular number in a set of 100 numbers. As soon as the


number is found it is desirable to terminate the loop.
 break statement is used to jump out of a loop.
 break statement provides an early exit from for, while, do…while and
switch constructs.
 break causes exit from the innermost loop or switch.
 break is keyword.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 123


WAP to calculate the sum of given numbers. User will enter -1 to terminate.

1.import java.util.*;
2.class BreakDemo{ OOP Java is the easiest, scoring and my favorite subject

3.public static void main (String[] args){


4. int a,sum=0;
5. System.out.println("enter numbers_ enter -1 to break");
6. Scanner sc = new Scanner(System.in);
7. while(true){
8. a = sc.nextInt();
9. if(a==-1)
10. break;
11. sum=sum+a;
12. }//while
13. System.out.println("sum="+sum);
14. }
15.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 124


Types of loops
Entry Control Entry Control Virtual
Exit Control Loop
Loop Loop Loop
int i=1; int i; int i=1;
OOP Java is the easiest, scoring and my favorite subject
int i=1;
while(i<=10) for(i=1;i<=10;i+ do p: i++;
{ +) { if(i<=10)
i++; { i++; goto p;
} i++; }
} while(i<=10);

False Label
conditi Statement
on Loop Body
True True conditi
True conditi on
Loop Body got
on o
False
False labe
l
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 125
OOP Java is the easiest, scoring and my favorite subject

nested loop
loop within a loop
WAP to print given pattern (nested loop)
* 1.class PatternDemo{
OOP Java is the easiest, scoring and my favorite subject

** 2.public static void main(String[] args) {


*** 3. int n=5;
**** 4. for(int i=1;i<=n;i++){
***** 5. for(int j=1;j<=i;j++){
6. System.out.print("*");
7. }//for j
8. System.out.println();
9. }//outer for i
10. }
11.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 127


WAP to print given pattern (nested loop)
1 1.class PatternDemo{
OOP Java is the easiest, scoring and my favorite subject

1 2 2.public static void main(String[] args) {


1 2 3 3. int n=5;
1 2 3 4 4. for(int i=1;i<=n;i++){
1 2 3 4 5. for(int j=1;j<=i;j++){
5 6. System.out.print(j+"\t");
7. }//for j
8. System.out.println();
9. }//outer for i
10. }
11.}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 128


Programs to perform (Looping Statements)
 Write a program to print first n odd numbers.
OOP Java is the easiest, scoring and my favorite subject

 Write a program to check that the given number is prime or not.


 Write a program to draw given patterns,

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 129


OOP Java is the easiest, scoring and my favorite subject

Introduction to Array
Large Data Handling
Why Array?
 Very often we need to deal with relatively large set of
data. OOP Java is the easiest, scoring and my favorite subject

 E.g.
 Percentage of all the students of the college. (May be in
thousands)
 Age of all the citizens of the city. (May be lakhs)
 We need to declare thousands or lakhs of the variable
to store the data which is practically not possible.
 We need a solution to store more data in a single
variable.
 Array is the most appropriate way to handle such
data.
 As per English Dictionary, “Array means collection
or group or arrangement in a specific order.”

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 131


Array
 An array is a fixed size sequential collection of elements of same
data type grouped under single variable name. OOP Java is the easiest, scoring and my favorite subject

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
int percentage[10
];
Fixed Size Sequential Same Data type Single Variable
Name
The size of an array All the elements of Data type of all the
is fixed at the time an array are stored elements of an All the elements of
of declaration in a consecutive array is same which an array will be
which cannot be blocks in a memory. is defined at the referred through
changed later on. time of declaration. common name.
10 (0 to 9)
Here array size is Here data type is Here array name
10. int is percentage

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 132


Array declaration
 Normal Variable Declaration: int a;
OOP Java is the easiest, scoring and my favorite subject

 Array Variable Declaration: int b[10];


 Individual value or data stored in an array is
known as an element of an array.
 Positioning / indexing of an elements in an
array always starts with 0 not 1.
 If 10 elements in an array then index is 0
to 9
 If 100 elements in an array then index is
0 to 99
 If 35 elements in an array then index is 0
to 34
 Variable a stores 1 integer number where as
variable b stores 10 integer numbers which
can be accessed as b[0], b[1], b[2], b[3],
b[4],
Prof. b[5], b[6], b[7], b[8]
Swati R Sharma and b[9]Unit 01 – Introduction to java
#2301CS201(OOP) 133
Array
 Important point about Java array.
 An array is derived datatype. OOP Java is the easiest, scoring and my favorite subject

 An array is dynamically allocated.


 The individual elements of an array is refereed by their index/subscript value.
 The subscript for an array always begins with 0.

35 13 28 106 35
a 42 5 83 97 14
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 134


One-Dimensional Array
 An array using one subscript to represent the list of elements is called
one dimensional array. OOP Java is the easiest, scoring and my favorite subject

 A One-dimensional array is essentially a list of like-typed variables.


 Array declaration:type var-name[];
Example: int student_marks[];
 Above example will represent array with no value (null).
 To link student_marks with actual array of integers, we must allocate one
using new keyword.
Example: int student_marks[] = new int[20];

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 135


Example (Array)
public class ArrayDemo{ OOP Java is the easiest, scoring and my favorite subject

public static void main(String[] args) {


int a[]; // or int[] a
// till now it is null as it does not assigned any memory

a = new int[5]; // here we actually create an array


a[0] = 5;
a[1] = 8;
a[2] = 15;
a[3] = 84;
a[4] = 53;

/* in java we use length property to determine the length


* of an array, unlike c where we used sizeof function */
for (int i = 0; i < a.length; i++) {
System.out.println("a["+i+"]="+a[i]);
}
}
}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 136


WAP to store 5 numbers in an array and print
them
1. import java.util.*;
OOP Java is the easiest, scoring and my favorite subject

2. class ArrayDemo1{
3. public static void main (String[] args){
4. int i, n;
5. int[] a=new int[5];
6. Scanner sc = new Scanner(System.in);
7. System.out.print("enter Array Length:"); Output:
8. n = sc.nextInt(); enter Array
Length:5
9. for(i=0; i<n; i++) {
enter a[0]:1
10. System.out.print("enter a["+i+"]:"); enter a[1]:2
11. a[i] = sc.nextInt(); enter a[2]:4
12. } enter a[3]:5
13. for(i=0; i<n; i++) enter a[4]:6
14. System.out.println(a[i]); 1
15. } 2
16.} 4
5
6

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 137


For-each loop
1. class Array1{ Limitations of for-each loop
OOP Java is the easiest, scoring and my favorite subject

1. For-each loops are not appropriate when you


2. public static void main(String[]want args) { the array.
to modify
3. int a[ ]={10,20,30,40,50};2. For-each loops do not keep track of
index. So we can not obtain array index
4. for(int i : a){// for each using For-Each loop.
3. For-each only iterates forward over the
5. System.out.println(i); array in single steps.
4. For-each cannot process two decision
6. }
making statements at once.
7. } 5. For-each also has some performance
overhead over simple iteration.
8. }

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 138


WAP to print elements of an array in reverse
order
1. import java.util.*; OOP Java is the easiest, scoring and my favorite subject

2. public class RevArray{


3. public static void main(String[] args) {
4. int i, n;
5. int[] a;
6. Scanner sc=new Scanner(System.in);
7. System.out.print("Enter Size of an Array:"); Output:
8. n=sc.nextInt();
Enter Size of an
9. a=new int[n];
Array:5
10. for(i=0; i<n; i++){
enter a[0]:1
11. System.out.print("enter a["+i+"]:");
enter a[1]:2
12. a[i]=sc.nextInt();
enter a[2]:3
13. }
enter a[3]:4
14. System.out.println("Reverse Array");
enter a[4]:5
15. for(i=n-1; i>=0; i--)
Reverse Array
16. System.out.println(a[i]);
5
17. }
4
18.}
3
2
1
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 139
WAP to count positive number, negative number and zero from an array of n size

1. import java.util.*;
2. class ArrayDemo1{ OOP Java is the easiest, scoring and my favorite subject

3. public static void main (String[] args){


4. int n,pos=0,neg=0,z=0;
5. int[] a=new int[5];
6. Scanner sc = new Scanner(System.in);
7. System.out.print("enter Array Length:");
8. n = sc.nextInt(); Output:
9. for(int i=0; i<n; i++) {
enter Array
10. System.out.print("enter a["+i+"]:");
11. a[i] = sc.nextInt(); Length:5
12. if(a[i]>0) enter a[0]:-3
13. pos++; enter a[1]:5
14. else if(a[i]<0) enter a[2]:0
15. neg++; enter a[3]:-2
16. else enter a[4]:00
17. z++; Positive no=1
18. } Negative no=2
19. System.out.println("Positive no="+pos);
Zero no=2
20. System.out.println("Negative no="+neg);
21. System.out.println("Zero no="+z);
22. }}

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 140


Exercise: Array
1. WAP to count odd and even elements of an array.
OOP Java is the easiest, scoring and my favorite subject

2. WAP to calculate sum and average of n numbers from an array.


3. WAP to find largest and smallest from an array.

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 141


OOP Java is the easiest, scoring and my favorite subject

Multidimensional Array
Multidimensional Array
OOP Java is the easiest, scoring and my favorite subject

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 143


WAP to read 3 x 3 elements in 2d array
1. import java.util.*;
2. class Array2Demo{ Column-0 Column-1 Column-2
3. public static void main(String[] args) {
OOP Java is the easiest, scoring and my favorite subject

4. int size; Row-0 11 18 -7


5. Scanner sc=new Scanner(System.in);
6. System.out.print("Enter size of an array");
7. size=sc.nextInt(); Row-1 25 100 0
8. int a[][]=new int[size][size];
9. for(int i=0;i<a.length;i++){ Row-2 -4 50 88
10. for(int j=0;j<a.length;j++){
11. a[i][j]=sc.nextInt(); Output:
12. } 11
13. } 12
13
14. for(int i=0;i<a.length;i++){ 14
15. for(int j=0;j<a.length;j++){ 15
16. System.out.print("a["+i+"]["+j+"]:"+a[i][j] 16
+"\t"); 17
17. } 18
18. System.out.println(); 19
19. } a[0][0]:11 a[0][1]:12 a[0]
20. } [2]:13
21.} a[1][0]:14 a[1][1]:15 a[1]
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction [2]:16
to java 144
WAP to perform addition of two 3 x 3 matrices
1.import java.util.*; 1.b=new int[size][size];
OOP Java is the easiest, scoring and my favorite subject

2.class Array2Demo{ 2.for(int i=0;i<b.length;i++){


3.public static void main(String[] args) { 3. for(int j=0;j<b.length;j++){
4.int size; 4. System.out.print("Enter
5.int a[][],b[][],c[][]; b["+i+"]
6.Scanner sc=new Scanner(System.in); ["+j+"]:");
7. System.out.print("Enter size of an 5. b[i][j]=sc.nextInt();
array:");
6. }
8. size=sc.nextInt();
7.}
9. a=new int[size][size];
8.c=new int[size][size];
10. System.out.println("Enter array
elements:");
9.for(int i=0;i<c.length;i++){
11.for(int i=0;i<a.length;i++){ 10. for(int j=0;j<c.length;j++){
12. for(int j=0;j<a.length;j++){ 11. System.out.print("c["+i+"]
13. System.out.print("Enter ["+j+"]:“ +(a[i][j]+b[i]
a["+i+"]["+j+"]:"); [j])+"\t");
14. a[i][j]=sc.nextInt(); 12. }
15. } 13. System.out.println();
16.} 14. }
15. }//main()
Prof. Swati R Sharma #2301CS201(OOP) Unit 01 –16.}//class
Introduction to java 145
WAP to perform addition of two 3 x 3 matrices
Output:
OOP Java is the easiest, scoring and my favorite subject

Enter size of an array:3


Enter array elements:
Enter a[0][0]:1
Enter a[0][1]:1
Enter a[0][2]:1
Enter a[1][0]:1
Enter a[1][1]:1
Enter a[1][2]:1
Enter a[2][0]:1
Enter a[2][1]:1
Enter a[2][2]:1
Enter b[0][0]:4
Enter b[0][1]:4
Enter b[0][2]:4
Enter b[1][0]:4
Enter b[1][1]:4
Enter b[1][2]:4
Enter b[2][0]:4
Enter b[2][1]:4
Enter b[2][2]:4
c[0][0]:5 c[0][1]:5 c[0]
[2]:5
c[1][0]:5 c[1][1]:5 c[1]
Matrix Multiplication

OOP Java is the easiest, scoring and my favorite subject

A[0][0] A[0][1] A[0][2] B[0][0] B[0][1] B[0][2]

A[1][0] A[1][1] A[1][2] B[1][0] B[1][1] B[1][2]

A[2][0] A[2][1] A[2][2] B[2][0] B[2][1] B[2][2]

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 147


Initialization of an array elements
1. One dimensional Array
OOP Java is the easiest, scoring and my favorite subject
1. int a[ ] = { 7, 3, -5, 0, 11 }; // a[0]=7, a[1] = 3, a[2] = -5, a[3] = 0, a[4] = 11
2. int a[ ] = { 7, 3 }; // a[0] = 7, a[1] = 3
3. int a[ ] = { 0 }; // all elements of an array are initialized to 0

2. Two dimensional Array


1. int a[ ][ ] = { { 7, 3, -5, 10 }, { 11, 13, -15, 2} }; // 1st row is 7, 3, -5, 10 & 2nd row
is 11, 13, -15, 2

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 148


Multi-Dimensional Array
 In java, multidimensional array is actually array of arrays.
OOP Java is the easiest, scoring and my favorite subject

 Example: int runPerOver[][] = new int[3][6];

First Over (a[0]) 4 0 1 3 6 1


a[0][0]a[0][1]a[0][2]a[0][3]a[0][4]a[0][5]

Second Over (a[1]) 1 1 0 6 0 4


a[1][0]a[1][1]a[1][2]a[1][3]a[1][4]a[1][5]

Third Over (a[2]) 2 1 1 0 1 1


a[2][0]a[2][1]a[2][2]a[2][3]a[2][4]a[2][5]

 length field:
 If we use length field with multidimensional array, it will return length of first
dimension.
 Here, if runPerOver.length is accessed it will return 3
 Also if runPerOver[0].length is accessed it will be 6

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 149


Multi-Dimensional Array (Example)
Scanner s = new Scanner(System.in); OOP Java is the easiest, scoring and my favorite subject

int runPerOver[][] = new int[3][6];


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
System.out.print("Enter Run taken" +
" in Over numner " + (i + 1) +
" and Ball number " + (j + 1) + " = ");
runPerOver[i][j] = s.nextInt();
}
}
int totalRun = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
totalRun += runPerOver[i][j];
}
}
double average = totalRun / (double) runPerOver.length;
System.out.println("Total Run = " + totalRun);
System.out.println("Average per over = " + average);

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 150


Multi-Dimensional Array (Cont.)
 manually allocate different size:
OOP Java is the easiest, scoring and my favorite subject
int runPerOver[][] = new int[3][];
runPerOver[0] = new int[6];
runPerOver[1] = new int[7];
runPerOver[2] = new int[6];
 initialization:
int runPerOver[][] = {
{0,4,2,1,0,6},
{1,-1,4,1,2,4,0},
{6,4,1,0,2,2},
}
Note : here to specify extra runs (Wide, No Ball etc.. ) negative values are
used

Prof. Swati R Sharma #2301CS201(OOP) Unit 01 – Introduction to java 151


OOP Java is the easiest, scoring and my favorite subject

Thank You

You might also like