UNIT 1 - OOP - Notes
UNIT 1 - OOP - Notes
Venkatasubramanian srinivasan
Object Oriented
PrOgramming in java
(cS3391)
SCE/CSBS
Contents
Introduction............................................................................................................................................. 2
programming paradigms .......................................................................................................................... 2
Building blocks of Object Oriented programming .................................................................................... 3
The OOP Principles ................................................................................................................................. 4
Abstraction..................................................................................................................................... 4
Encapsulation................................................................................................................................. 6
Inheritance ..................................................................................................................................... 8
Polymorphism ................................................................................................................................ 9
PROCEDURAL LANGUAGE VS OOP ............................................................................................ 10
Java Buzzwords or Features of Java .................................................................................................. 11
Overview of Java ................................................................................................................................. 12
Execution Process of Java Program.................................................................................................... 12
Java Variables ..................................................................................................................................... 15
Data Types in Java .............................................................................................................................. 16
Literals ................................................................................................................................................. 17
Operator In Java ................................................................................................................................. 19
Type Conversion in Java ..................................................................................................................... 23
Structure of a java Program ................................................................................................................... 25
Conditional statements (Control Structures) in Java : .......................................................................... 26
Java if...else Statement .................................................................................................................... 26
Java switch Statement ..................................................................................................................... 30
Java for Loop ................................................................................................................................... 31
Java for-each Loop ......................................................................................................................... 34
while loop ......................................................................................................................................... 35
do...while loop .................................................................................................................................. 37
break Statement............................................................................................................................... 40
continue Statement .......................................................................................................................... 42
Java Arrays ........................................................................................................................................... 45
Single Dimensional Array ............................................................................................................... 46
Multidimensional Array in Java ..................................................................................................... 49
Jagged Array in Java....................................................................................................................... 50
Copying a Java Array ...................................................................................................................... 51
1
SCE/CSBS
Introduction
Java is a high-level, third generation programming language, like C, FORTRAN, Smalltalk, Perl,
and many others. You can use Java to write computer applications that play games, store data or
do any of the thousands of other things computer software can do. Java language is called as an
Object-Oriented Programming language and before begining for Java, we have to learn the
concept of OOP(Object-Oriented Programming).
programming paradigms
2
SCE/CSBS
The term programming paradigm refers to a style of programming. It does not refer to a specific
language, but rather it refers to the way you program.
1.Classes
A class is defined as the blueprint for an object. It serves as a plan or a template. The description
of a number of similar objects is also called a class. An object is not created by just defining a
class. It has to be created explicitly. Classes are logical in nature. For example, furniture does
not have any existence but tables and chairs do exist. A class is also defined as a new data type,
a user-defined type that contains two things: data members and methods.
2. Objects
Objects are defined as the instances of a class, e.g. table, chair are all instances of the class
Furniture. Objects of a class will have same attributes and behavior which are defined in that
class. The only difference between objects would be the value of attributes, which may vary.
Objects (in real life as well as programming) can be physical, conceptual, or software. Objects
have a unique identity, state, and behavior. There may be several types of objects:
Creator objects: Humans, Employees, Students, animals
Physical objects: Car, Bus, Plane
Objects in the computer system: Monitor, Keyboard, Mouse, CPU, Memory
3
SCE/CSBS
Object-Oriented Principles mainly include the 4 pillars that together make the OOP a very
powerful concept. That is –
OOP is based on real-life engineered things. Like the approaches followed in the other
engineering – Electronic Engineers are making some device, Automobile engineers are making
some vehicle, etc. So the design approaches followed their, the same replicated to the software
engineering with the concept of these 4 Object-Oriented Programming principles.
If we analyze the programming concept then we will find that there are two elements of
programming –
1. Data
2. Operations on Data [functions]
So If we develop software then that software is meant for performing tasks on data only. And if
any function is performed on data, then there might be chances that in the future also the same
operation can be performed either in the same way or in some modified way. So that is very
smoothly done using the concept of OOP principles. Let’s see the principles:
Abstraction
4
SCE/CSBS
Abstraction can be defined as hiding internal implementation and showing only the required
features or set of services that are offered. This is the most essential part of Object-Oriented
programming.
Example 1 – We all have been using ATMs. And if we want to withdraw the money from that
then we simply interact with the Use Interface Screen where we have been asking for details.
As a user, we only want that I can use that ATM for the services. We are not interested in
knowing the internal implementation that what is the process happening inside the ATM
Machine like getting card details, validation, etc kind of things. We only have been provided an
interface to interact with that and simply ask for the work. And the internal implementation we
don’t need to know. So that is the Abstraction.
Explanation-
The above image shows the GUI screen of the ATM. In this when we want to withdraw then we
simply use that. For the implementation part, we don’t care.
Access Specifiers are the keywords that state, from where the (attributes and methods) of a class
can be accessed. For example – private can only be accessible within the class, the public can
be accessed from anywhere, etc.
Similarly, other programming languages follow their own implementation for achieving
abstraction.
class Television{
void changeChannel(){
//Implementation
}
void adjustVolume(){
//Implementation
}
void otherFeatues(){
5
SCE/CSBS
//Implementation
}
}
This pseudo-code example states that the television class is providing features like channel
change, adjust volume, etc. so as a user we only need to use that functions. We need not know
the internal implementation like how the function is working for changing channels, how the
codes manage to adjust the volume, etc. We have been provided the method to do that task, So
just utilize that.If we consider an example more specific to programming then we can say that the
functions included in the Math library like – pow(), min(), max(), etc are there, and we are only
using that to get our result. It’s not the case where we check its implementation. So it is also an
abstraction.
Features of Abstraction –
1. Security- With Abstraction, the Outside persons don’t know the internal implementation
so it makes the classes more secure, so the unauthorized user will not have access to the
data.
2. Easy Enhancement- Suppose in the future we want to change the logic of the
implementation in class, So we don’t have to change the entire external logic which is
there for the user. Just we need to make changes for the methods and it will not affect the
functionality.
3. Improves Easiness- It helps to use the features without knowing implementation so it
improves easiness for the users to use that.
4. Maintainability will improve- Without affecting the user, it can able to perform any
types of changes internally. SO maintainability will improve.
Encapsulation
Encapsulation can be defined as the binding of data and attributes or methods and data members
in a single unit. In classes, we have Data and attributes that perform operations on that data. So
according to the OOPs principle of Encapsulation, that data can be merged into a single unit.
Encapsulation enhances more security of the data as everything related to a single task must be
grouped and access to the data is given as per need.
Data Hiding – It means hiding the data of the class and restricting access to the outside
world. Example – Using the access specifier keywords like private that restricts the data to only
accessible and modifiable in the same class. Outside users can not access the data.
6
SCE/CSBS
Example 1- In the market, Capsules are available to cure different medical problems. Consider
capsule for fever. Now in that capsules, there are different compositions are grouped to make a
complete medicine that cures fever. So the grouping of that compositions into a single unit in the
capsule is a form of encapsulation. Here, consider fever as data, and the capsule as the operations
on the data. So everything is grouped here.
Explanation-
In the above image, all the dots represent the compositions for curing the fever (as per the
example). And these are grouped into a capsule. Similarly in programming, when there are
multiple operations related to a particular data are present, then grouping that into a simple unit
is Encapsulation.
Example 2- In a car, we have all the required things to make a car complete. Like engines, gear
shift, Wheels, etc, and these are grouped into a single body that makes a car. It is not like the
wheels are not attached to the car, Engines are misplaced and dragged outside, etc. Everything is
grouped into a single body. So in the OOP Principle also the same principle applies that
whatever operations are there for a particular group, must be capsuled to a single unit.
Explanation-
In the image we can see that the car has an engine, steering to control, gear shift, paddles to race
and stop the car are present, and these are grouped into a complete car.
So we want the same things in programming also, And that’s what OOP Principle makes it
possible. Similarly, if we take an example more specific to programming then we can state an
example of a LinkedList. We create a node that contains data and this node is related to the
LinkedList class. And Operation on that node like – Add, Delete, Search, etc are grouped into a
single class.
class LinkedList{
private class Node{
data;
next pointer;
}
public createNode(){}
public addNode(){}
public deleteNode(){}
.
.
}
This pseudo-code stated the encapsulation feature that every operation related to the LinkedList
is grouped as private and the operation to be public that is accessible to everyone.
Implementation of Encapsulation is language-specific. Like java uses the setter and getter
Method, C++ uses accessors and mutators, etc.
If any components follow Data Hiding and Abstraction, such type of component is said to be
encapsulated component.
7
SCE/CSBS
Features of Encapsulation –
Inheritance
Inheritance is the method of acquiring features of the existing class into the new class. Suppose
there is a class, considered as the parent class, that has some methods associated with it. And we
declare a new class, considered as the child class, that has its own methods. So, when a child
class is inherited from the parent class then it will have all the methods associated with parent
class are available in the child class along with the child class own methods also. So that is
Inheritance.
Example 1 – We all have seen the updates which receive on gadgets both in terms of hardware
and software. Like firstly mobile phones are their only to talk and then used for media access,
Internet, Camera, etc. So these are evolution that arrives by adding some extra feature and
making a new product without rebuilding the complete functionality so it is an example of
inheritance. Similarly, in software, regular updates are with some new features are also the
inheritance.
Explanation-
In the above image, we see that from old mobile new mobile is derived by adding new features
without affecting the old functionality, so it is an inheritance.
Note- This is just an example of what inheritance is. In OOPs it has some differences.
Now, In terms of Object-Oriented Programming Inheritance can be stated as –
There are two keywords involved in the inheritance – Base and Derived Class.
Base Class – It is also termed the parent class. It is the main class that has the basic properties
and methods which is defined.
Derived Class – This is the extension of the base class and it is also called the child class. It has
the properties and methods that are in the base class with its own features in it.
Inheritance has multiple types that depend on programming languages implementation. Some of
the common types of inheritance are-
1. Single Inheritance – When there is only one derived class.
2. Multiple Inheritance – When child class is inheriting more than one base class.
3. Multilevel Inheritance – When there is a level of inheritance. From class A to class B to
class C.
4. Hierarchical Inheritance – When more than one derived class is inheriting one base
class.
feature1(){}
feature2(){}
}
class Derived extends Base{
feature3(){}
}
In the above snippet of code there is a base class that has some data and features. And now the
derived class is implementing the base class which has an additional feature. So overall derived
class have all the feature which are in the base class with its own feature. So this is inheritance.
Note- Different programming languages used their different keyword for inheritance. Like java
uses extends keyword, c++ uses : (colon to inherit), Python uses () Parenthesis, etc.
The biggest advantage of inheritance is code reusability. The methods which are already declared
in the base class need not be rewritten in the derived class, They can be directly used. It is
automatically available for use on the derived class.
Polymorphism
Polymorphism is the most essential concept of the Object-Oriented Programming principle. It
has meaning ‘poly’ – many, ‘morph’ – forms. So polymorphism means many forms.
In Object-Oriented Programming, any object or method has more than one name associated with
it. That is nothing but polymorphism.
For Objects – When any object can hold the reference of its parent object then it is a
polymorphism. To understand this concept more clear, let’s consider an example-
Example – We have Television from different companies, Let’s say Samsung TV, LG TV,
Xiaomi TV, etc. Now if we have to call it then mostly we don’t call it with its brand name. We
simply call it a Television, And it can be of a different brand. But in general, we call it television.
So this can be said to be polymorphism.
9
SCE/CSBS
Explanation-
In the above image we have given these different brands of Television a common name which
we call Television. Here the term Polymorphism is followed.
It can also be stated as the Generalization because we have given a general name that can apply
to all the subclasses it has been derived from.
And yes, It can be achieved using inheritance. And the derived class object can also be called
with the name of the base class.
Example-
class Television{
public void TVOn(){}
public void TVOff(){}
}
class SamsungTV extends Television{
public void surfInternet(){}
}
Television TV = new SamsungTV(); //Yes, It is absolutely correct.
Explanation – In the above snippet the SamsungTV implemented Television class and
method TVOn() and TVOff() is available in SamsungTV class.
Now the object we have created of reference of Television class and created the object of the
SamsungTV class. Now, if we call TV.TVOn() then this works perfectly well. So it is the way to
achieve Polymorphism.
Because here it is polymorphism. And we can say that the SamsungTV is a Television. Because
the Television, as it has all the methods related to that. If we call Television.on() then the
SamsungTV will on as we have objected to that.
For Methods – Methods can also have multiple names associated with them. That we also
consider as the types of polymorphism.
10
SCE/CSBS
11
SCE/CSBS
Overview of Java
Java is a computer programming language. Java was created based on C and C++. Java uses C syntax and
many of the object-oriented features are taken from C++. Before Java was invented there were other
languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These languages had few disadvantages
which were corrected in Java. Java also innovated many new features to solve the fundamental problems
which the previous languages could not solve. Java was invented by a team of 13 employees of Sun
Microsystems, Inc. which is lead by James Gosling, in 1991. The team includes persons like Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as a part of the Green
project. Initially, it was called Oak, later it was changed to Java in 1995.
12
SCE/CSBS
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode. The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools that are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at runtime.
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment that 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:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
13
SCE/CSBS
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.. Each
packages contain a set of related classes and every class contains built-in methods, properties, data , etc.,
14
SCE/CSBS
If we want to use any built-in class then we have to import that package in the first lines of our java
program. An example of importing a package is import java.lang.*;
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. Java is a statically-typed language. This means that all variables must
be declared before they can be used.
Variable is a name of memory location. There are three types of variables in java:
EXAMPLE:
import java.io.*;
15
SCE/CSBS
class MyClass {
public static void main(String[] args)
{
// Declaring all the
// possible combinations of
// variable format
int _a = 10;
int $b = 20;
int C = 30;
int c = 40;
int result = _a + $b + C + c;
// Displaying O/P
System.out.println("Result: " + result);
}
}
16
SCE/CSBS
Literals
are data items with constant or fixed values. As a result, literals are also referred to as constants
in Java. Literals can be used to represent a variety of values, including numeric, character,
boolean, and String values. In Java, also we can assign literals to any of the eight primitive data
types.
Example: int i = 100; Here, 100 is a literal.
Types of Literals in Java:
Basically, there are five types of literal in Java :
1. Integer Literals
2. Floating-point Literals
3. Boolean Literals
4. Character Literals
5. String Literals
Integer Literals in Java:
17
SCE/CSBS
Integers are probably the most commonly used type in the typical program. Any whole number
value is an integer literal. The integer literal can be specified in four ways :
Decimal (Base-10): Digits from 0-9 are allowed in this form. Example: int x=101;
Octal (Base-8): Digits from 0 – 7 are allowed. It should always have a prefix 0. Example:
int x=0146;
Hexa-Decimal (Base-16): Digits 0-9 are allowed and also characters from a-f are allowed
in this form. Furthermore, both uppercase and lowercase characters can be used, Java
provides an exception here. Example: int x = 0X123Face;
Binary: A literal in this type should have a prefix 0b and 0B, from 1.7 one can also
specify in binary literals, i.e. 0 and 1. Example: int x = 0b1111;
Example of integer literals using a java code:
public class IntegerLiteral {
public static void main(String[] args) {
int a = 101; // decimal literal
int b = 0146; // octal literal
int c = 0x123Face; // Hexa-decimal literal
int d = 0b1111; // Binary literal
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
Note : By default, every literal is of int type, we can specify explicitly as long type by suffixed with l or L. There is no
way to specify byte and short literals explicitly but indirectly we can specify. Whenever we are assigning integral
literal to the byte variable and if the value is within the range of byte then the compiler treats it automatically as
byte literals.
Floating Literals :
All floating values for primitive type float and double comes under Floating Literals. Below are
some points that need to keep in mind while handling Floating Literals:
Floating points literals for float ends with the letter F or f. (32-bit float literal)
Floating points literals for double ends with the letter D or d(Optional) (64-bit
double literal; this is the default and by convention is omitted)
Floating points literals for float and double can also be expressed using E or e (for
scientific notation).
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double
and it can optionally end with the letter D or d.
Below are diffrent representation of decimal value 123.4:
Decimal : double d1 = 123.4;
18
SCE/CSBS
\b (backspace)
\t (tab)
\n (line feed)
\f (form feed)
\r (carriage return)
\” (double quote)
\’ (single quote)
\ (backslash).
Boolean Literals
A Boolean Literals is of type boolean which allow values as true or false.
For Example:
boolean isValidUser=false;
boolean isPetrolCar=true;
Null Literals
null literal is often used in programs as a marker to indicate that refrence type object is unavailable. null
may be assigned to any variable, except variables of primitive types.
For Example:
String employeeName=null;
Employee employee=null;
Operator In Java
In Java, operators are the keys through which we can perform some mathematical or logical operation for
some specific task.
19
SCE/CSBS
Operator precedence determines the order in which the operators in an expression are evaluated.
20
SCE/CSBS
21
SCE/CSBS
Assignment Operator
The assignment operator is represented by =. It is used for assigning a value to a variable as shown
below:
int a = 10;
Conditional Operator
Java provides a special ternary operator that can be used as an replacement for if-then-else selection
statement. The conditional operator is represented as ?:
The syntax for using the conditional operator is shown below:
expression 1 ? expression 2 : expression 3
Always expression 1 must evaluate to a boolean value. If the result of expression 1 is true,
then expression 2 is evaluated or else if expression 1 is false, expression 3 is evaluated and the resulting
value will be returned. Example : int a = 1, b = 1;
int result = (a==1 && b==1) ? 1 : 0;
22
SCE/CSBS
The above image shows the conversions that Java allows. For example, the compiler automatically
converts byte to short because the byte is smaller ( 8 bits ) or narrower than short ( 16 bits ).
byte ——— is convertible to ————-> short, int, long, float, or double
Short ——— is convertible to ————-> int, long, float, or double
char ——— is convertible to ————-> int, long, float, or double
int ——— is convertible to ————-> long, float, or double
long ——— is convertible to ————-> float or double
float ——— is convertible to ————-> double
An example of the above in java code is:
public class ImplicitTypeConversion
{
public static void main(String[] args)
{
int intVariable = 25;
long longVariable = intVariable;
float floatVariable = longVariable;
double doubleVariable = floatVariable;
23
SCE/CSBS
24
SCE/CSBS
The following table shows whether an assignment from a particular integer type to another integer type
can be directly done or it requires a typecast.
25
SCE/CSBS
26
SCE/CSBS
27
SCE/CSBS
Example of if…else…
class Main {
public static void main(String[] args) {
int number = 10;
28
SCE/CSBS
Example:
class Main {
public static void main(String[] args) {
int number = 0;
class Main {
public static void main(String[] args) {
29
SCE/CSBS
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
The expression is evaluated once and compared with the values of each case.
If expression matches with value1, the code of case value1 are executed. Similarly, the code of case
value2 is executed if expression matches with value2.
If there is no match, the code of the default case is executed.
Note: The working of the switch-case statement is similar to the Java if...else...if ladder. However, the
syntax of the switch statement is cleaner and much easier to read and write.
30
SCE/CSBS
class Main {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
The break statement is used to terminate the switch-case statement. If break is not used, all the cases after
the matching case are also executed.
Note: The Java switch statement only works with:
Primitive data types: byte, short, char, and int
Enumerated types
String Class
Wrapper Classes: Character, Byte, Short, and Integer.
31
SCE/CSBS
32
SCE/CSBS
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
}
}
}
Output
Java is fun
Java is fun
Java is fun
Java is fun
Java is fun
i=6
6th false The loop is terminated.
n=5
33
SCE/CSBS
In Java, the for-each loop is used to iterate through elements of arrays and collections (like
ArrayList). It is also known as the enhanced for loop.
for-each Loop Sytnax
The syntax of the Java for-each loop is:
for(dataType item : array) {
...
}
Here,
array - an array or a collection
item - each item of array/collection is assigned to this variable
dataType - the data type of the array/collection.
Example 1: Print Array Elements
// print array elements
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
Output
3
9
5
-5
Here, we have used the for-each loop to print each element of the numbers array one by one.
34
SCE/CSBS
while loop
Java while loop is used to run a specific code until a certain condition is met. The syntax of the
while loop is:
while (testExpression) {
// body of loop
}
Here,
A while loop evaluates the textExpression inside the parenthesis ().
If the textExpression evaluates to true, the code inside the while loop is executed.
The textExpression is evaluated again.
This process continues until the textExpression is false.
When the textExpression evaluates to false, the loop stops.
35
SCE/CSBS
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
Output
36
SCE/CSBS
i=1 1 is printed.
1st true
n=5 i is increased to 2.
i=2 2 is printed.
2nd true
n=5 i is increased to 3.
i=3 3 is printed.
3rd true
n=5 i is increased to 4.
i=4 4 is printed.
4th true
n=5 i is increased to 5.
i=5 5 is printed.
5th true
n=5 i is increased to 6.
do...while loop
The do...while loop is similar to while loop. However, the body of do...while loop is executed once before
the test expression is checked. For example,
do {
// body of loop
} while(textExpression);
Here,
The body of the loop is executed at first. Then the textExpression is evaluated.
If the textExpression evaluates to true, the body of the loop inside the do statement is executed again.
The textExpression is evaluated once again.
If the textExpression evaluates to true, the body of the loop inside the do statement is executed again.
This process continues until the textExpression evaluates to false. Then the loop stops.
Flowchart of do...while loop
37
SCE/CSBS
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
1
2
3
4
5
Here is how this program works.
38
SCE/CSBS
i=1 1 is printed.
not checked
n=5 i is increased to 2.
i=2 2 is printed.
1st true
n=5 i is increased to 3.
i=3 3 is printed.
2nd true
n=5 i is increased to 4.
i=4 4 is printed.
3rd true
n=5 i is increased to 5.
i=5 6 is printed.
4th true
n=5 i is increased to 6.
39
SCE/CSBS
break Statement
While working with loops, it is sometimes desirable to skip some statements inside the loop or
terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.
The break statement in Java terminates the loop immediately, and the control of the program
moves to the next statement following the loop.It is almost always used with decision-making statements
(Java if...else Statement).
// for loop
for (int i = 1; i <= 10; ++i) {
1
2
3
4
40
SCE/CSBS
In the case of nested loops, the break statement terminates the innermost loop.
However, there is another form of break statement in Java known as the labeled break. We can use the
labeled break statement to terminate the outermost loop as well.
41
SCE/CSBS
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
continue Statement
The continue statement skips the current iteration of a loop (for, while, do...while, etc).
After the continue statement, the program moves to the end of the loop. And, test expression is evaluated
(update statement is evaluated in case of the for loop).
// for loop
for (int i = 1; i <= 10; ++i) {
42
SCE/CSBS
1
2
3
4
9
10
Here, the continue statement is executed when the value of i becomes more than 4 and less than 9.
It then skips the print statement for those values. Hence, the output skips the values 5, 6, 7, and 8.
In the case of nested loops in Java, the continue statement skips the current iteration of the
innermost loop.
class Main {
public static void main(String[] args) {
int i = 1, j = 1;
// outer loop
while (i <= 3) {
43
SCE/CSBS
// inner loop
while(j <= 3) {
if(j == 2) {
j++;
continue;
}
Outer Loop: 1
Inner Loop: 1
Inner Loop: 3
Outer Loop: 2
Outer Loop: 3
Here, when the value of j is 2, the value of j is increased and the continue statement is executed.
This skips the iteration of the inner loop. Hence, the text Inner Loop: 2 is skipped from the output.
There is another form of continue statement in Java known as labeled continue. It includes the label of the
loop along with the continue keyword. For example,
continue label;
44
SCE/CSBS
class Main {
public static void main(String[] args) {
// inner loop
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)
Output:
i = 1; j = 1
i = 2; j = 1
i = 4; j = 1
i = 5; j = 1
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
45
SCE/CSBS
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the 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 which grows
automatically.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array
Syntax to Declare an Array in Java
Example of an aray
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
46
SCE/CSBS
Also,
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int arrayLength = number.length;
Here, we are using the length attribute of the array to calculate the size of the array.
Example : Linear Search - Search in an array if the given element (key) is present by comparing
each element of the array with the key
import java.util.*;
class LinearSearch{
47
SCE/CSBS
}
Example : binary search – Suppose we have a list that is sorted in ascending order.
To do a binary search, we first compare the target with the element in the middle of the list.
If the target equals the middle element, we’ve found the element and can just return that element’s index.
On the other hand, if the target is not equal to the middle element, we need to divide the list into two
halves (excluding the middle element).
If the target is greater than the middle element, we’ll search for it in the upper half in subsequent steps.
In contrast, if the target is smaller than the middle element, we’ll search for it in the lower half.
We keep dividing the list into smaller halves until we finally find the element that we want.
import java.util.*;
class BinarySearch{
48
SCE/CSBS
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
}
Array has length property which provides the length or capacity of the Array. It is the total space
allocated during the intialization of the array.
import java.util.ArrayList;
public class ArrayLength {
public static void main(String[] args) {
//creating array of 10 elements
int arr[]=new int[10];
//storing 2 elements
arr[0]=10;
arr[1]=12;
//printing length of array
System.out.println(arr.length); //10
}
}
49
SCE/CSBS
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
50
SCE/CSBS
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
51
SCE/CSBS
Output:
caffein
Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we
create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will
copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy
of the Java array which means it copies the references.
}}
Output:
52
SCE/CSBS
53
SCE/CSBS
54
SCE/CSBS
Java Package
A package is simply a container that groups related types (Java classes, interfaces, enumerations, and
annotations). Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:
Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
Providing controlled access: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member
(without any access specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding).
How did they manage to include two classes with the same name Date in JDK?
This was possible because these two Date classes belong to two different packages:
java.util.Date - this is a normal Date class that can be used anywhere.
java.sql.Date - this is a SQL Date used for the SQL query and such.
55
SCE/CSBS
Procedure:
1. To generate the output from the above program
Command>: javac Welcome.java
2. The Above Command Will Give Us Welcome.class File.
Command:> javac -d . Welcome.java
3. So This Command Will Create a New Folder Called FirstPackage.
Command:> java FirstPackage.Welcome
Output: The Above Will Give The Final Output Of The Example Program
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class , we cannot create
any Java program. A Java program may conation more than one class definition. We use
the class keyword to define the class. The class is a blueprint of a Java program. It contains information
about user-defined methods, variables, and constants. Every Java program has at least one class that
contains the main() method. For example:
class Student //class definition
{
}
56
SCE/CSBS
during the execution of the program. We can also decide and define the scope of variables by using the
modifiers. It defines the life of the variables. For example:
The main() is the starting point for JVM to start execution of a Java program. Without the main() method,
JVM will not execute the program. The syntax of the main() method is:
57
SCE/CSBS
Remember JVM always looks for the main() method with a string type array as a parameter.
First, JVM executes the static block, then it executes static methods, and then it creates the object needed
by the program. Finally, it executes the instance methods. JVM executes a static block on the highest
priority basis. It means JVM first goes to static block even before it looks for the main() method in the
program.
Example
class Demo
{
static //static block
{
System.out.println("Static block");
}
public static void main(String args[]) //static method
{
System.out.println("Static method");
}
}
Output:
Static block
Static method
Note: A program that does not have the main() method but having static block gives an error at run time.
Access Modifiers
In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables,
methods, constructors, data members, and the setter methods. For example,
class Animal {
public void method1() {...}
private void method2() {...}
}
In the above example, we have declared 2 methods: method1() and method2(). Here,
method1 is public - This means it can be accessed by other classes.
method2 is private - This means it can not be accessed by other classes.
Note the keyword public and private. These are access modifiers in Java. They are also known as
visibility modifiers.
58
SCE/CSBS
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Here, the MyClass class has the default access modifier. And the class is visible to all the classes that
belong to the defaultPackage package. However, if we try to use the MyClass class in another class
outside of defaultPackage, we will get a compilation error.
Private Access Modifier
When variables and methods are declared private, they cannot be accessed outside of the class. For
example,
59
SCE/CSBS
class Data {
// private variable
private String name;
}
In the above example, we have declared a private variable named name. When we run the program, we
will get the following error:
Main.java:18: error: name has private access in Data
d.name = "Saranathan";
^
The error is generated because we are trying to access the private variable of the Data class from
the Main class.
You might be wondering what if we need to access those private variables. In this case, we can use the
getters and setters method. For example,
class Data {
private String name;
// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();
60
SCE/CSBS
Output:
The name is Saranathan
In the above example, we have a private variable named name. In order to access the variable from the
outer class, we have used methods: getName() and setName(). These methods are called getter and setter
in Java.
Here, we have used the setter method (setName()) to assign value to the variable and the getter method
(getName()) to access the variable.
Protected Access Modifier
When methods and data members are declared protected, we can access them within the same package as
well as from subclasses. For example,
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
61
SCE/CSBS
// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
this Keyword
In Java, this keyword is used to refer to the current object inside a method or a constructor. For example,
62
SCE/CSBS
class Main {
int instVar;
Main(int instVar){
this.instVar = instVar;
System.out.println("this reference = " + this);
}
Java Methods
63
SCE/CSBS
// method body
}
Here,
returnType - It specifies what type of value a method returns For example if a method has
an int return type then it returns an integer value.
If the method does not return a value, its return type is void.
methodName - It is an identifier that is used to refer to the particular method in a program.
method body - It includes the programming statements that are used to perform some tasks. The
method body is enclosed inside the curly braces { }.
For example,
int addNumbers() {
// code
}
In the above example, the name of the method is adddNumbers(). And, the return type is int. We will
learn more about return types later in this tutorial.
This is the simple syntax of declaring a method. However, the complete syntax of declaring a method is
modifier static returnType nameOfMethod (parameter1, parameter2, ...) {
// method body
}
Here,
modifier - It defines access types whether the method is public, private, and so on.
static - If we use the static keyword, it can be accessed without creating objects.
For example, the sqrt() method of standard Math class is static. Hence, we can directly
call Math.sqrt() without creating an instance of Math class.
parameter1/parameter2 - These are values passed to a method. We can pass any number of
arguments to a method.
64
SCE/CSBS
// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}
65
SCE/CSBS
Here, we have called the method by passing two arguments num1 and num2. Since the method is
returning some value, we have stored the value in the result variable.
Note: The method is not static. Hence, we are calling the method using the object of the class.
// create a method
public static int square(int num) {
// return statement
return num * num;
}
Output:
Squared value of 10 is: 100
66
SCE/CSBS
In the above program, we have created a method named square(). The method takes a number as its
parameter and returns the square of the number.
Here, we have mentioned the return type of the method as int. Hence, the method should always return an
integer value.
Note: If the method does not return any value, we use the void keyword as the return type of the method.
For example,
public void square(int a) {
int square = a * a;
System.out.println("Square is: " + square);
}
67
SCE/CSBS
68
SCE/CSBS
// method defined
private static int getSquare(int x){
return x * x;
}
// method call
int result = getSquare(i);
System.out.println("Square of " + i + " is: " + result);
}
}
}
Output:
Square of 1 is: 1
Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square of 5 is: 25
In the above program, we have created the method named getSquare() to calculate the square of a
number. Here, the method is used to calculate the square of numbers less than 6.
Hence, the same method is used again and again.
2. Methods make code more readable and easier to debug. Here, the getSquare() method keeps the code
to compute the square in a block. Hence, makes it more readable.
Java Method Overloading
In Java, two or more methods may have the same name if they differ in parameters (different number of
parameters, different types of parameters, or both). These methods are called overloaded methods and this
feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
69
SCE/CSBS
Example: 2
class HelperService {
70
SCE/CSBS
Important Points
Two or more methods can have the same name inside the same class if they accept different
arguments. This feature is known as method overloading.
Method overloading is achieved by either:
o changing the number of arguments.
o or changing the data type of arguments.
It is not method overloading if we only change the return type of methods. There must be
differences in the number of parameters.
Java Constructor
A constructor in Java is similar to a method that is invoked when an object of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and does not have any return
type. For example,
class Test {
71
SCE/CSBS
Test() {
// constructor body
}
}
Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return type.
Constructor is not directly called by the user's code. It's called by the memory allocation and object
initialization code in the run time. Its value is not visible to the user.
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Saranathan";
}
Types of Constructor
72
SCE/CSBS
int i;
73
SCE/CSBS
Here, we are creating the object inside the same class. Hence, the program is able to access the
constructor.
However, if we want to create objects outside the class, then we need to declare the constructor as public.
Example 3: Java public no-arg constructors
class Company {
String name;
// public constructor
public Company() {
name = " Saranathan ";
}
}
class Main {
public static void main(String[] args) {
Output:
Company name = Saranathan
2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructor with parameters).
Example 4: Parameterized constructor
class Main {
String languages;
74
SCE/CSBS
int a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
Default Value:
75
SCE/CSBS
a=0
b = false
Here, we haven't created any constructors. Hence, the Java compiler automatically creates the default
constructor.
The default constructor initializes any uninitialized instance variables with default values.
Important Notes on Java Constructors
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
The name of the constructor should be the same as the class.
A Java constructor must not have a return type.
If a class doesn't have a constructor, the Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with default
values. For example, the int variable will be initialized to 0
Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java compiler if it is not
explicitly defined.
A constructor cannot be abstract or static or final.
A constructor can be overloaded but can not be overridden.
Constructors Overloading in Java
Similar to Java method overloading, we can also create two or more constructors with different
parameters. This is called constructors overloading.
String language;
76
SCE/CSBS
obj1.getName();
obj2.getName();
}
}
Output:
Programming Language: Java
Programming Language: Python
In the above example, we have two constructors: Main() and Main(String language). Here, both the
constructor initialize the value of the variable language with different values.
Based on the parameter passed during object creation, different constructors are called and different
values are assigned.
It is also possible to call one constructor from another constructor.
In Java, if we want to access class members, we must first create an instance of the class. But there will be
situations where we want to access class members without creating any variables.
In those situations, we can use the static keyword in Java. If we want to access class members without
creating an instance of the class, we need to declare the class members static.
A static member can be:
static variables,
static methods,
77
SCE/CSBS
Static Methods
Static methods are also called class methods. It is because a static method belongs to the class rather than
the object of a class.
And we can invoke static methods directly using the class name. For example,
class Test {
// static method inside the Test class
public static void method() {...}
}
class Main {
// invoking the static method
Test.method();
}
Here, we can see that the static method can be accessed directly from other classes using the class name.
In every Java program, we have declared the main method static. It is because to run the program the
JVM should be able to invoke the main method during the initial phase where no objects exist in the
memory.
Example 1: Java static and non-static Methods
class StaticTest {
// non-static method
int multiply(int a, int b){
return a * b;
}
// static method
static int add(int a, int b){
return a + b;
}
}
78
SCE/CSBS
class Main {
// create instances of Test
Test test1 = new Test();
Test test2 = new Test();
}
Here, both the objects test1 and test2 will have separate copies of the variable age. And, they are different
from each other.
However, if we declare a variable static, all objects of the class share the same static variable. It is
because like static methods, static variables are also associated with the class. And, we don't need to
create objects of the class to access the static variables. For example,
class Test {
// static variable
static int age;
79
SCE/CSBS
}
class Main {
// access the static variable
Test.age = 20;
}
Here, we can see that we are accessing the static variable from the other class using the class name.
Static Blocks
In Java, static blocks are used to initialize the static variables. For example,
class Test {
// static variable
static int age;
// static block
static {
age = 23;
}
}
Here we can see that we have used a static block with the syntax:
static {
// variable initialization
}
The static block is executed only once when the class is loaded in memory. The class is loaded if either
the object of the class is requested in code or the static members are requested in code.
A class can have multiple static blocks and each static block is executed in the same sequence in which
they have been written in a program.
Example : Use of static block in java
class Main {
// static variables
static int a = 23;
static int b;
static int max;
// static blocks
static {
System.out.println("First Static block.");
80
SCE/CSBS
b = a * 4;
}
static {
System.out.println("Second Static block.");
max = 30;
}
// static method
static void display() {
Java Comments
The Java comments are the statements in a program that are not executed by the compiler and interpreter.
Why do we use comments in a code?
o Comments are used to make the program more readable by adding the details of the code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative code.
Types of Java Comments
There are three types of comments in Java.
81
SCE/CSBS
3. Documentation Comment - Documentation comments are usually used to write large programs
for a project or software application as it helps to create documentation API. These APIs are
needed for reference, i.e., which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are
placed between /** and */.
javadoc tags
Some of the commonly used tags in documentation comments:
@code {@code text} To show the text in code font without interpreting it
as html markup or nested javadoc tag.
@since @since release To add "Since" heading with since text to generated
documentation.
@param @param parameter-name To add a parameter with given name and description
description to 'Parameters' section.
82
SCE/CSBS
@return @return description Required for every method that returns something
(except void)
import java.io.*;
/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
* <b>Note:</b> Comments make the code readable and
* easy to understand.
*
* @author veeyes
* @version 16.0
* @since 2022-07-06
*/
83
SCE/CSBS
* @see IOException
*/
public static void main(String[] args) {
Calculate obj = new Calculate();
int result = obj.sum(40, 20);
P
A
R
T
-
A
Q.No Questions Competence
1 Express what is meant by Object Oriented Programming. Understand
2 Compare class and object. Analyze
3 List the core OOP’s concepts. Remember
4 Tabulate the difference between C++ and Java. Remember
5 Discuss what is meant by abstraction. Understand
6 Describe about Encapsulation, Inheritance and Understand
Polymorphism.
7 Point out the justification of the statement “Java is platform Analyze
independent”.
8 Express a Java programming structure to display “Hello Understand
World”.
9 List the various access specifiers supported by OOPS. Remember
10 Illustrate constructors in Java. Apply
11 Create a simple Java Program to find the given number is Create
Prime or not.
12 Evaluate the characteristics of objects. Evaluate
84
SCE/CSBS
B
1 i.Explain OOPS and its features. Evaluate
ii.Summarize about the usage of constructor with an
example using Java.
2 i.What is class? How do you define a class in Java? Remembe
r
ii.Examine the use of inheritance and class hierarchy.
3 i.Define polymorphism.
ii.Describe variables and operators in Java.
4. Define and explain the control flow statements in Java with Remember
suitable examples
5 What is meant by constructor? Discuss the types of Understand
constructor with example.
6 i.Analyse and Develop a simple Java program to sort the Analyze
given numbers in increasing order.
ii.Write a Java program to reverse the given number.
7 i. Classify the characteristics of Java. Apply
ii.Illustrate the working principles of Java Virtual Machine.
iii.Show with an example the structure of Java Program
85
SCE/CSBS
86