OOP Unit1
OOP Unit1
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity
that has state and behavior is known as an object. Object can be
defined as an instance of a class. An object contains an
address and takes up some space in memory. Objects can
communicate without knowing details of each other'sdata or code, the
only necessary thing is that the type of message accepted and
1
type of response returned by the objects. An object has three
characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such
as deposit, withdraw etc.
• identity: Object identity is typically implemented via a uniqueID.
The value of the ID is not visible to the external user.
But it is used internally by the JVM to identify each
object uniquely.
CLASS
Collection of objects is called class. It is a logical entity. A
class can also be defined as a blueprint from which you can
create an individual object. A class consists of Data members and
methods. The primary purpose of a class is to hold
data/information. The member functions determine the behavior of the
class, i.e. provide a definition for supporting various operations on
data held in the form of an object. Class doesn’t store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring
all the properties and behavior of one class to another, i.e.,
acquiring the properties and behavior of child class from the parent
class. When one object acquires all the properties and behaviours of
another object, it is known as inheritance. It provides code
reusability and establishes relationships between different classes. A
class which inherits the properties is known as Child Class (sub-class or
derived class) whereas a class whose properties are inherited is
known as Parent class (super-class or base class). Types of inheritance in
java: single, multilevel and hierarchical inheritance. Multiple and hybrid
inheritance is supported through interface only.
POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism.
For example: to convince
the customer differently, to draw something e.g. shape or rectangle etc.
2
Polymorphism is classified into two ways:
ABSTRACTION
Abstraction is a process of hiding the implementation details and
showing only functionality to the user. For example: phone call, we
don't know the internal processing. In java, we use abstract class
and interface to achieve abstraction.
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data
together into a single unit, for example capsule i.e. mixed of
several medicines. A java class is the example of encapsulation
3
1.1 OBJECT ORIENTED PROGRAMMING PARADIGMS
4
Object-oriented programming (OOP) is a programming paradigm based upon
objects that aims to incorporate the advantages of modularity and
reusability. Objects, which are usually instances of classes, are
used to interact with one another to design applications and computer
programs.
Object–Oriented Analysis (OOA) is the procedure of identifying software
engineering requirements and developing software specifications in terms of a
software system’s object model, which comprises of interacting objects.
5
POP does not have any access OOP has access specifiers named
specifier. Public, Private,
Protected, etc.
In POP, Data can move freely In OOP, objects can move
from function to function and communicate with each
in the system. other through member
functions.
To add new data and function OOP provides an easy way to
in POP is not so add new data and function.
easy.
In POP, most function uses In OOP, data cannot move easily
Global data for sharing from function to function,
that can be accessed it can be kept public or
freely from function to private so we can
function in the system. control the access of
data.
POP does not have any proper OOP provides Data Hiding so
way for hiding data so provides more security.
it is less secure.
In POP, Overloading is not In OOP, overloading is possible
possible. in the form of
Function Overloading and Operator
Overloading.
Example of POPare: C, VB, Example of OOP are: C++,
FORTRAN, JAVA, VB.NET, C#.NET.
Pascal.
OOP stands for Object Oriented Programming and the language that support this
Object-Oriented programming features is called Object oriented Programming
Language. An example of a language that support this Object-
oriented feature is Java. The Objects Oriented programming language
supports all the features of normal programming languages. In
addition, it supports some important concepts and terminology which has
made it popular among programming methodology.
Inheritance
Polymorphism
Data Hiding
Encapsulation
Overloading
6
Reusability
Objects
Classes Objects:
In other words, object is an instance of a class.
Classes:
These contain data and functions bundled together under a unit. In
other words, class is a collection of similarobjects. When we define a
class, it just creates template or Skelton. So, no memory is
created when class is created. Memory is occupied only by
object.
Example:
Class classname
{
Data
Functions
};
main ( )
{
classname objectname1,objectname2,..;
}
Member functions:
7
The functions defined inside the class as above are called member functions.
Example:
Class classname
priv
ate:
datatype data;
public:
Member functions
};
main ( )
{
8
classname objectname1,objectname2,..;
}
Encapsulation:
The technical term for combining data and functions together as
a bundleis encapsulation.
Inheritance:
Inheritance as the name suggests is the concept of inheriting or
deriving properties of an exiting class to get new class or classes.
In other words we may have common features or characteristics that
may be needed by number of classes. So those features can
be placed in a common tree class called base class and the other
classeswhich have these charaterisics can take the tree class and define only the
new things that they have on their own in their classes. These classes are
called derived class. The main advantage of using this concept of
inheritance in Object oriented programming is it helps in reducing the
code size since the common characteristic is placed separately called as
base class and it is just referred in the derived class. This
provide the users the important usage of terminology called as reusability
Reusability:
This usage is achieved by the above explained terminology called as
inheritance. Reusability is nothing but re- usage of structure without
changing the existing one but adding new features or characteristics
to it. It is very much needed for any programmers in different
situations. Reusability gives the following advantages to user. It helps in
reducing the code size since classes can be just derived from existing
one and one need to add only the new features and it helps
users to save their time.
9
the place they are present is called Polymorphism. Overloading is a
kind of polymorphism. In other words say for instance we know that
+, – operate on integer data type and is used to perform
arithmetic additions and subtractions. But operator overloading is one in
which we define new operations to these operators and make them operate
on different data types in other words overloading the existing
functionality with new one. This is a very important feature of
object oriented programming methodology which extended the handling of
data type and operations.
Thus the above given important features of object oriented programming among the
numerous
features it have gives the following advantages to the programming world.
2. OVERVIEW OF JAVA
1. What is Java? Explain the internal architecture of JVM with neat sketch?(13) (NOV/DEC 2019)
2. How Java changed the internet?(9) (APR/MAY 2021)
3. If semicolons are needed at the end of each statement, why does the comment line not end with a
semicolon ?(4) (APR/MAY 2021)
4. Outline the arithmetic operators in Java.(6) (NOV/DEC 2021)
5. Name the four integer types in Java and outline the bitwise operators that can be applied to the
integer types.(7) (NOV/DEC 2021)
6. Outline the iteration statements in Java with syntax and example.(9) (NOV/DEC 2021)
7. What are the three categories of control statements used in Java ? Explain each category with
example.(13) (APR/MAY 2021)
8. Write a java code using do-while loop that counts down to 1 from 10 printing exactly ten lines of
“Hello”(6) (APR/MAY 2019)
The Java platform differs from most other platforms in the sense that it is
a software-based platform that runs on the top of other hardware-
based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
12
Java code can be run on multiple platforms e.g. Windows, Linux, Sun
Solaris, Mac/OS etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms i.e. Write
Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox
These security are provided by java language. Some security can also
be provided by application developer through SSL, JAAS, Cryptography etc.
JRE
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit
(JDK) is a software development environment which is used to develop
java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms
released by Oracle corporation: Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
14
The JDK contains a private Java Virtual Machine (JVM) and a few
other resources such as an interpreter/loader (Java), a compiler (javac),
an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.
Data types specifythe different sizes and values that can be stored in the
variable. There are two types of data types in Java:
15
1. Primitive data types: The primitive data types include Integer, Character,
Boolean, and Floating Point.
2. Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
• Integers This group includes byte, short, int, and long, which are for
whole-valued signed numbers.
Example :
// Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
16
int
lightspee
d; long
days;
long
seconds;
long
distance;
Output:
In 1000 days light will travel about 1607040000000miles. Clearly, the result
could not have been held in an int variable.
2.2 VARIABLES
A variable is a container which holds the value and that can
be changed durig the execution of the program. A variable
is assigned with a datatype. Variable is a name of
memory location. All the variables must be declared before they
can be used. There are three types of variables in java: local
variable, instance variable and static variable.
20
Local Variable
17
A variable defined within a block or method or constructor is
called local variable.
• These variable are created when the block in entered or the
function is called and destroyed after exiting from the block or
when the call returns from the function.
• The scope of these variables exists only within the block in which the
variable is declared. i.e.
we can access these variable only within that block.
Example:
import java.io.*;
public class StudentDetails
{
public void
StudentAge() {
//localvariable
age int
age = 0;
age = age +
5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new
StudentDetails(); obj.StudentAge();
}
}
Output:
Student age is : 5
Instance Variable
18
import
java.io.*;
class
Marks{
int m1;
int m2;
}
class MarksDemo
{
public static void main(String args[])
{ //first object
Marks obj1 = new
Marks();
obj1.m1 =
50; obj1.m2
= 80;
//second
object
Marks obj2 = new
Marks();
obj2.m1 =
80; obj2.m2
= 60;
//displaying marks for first object
System.out.println("Marks for first object:");
System.out.println(obj1.m1);
System.out.println(obj1.m2);
//displaying marks for second object
System.out.println("Marks for second object:");
System.out.println(obj2.m1);
System.out.println(obj2.m2);
}}
Output:
Marks for first object:
50
80
Marks for second object:
80
60
Static variable
Static variables are also known as Class variables.
19
These variables are declared similarly as instance variables, the
difference is that static variables are declared using the static
keyword within a class outside any method constructor or
block.
Unlike instance variables, we can only have one copy of a static
variable per class irrespective of how many objects we create.
Example:
import java.io.*;
class
Emp {
// static variable salary public static double
salary; public static String name = "Vijaya";
}
public class EmpDemo
{
public static void main(String args[]) {
}
}
Output:
Vijaya’s average salary:10000.0
20
object has its own copy of instance variables are common to
variable all object of a class.
2.3 ARRAYS
21
Code Optimization: It makes the code optimized, we can retrieve
or sort the data easily. Random access: We can get any
data located at any index position.
Size Limit: We can store only fixed size of elements in the array.
It doesn't grow its size at runtime. To solve this
problem, collection framework is used in java.
One-Dimensional Arrays
An array is a group of like-typed variables that are referred to
by a common name. An array declaration has two components: the
type and the name. type declares the element type of the
array. The element type determines the data type of each element
that comprises the array. We can also create an array of other
primitive data types like char, float, double..etc or user defined data
type(objects of a class).Thus, the element type for the array
determines what type of data the array will hold.
Syntax: type
var-name[
];
Instantiation of an
Array in java array-
var = new type [size];
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration
and instantiation a[0]=10;//initialization
a[1]=20; a[2]=70; a[3]=40;
a[4]=50; //printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
22
70
40
50
Multidimensional Arrays
23
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other array. These are also known as
Jagged Arrays. A multidimensional array is created by appending
one set of square brackets ([]) per dimension. Syntax:
type var-name[ ][ ]=new type[row-size ][col-size ];
Example:
// Demonstrate a two-
dimensional array. class
TwoDArray {
public static void main(String
args[]) { int twoD[][]=
new int[4][5];
int i, j,
k =
0;
for(i=0;
i<4; i++)
for(j=0;
j<5; j++)
{
twoD[i][j]
= k;
k++;
}
for(i=0; i<4; i++)
{ for(j=0;
j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
24
When you allocate memory for a multidimensional array, you need
only specifythe memory for the first (leftmost) dimension. You can
allocate the remaining dimensions separately. For example, this
following code allocates memory for the first dimension of twoD
when it is declared. It allocates the second dimension
manually.
Syntax:
int twoD[][] =
new int[4][];
twoD[0] =
new int[5]; twoD[1]
= new int[5];
twoD[2] =
new int[5]; twoD[3]
= new int[5];
Example:
// Manually allocate
differing size second
dimensions. class TwoDAgain {
public static void main(String
args[])
{
int twoD[][] =
new int[4][];
twoD[0] =
new int[1]; twoD[1]
= new int[2];
twoD[2] =
new int[3]; twoD[3]
= new int[4];
int i, j, k = 0;
25
for(i=0; i<4; i++)
for(j=0; j<i+1; j++)
{
twoD[i][j] =
k; k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
0
12
3 4 5
6 7 8 9
The array created by this program looks like this:
Operator Result
Example:
// Demonstrate the basic arithmetic
operators. class BasicMath
{
public static void main(String args[])
{
// arithmetic using integers
System.out.println("Integer Arithmetic"); int a
= 1
+
1;
int
b
=
a
*
3;
int
c
=
b
/
4;
int
d
=
27
c
-
a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println ("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}}
Output:
Integer
Arithmeti
ca =
2 b
= 6
c =
1 d
= -1
e = 1
Floating Point
Arithmetic
da =
2.0 db
= 6
dc =
1.5 dd
= -0.5
de =
0.5
28
Modulus Operator
The modulus operator, %, returns the remainder of a division
operation. It can be applied to floating-point types as well as
integer types.
Example:
// Demonstrate the %
operator. class Modulus
{
public static void main(String
args[]) { int x =
42; double y =
42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Output:
x mod 10
= 2
y
mod 10
=
2.25
a =
6
b
=
8
c = 3
31
Bitwise Operators
Example:
// Demonstrate the bitwise logical operators. class
BitLogic
{
public static void main(String args[])
{
String binary[] = {"0000", "0001", "0010", "0011", "0100",
"0101", "0110", "0111", "1000", "1001",
"1010", "1011", "1100", "1101",
"1110", "1111"}; int a =
3; // 0 + 2 + 1
or 0011 in binary int b =
6; // 4 + 2 + 0
32
or 0110 in binary int c
= a | b;
int d = a
& b; int
e = a
^ b; int f
= (~a &
b)|(a & ~b);
int g =
~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
Output: a
= 0011
b =
0110 a|b
= 0111
a&b =
0010 a^b
= 0101
~a&b|a&~b
= 0101
~a = 1100
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
33
}
}
Output:
40
80
80
240
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output:
2
5
2
Relational Operators
The relational operators determine the relationship that one operand
has to the other.Specifically, they determine equality and
ordering. The outcome of these operations is a boolean
value. Boolean Operators
The Boolean logical operators shown here operate only on boolean
operands. All of the binary logical operators combine two boolean
values to form a resultant boolean value.
34
Example:
// Demonstrate the boolean logical
operators. class BoolLogic
{
public static void main(String args[])
{
boolean a = true; boolean
b = false; boolean c
= a | b; boolean
d= a & b;
boolean e = a ^
b;
boolean f = (!a &
b) | (a & !b);
boolean g =
!a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
Output:
a = true b
= false a|b
= true a&b
= false a^b
= true
35
!a&b|a&!b =
true !a=false
In the output, the string representation of a Java boolean value
is one of the literal values true or false. Java AND Operator
Example: Logical && and Bitwise &
The logical && operator doesn't check second condition if first
condition is false. It checks second condition only if first one
is true.
The bitwise & operator always checks both conditions whether first
condition is true or false.
Example: class OperatorExample
{
public static void main(String args[])
{
int a=10;int b=5; int c=20;
System.out.println(a<b&&a<c);//false && true=
false System.out.println(a<b&a<c);//false
& true = false
}
}
Output:
fal
se
fal
s
e
Assignment Operator
Ternary Operator
Ternary operator in java is used as one liner replacement for if-then-
else statement and used a lot in java programming. it is the
only conditional operator which takes three operands.
Syntax:
36
expression1 ? expression2 :
expression3 Example: class
OperatorExample
{
public static void main(String args[])
{
int a=2; int b=5;
int
min=(a<b)?a:b;
System.out.println(
min);
}
}
Output:
2
if Statement
if statement is the most simple decision making statement. It is
used to decide whether a certain statement or block of
statements will be executed or not that is if a certain
condition is true then a block of statement is executed
otherwise not.
Syntax:
if(condition)
{
//statements to execute if
//condition is true
}
37
Condition after evaluation will be either true or false. If the value is
true then it will execute the block of statements under it. If
there are no curly braces ‘{‘ and ‘}’ after if( condition ) then
by defaultif statement will consider the immediate one statement
to be inside its block.
Example:
class IfSample
{
public static void main(String args[])
{ int
x,
y;
x
=1
0; y
=
20
;
if(
x <
y)
System.out.println("x is less
than y"); x = x
* 2; if(x == y)
System.out.println("x now
equal to y") x
= x * 2; if(x
> y)
System.out.println("x now greater than y");
38
// this won't
displayanything if(x
== y)
System.out.println("you won't see this");
}
}
Output:
x is less
than y x
now equal
to y x
now greater
than y
if-else Statement
The Java if-else statement also tests the condition. It executes the if
block if condition is true else if it is false the else block
is executed.
Syntax:.
If(condition)
{
else
}
//Executes this block if
//condition is true
//Executes this block if
//condition is false
39
Example:
public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0){
System.out.println("even number");
}else
{
System.out.println("odd number");
} }}
Output:
odd number
Nested if Statement
Nested if-else statements, is that using one if or else if statement
inside another if or else if statement(s).
40
Example:
// Java program to illustrate
nested-if statement class
NestedIfDemo
{
public static void main(String args[])
{ int I
=
10;
if (I == 10)
{ if (I
<
15)
System.out.println(“I is smaller
than 15”); if (I < 12)
41
if-else-if ladder statement
The if statements are executed from the top down. The conditions
controlling the if is true, the statement associated with that if
is executed, and the rest of the ladder is bypassed. If none
of the conditions is true, then the final else statement will be
executed.
Syntax: if(condition)
statement; else
if(condition)
statement; else
if(condition)
statement;
.
.
else statement;
Example:
public class IfElseIfExample
{ public static void
main(String[] args)
{
int marks=65;
if(marks<50){
System.out.println(“fail”);
}
else if(marks>=50 && marks<60){
System.out.println(“D grade”);
}
42
else if(marks>=60 &&marks<70){
System.out.println(“C grade”);
}
else if(marks>=70 && marks<80){
System.out.println(“B grade”);
}
else if(marks>=80 && marks<90){
System.out.println(“A grade”);
}else if(marks>=90 && marks<100){
System.out.println(“A+ grade”);
}else{
System.out.println(“Invalid!”);
}
}
}
Output:
C grade
Switch Statements
The switch statement is Java’s multiway branch statement. It provides
an easy way to dispatch execution to different parts of your
code based on the value of an expression.
Syntax: switch
(expression) {
case value1:
// statement sequence
break; case value2:
// statement sequence break;
.
. case
valueN:
// statement sequence
break; default:
// defaultstatement sequence
}
Example:
// A simple example of
the switch. class
SampleSwitch {
public static void main(String args[]) {
43
for(int i=0;
i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case
1:
System.out.println("i is
one."); break; case 2:
System.out.println("i is
two."); break; case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater
than 3."); }}}
Output: i is zero. i
is one. i is
two. i is three. i
is greater than 3.
i is greater
than 3.
44
ITERATIVE STATEMENTS
In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true. There are
three types of loops in java.
• while loop
• do-while loop
• For loop while loop
A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while
loop can be thought of as a repeating if statement.
Syntax:
while(condition)
{
// body of loop
}
45
While loop starts with the checking of condition. If it evaluated
to true, then the loop body statements are executed otherwise first
statement following the loop is executed. It is called as Entry
controlled loop.
Normally the statements contain an updatevalue for the variable being
processed for the next iteration.
When the condition becomes false, the loop terminates which marks the
end of its life cycle. Example:
// Demonstrate the while
loop. class While {
public static void main(String
args[]) { int n =
5;
while(n > 0)
{
System.out.println("tick "
+ n); n--;
}
}
}
Output:
tick 5
tick
4
tick
3
tick
2
tick
1
46
do-while loop:
do while loop checks for condition after executing the statements, and
therefore it is called as Exit Controlled Loop.
Syntax:
do {
// body of loop
} while (condition);
47
Output:
1
2
3
4
5
48
Loop termination:When the condition becomes false, the loop terminates
marking the end of its life cycle.
Example
public class ForExample {
public static void main(String[] args)
{ for(int i=1;i<=5;i++)
{
System.out.println(i);
}
} }
Output:
1
2
3
4
5
for-each Loop
Example:
// Use a for-each
style for loop.
class ForEach
{
public static void main(String
args[]) { int nums[] =
{ 1, 2, 3, 4,
5, 6, 7, 8, 9,
10 }; int sum =
0;
// use for-each style for to display
and sum the values for(int x : nums)
49
System.out.println("Valueis: "
+ x); sum +=
x;
}
System.out.println("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is:
6
Value is:
7
Value is:
8
Value is: 9
Value is: 10
Summation: 55
Nested Loops
Java allows loops to be nested. That is, one loop may be inside
another.
Example:
// Loops may be
nested. class
Nested {
public static void main(String args[])
{
i
nt i,
j;
Output:
50
..........
.........
........
.......
......
.....
....
...
..
.
JUMP STATEMENTS
Java Break Statement
When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the
next statement following the loop.
The Java break is used to break loop or switch statement. It
breaks the current flow of the program at specified condition.
In case of inner loop, it breaks only inner loop.
Example:
// Using break to exit
a loop. class
BreakLoop {
public static void main(String args[])
{
for(int i=0; i<100; i++)
{ if(i
==
10)
51
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i:
i:
i:
i:
i:
i:
i:
i:
i:
i:
52
9
Loop complete.
Java Continue Statement
The continue statement is used in loop control structure when you
need to immediately jump to the next iteration of the loop. It
can be used with for loop or while loop.
The Java continue statement is used to continue loop. It continues
the current flow of the program and skips the remaining code
at specified condition. In case of inner loop, it continues only
inner loop.
Example:
// Demonstrate continue.
class Continue {
System.out.print(i +
" "); if
(i%2 == 0)
continue;
System.out.println(
"");
}
}
}
This code uses the % operator to check if i is
even. If it is, the loop continues without printing
a newline.
Output:
Return
The last control statement is return.The return statement is used to
explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
53
Example:
// Demonstrate return.
class Return{
public static void main(String args[])
{ boolean t = true;
System.out.println("Before the
return."); if(t) return;
// return to caller
System.out.println("This won't execute.");
}
}
Output:
Before the return.
54
So it saves memory. void is the return type of the method,
it means it doesn't return any value.
main represents the starting point of the program. String[] args
is used for command line argument. System.out.println() is used
print statement.
55
The data, or variables, defined within a class are called instance
variables. The code is contained within methods. The methods and
variables defined within a class are called members of the class.
In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.
Variables defined within a class are called instance variables because
each instance of the class (that is, each object of the class)
contains its own copy of these variables. Thus, the data for one
object is separate and uniquefrom the data for another.
A Simple
Class class
called Box
that defines
three instance
variables:
width, height,
and depth.
class Box {
double width;
double height;
double depth;
}
The new data type is called Box. This name is used to declare
objects of type Box. The class declaration only creates a
template. It does not create an actual object.
*/
clas
s Box
56
{
double width; double height;double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[])
{ Box mybox = new
Box(); double vol;
// assign values to mybox's
instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15; //
compute volume of box
Example2:
// This program declares two
Box objects. class Box {
double width; double height;double depth;
}
class BoxDemo2 {
public static void main(String args[])
{ Box mybox1
= new Box();
Box mybox2
= new Box();
double vol;
// assign values to mybox1's
instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables
*/
mybox2.width =
3; mybox2.height
57
= 6;
mybox2.depth
= 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is "
+ vol); // compute
volume of second
box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
Declaring Objects
First, declare a variable of the class type. This variable does not
define an object.Instead, it is simply a variable that can refer to
an object.
Second, you must acquire an actual, physical copy of the object and
assign it to that variable. This is done using the new operator.
The new operator dynamically allocates (that is, allocates at run
time) memory for an object and returns a reference to it.
This reference is then stored in the variable. Thus, in Java, all
class objects must be dynamically allocated.
Syntax:
Box mybox = new Box();
Box mybox; // declare
reference to object mybox =
new Box(); // allocate a
Box object
58
Assigning Object Reference
Variables Syntax:
Box b1 = new
Box(); Box b2
= b1;
b2 is being assigned a reference to a copy of the object referred
to by b1. b1 and b2 will both refer to the
same object. The assignment of b1 to b2 did not allocate any
memory or copy any part of the original object. It simply makes b2
refer to the same object as does b1. Thus, any changes made to the
object through b2 will affect the object to which b1 is referring,
since they are the same object.
3.2 CONSTRUCTORS
Constructors are special member functions whose task is to initialize
the objects of its class.
It is a special member function; it has the same as
the class name.
Java constructors are invoked when their objects are created. It
is named such because, it constructs the value, that is
provides data for the object and are used to initialize
objects.
59
Every class has a constructor when we don't explicitly declare a
constructor for any java class the compiler creates a
defaultconstructor for that class which does not have any return
type.
The constructor in Java cannot be abstract, static, final or
synchronized and these modifiers are not allowed for the
constructor.
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
}
// compute and return
volume double
volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String
args[]) { // declare,
allocate, and initialize Box
objects
Box mybox1 = new Box();
Box mybox2 = new
Box(); double vol;
// get volume of first box vol = mybox1.volume();
60
System.out.println("Volume is " + vol);
// get volume of second box vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Constructing Box
Constructing Box
Volume is
1000.0Volume
is 1000.0
new Box( ) is calling the Box( ) constructor. When the constructor for
a class is not explicitly defined , then Java creates a
defaultconstructor for the class. The defaultconstructor automatically initializes
all instance variables to their defaultvalues, which are zero, null, and
false, for numeric types, reference types, and boolean, respectively.
Parameterized Constructors
A constructor which has a specific number of parameters is
called parameterized constructor. Parameterized constructor is
used to provide different values to the distinct objects.
Example:
/* Here, Box uses a
parameterized constructor to
initialize the dimensions of
a box. */ class Box {
double width; double height;double
depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{ width =
w; height
= h;
depth = d;
}
// compute and return
volume double volume()
{
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
61
// declare, allocate, and
initialize Box objects Box
mybox1 = new Box(10,
20, 15);
Box mybox2 = new
Box(3, 6, 9); double vol;
// get volume of
first box vol =
mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of
second box
vol =
mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
Box mybox1 = new Box(10, 20, 15);
The values 10, 20, and 15 are passed to the Box( ) constructor when
new creates the object. Thus, mybox1’s copy of width, height, and
depth will contain the values 10, 20, and 15 respectively.
Overloading
Constructors Example:
/* Here, Box defines three constructors to initialize the dimensions of
a box various ways.
*/ class
Box {
double
width;
double
height;
double
depth;
// constructor used when all
dimensions specified Box(double w,
double h, double d) { width =
w; height = h; depth = d;
62
// constructor used when no dimensions
specified Box() {
width = -1; // use
-1 to indicate
height = -1; // an
uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height =
depth = len;
}
// compute and return
volume double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 =
new Box(); Box
mycube =
new Box(7);
double vol; //
get volume
of first box
vol =
mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of
second box
vol =
mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume
of cube vol
=
mycube.volume();
63
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
3.3 METHODS
Syntax:
type name(parameter-list) {
// body of method
}
type specifies the type of data returned by the method. This
can be any valid type, including class types that you create.
If the method does not return a value, its return type must be
void.
The name of the method is specified by name.
The parameter-list is a sequence of type and identifier pairs
separated by commas. Parameters are essentially variables that
receive the value of the arguments passed to the method
when it is called. If the method has no parameters, then
the parameter list will be empty.
Methods that have a return type other than void return a value to
the calling routine using the following form of the return
statement:
Syntax:
return value;
Example:
// This program includes a
method inside the box class.
class Box { double width; double
height;double depth;
// display volume
of a box void
volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo3 {
public static void main(String args[])
{ Box mybox1 = new Box();
Box mybox2 = new Box();
64
// assign values to mybox1's
instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to
mybox2's instance
variables */
mybox2.width =
3; mybox2.height
= 6;
mybox2.depth
= 9;
// display volume of first
box mybox1.volume();
// display volume of second
box mybox2.volume();
}
}
Output:
Volume is
3000.0Volume
is 162.0
The first line here invokes the volume( ) method on mybox1.
That is, it calls volume( ) relative to the mybox1
object, using the object’s name followed by the dot operator. Thus,
the call to mybox1.volume( ) displays the volume of the
box defined by mybox1, and the call to mybox2.volume( )
displays the volume of the box defined by mybox2. Each
time volume( ) is invoked, it displays the volume for
the specified box.
Returning a
Value Example:
// Now, volume() returns the volume of a box.
class Box {
double
width;
double
height;
double
depth;
// compute and return
volume double volume()
{
65
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[])
{ Box mybox1
= new Box();
Box mybox2
= new Box();
double vol;
// assign values to mybox1's
instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2'sinstance
variables */ mybox2.width =
3; mybox2.height = 6;
mybox2.depth = 9;
// get volume of
first box vol =
mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of
second box vol
= mybox2.volume();
Syntax: vol =
mybox1.volume();
executes, the
value of
mybox1.volume(
) is
3,000 and this
value then is
66
stored in vol.
depth = d;
}
}
class BoxDemo5 {
public static void main(String args[])
{ Box mybox1
= new Box();
Box mybox2
= new Box();
double vol;
// initialize each
box
mybox1.setDim(10,
20, 15);
mybox2.setDim(3, 6,
9); // get
volume of
67
first box vol =
mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of
second box
vol =
mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000
Volume is 162
{ int
id
;
String name;
student(int id, String name)
{ this.id =
id;
this.name
= name;
}
void display()
{
System.out.println(id+" "+name);
68
}
public static void main(String args[])
{
Student stud1 = new
Student(01,"Tarun"); Student
stud2 = new
Student(02,"Barun");
stud1.display(); stud2.display();
}
}
Output:
01 Tarun
02 Barun
Overloading Methods
When two or more methods within the same class that have the same
name, but their parameter declarations are different. The methods are
said to be overloaded, and the process is referred to as
method overloading. Method overloading is one of the ways that
Java supports polymorphism.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type Example:
// Demonstrate method
overloading. class
OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer
parameters. void test(int a,
int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double
parameter double test(double a)
{
System.out.println("double a: "
+ a); return a*a;
}
69
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new
OverloadDemo();double
result; // call all
versions of
test() ob.test();
ob.test(10); ob.test(10,
20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Output: No
parameters
a: 10
a and
b: 10
20
double a:
123.25
Result of ob.test(123.25): 15190.5625
Method Overriding
}
// display k – this
overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[])
{ B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output:
k: 3
When show( ) is invoked on an object of type B, the
version of show( ) defined within B is used. That is, the
version of show( ) inside B overrides the version declared
in A. If you wish to access the superclass version of an
overridden method, you can do so by using super. For example,
in this version of B, the superclass version of show( )
is invoked within the subclass’ version. This allows all instance
variables to be displayed.
class B
extends A
71
{ int k;
B(int a,
int b,
int c) {
super(a,
b); k
= c;
If you substitute this version of A into the previous
program, you will see the following Output:
i and
j:
1
2
k:
3
Here, super.show( ) calls the superclass version of show( ).
If you make any class constructor private, you cannot create the instance
of that class from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
73
//save by
A.java
package
pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by
B.java
package
mypack;
import
pack.*; class
B{
public static void main(String
args[]){ A obj =
new A();//Compile Time
Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method
msg() is defaultso it cannot be accessed from outside the
package.
74
pack;
public
class A{
class B extends A{
public static void main(String
args[]){
B obj = new
B(); obj.msg();
}
}
Output:
Hello
By Subclass
Only
Private Y N N N
Default Y Y N N
Protecte Y Y Y N
d
Public Y Y Y Y
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The defaultmodifier is more restrictive than protected. That is why there
is compile time error.
76
If you need to do computation in order to initialize your static
variables, you can declare a static block that gets executed
exactly once, when the class is first loaded.
Example:
// Java program to demonstrate use of
static blocks class Test
{
// static variable
static int a
= 10;
static int b;
// static
block
static {
System.out.println("Static block
initialized."); b = a *
4;
}
}
}
Output:
Static block
initialized. from main
Value of a : 10
Value of b : 40
Static variables
When a variable is declared as static, then a single copy of
variable is created and shared among all objects at class level.
Static variables are, essentially, global variables. All instances of the
class share the same static variable.
Important points for static variables :-
• We can create static variables at class-level only.
77
• static block and static variables are executed in order they are
present in a program.
Example:
// Demonstrate static variables, methods,
and blocks. class UseStatic { static
int a = 3; static int b;
static void meth(int x) {
System.out.println("x = "
+ x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
st
atic {
Static methods
When a method is declared with static keyword, it is
known as static method. When a member is declared static,
it can be accessed before any objects of its class are
created, and without reference to any object. The most
common example of a static method is main( )
method.
Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
Syntax:
78
classname.method( )
Example:
//Inside main( ), the static method callme( ) and the static
variable b are accessed through their class name
//StaticDemo.
class
StaticDemo {
b = 99
Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's
declare and
print variable
in java. */
int i=10;
System.out.println(
i);
}
}
Output:
10
80
Example:
/** The Calculator class provides methods to get addition and
subtraction of given 2 numbers.*/
81
OOP Unit-1 - CBS - Lambda Expressions
Lambda expression is a new and important feature of Java which was included in Java SE 8.
It provides a clear and concise way to represent one method interface using an expression.
It is very useful in the collection library. It helps to iterate, filter and extract data from
collections.
The Lambda expression is used to provide the implementation of an interface which has a
functional interface. It saves a lot of code. In case of lambda expression, we don't need to
define the method again for providing the implementation. Here, we just write the
implementation code.
Java lambda expression is treated as a function, so compiler does not create .class file
No Parameter Syntax
1. () -> {
2. //Body of no parameter lambda
3. }
1. (p1,p2) -> {
2. //Body of multiple parameter lambda
3. }
Example
1. interface Addable{
2. int add(int a,int b);
3. }
4.
5. public class LambdaExpressionExample5{
6. public static void main(String[] args) {
7.
8. // Multiple parameters in lambda expression
9. Addable ad1=(a,b)->(a+b); 10.
System.out.println(ad1.add(10,20)); 11.
12. // Multiple parameters with data type in lambda expression
13. Addable ad2=(int a,int b)->(a+b);
14. System.out.println(ad2.add(100,200));
15. }
16. }
Assignment -1
Category - Easy
Install Microsoft Visual Studio.net in your laptop/desktop.Execute any ten basic C#
programs.Share the programs & screenshots through your respective github link.
Category - Medium
Write a Java Program to sort three numbers.Repeat the same program using 10 different
logics.
Category - Hard
Part A
Sl.n Questions Blooms
o CO Level*
if(num1==num2){
System.out.println("num1 == num2");
} else{
System.out.println("num1 != num2");
}
if(num3 == num4){
System.out.println("num3 == num4");
}
else{
System.out.println("num3 != num4");
}
}
}
17 Guess the output public class Demo{ CO1 B3
public static void main(String[] arr){
}
public static void main(String arr){
}
}
18 Write a Java program to find the minimum element in a CO1 B3
given array.
19 Write a Java program to perform the transpose of any 3 X 3 CO1 B3
matrix.
20 Mention the purpose of the javadoc tool. CO1 B1
Part B
7 Write a Java program to implement a user defined CO1 B3
package.
Part C
Sl.no Questions CO Blooms
Level*
1 Identify the problem in the code CO1 B4
{ System.out.println("how to do");
return;
System.out.println("in java");
System.out.println("in java");
{ System.out.println("how to do");
System.out.println("in java");
1. Write a Java program to print 'Hello' on screen and then print your name on a separate line.
Expected Output :
Hello
Alexandra Abramov
3. Write a Java program to divide two numbers and print on the screen. Test Data :
50/3
Expected Output :
16
5. Write a Java program that takes two numbers as input and display the product of two
numbers.
Test Data:
Input first number: 25
Input second number: 5
Expected Output :
25 x 5 = 125
6. Write a Java program to print the sum (addition), multiply, subtract, divide and remainder of
two numbers.
Test Data:
Input first number: 125
Input second number: 24
Expected Output :
125 + 24 = 149
125 - 24 = 101
125 x 24 = 3000
125 / 24 = 5
125 mod 24 = 5
7. Write a Java program that takes a number as input and prints its multiplication table upto 10.
Test Data:
Input a number: 8
Expected Output :
8x1=8
8 x 2 = 16
8 x 3 = 24
...
8 x 10 = 80
9. Write a Java program to compute the specified expressions and print the output.
Test Data:
((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5))
Expected Output
2.138888888888889
11. Write a Java program to print the area and perimeter of a circle.
Test Data:
Radius = 7.5
Expected Output
Perimeter is = 47.12388980384689
Area is = 176.71458676442586
12. Write a Java program that takes three numbers as input to calculate and print the average
of the numbers.
13. Write a Java program to print the area and perimeter of a rectangle.
Test Data:
Width = 5.5 Height = 8.5
Expected Output
Area is 5.6 * 8.5 = 47.60
Perimeter is 2 * (5.6 + 8.5) = 28.20
31. Write a Java program to check whether Java is installed on your computer.
Expected Output
Java Version: 1.8.0_71
Java Runtime Version: 1.8.0_71-b15
Java Home: /opt/jdk/jdk1.8.0_71/jre
Java Vendor: Oracle Corporation Java
Vendor URL: http://Java.oracle.com/
Java Class Path: .
33. Write a Java program and compute the sum of the digits of an integer.
Input Data:
Input an integer: 25
Expected Output
The sum of the digits is: 7
34. Write a Java program to compute the area of a hexagon. Area of a hexagon
= (6 * s^2)/(4*tan(π/6)) where s is the length of a side Input Data:
Input the length of a side of the hexagon: 6
Expected Output
The area of the hexagon is: 93.53074360871938
35. Write a Java program to compute the area of a polygon. Area of a polygon =
(n*s^2)/(4*tan(π/n))
where n is n-sided polygon and s is the length of a side
Input Data:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Expected Output
The area is: 130.82084798405722
36. Write a Java program to compute the distance between two points on the
surface of earth. Distance between the two points [ (x1,y1) & (x2,y2)]
d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2))
Radius of the earth r = 6371.01 Kilometers Input Data:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 35.5
Input the longitude of coordinate 2: 25.5
Expected Output
The distance between those points is: 1480.0848451069087 km