0% found this document useful (0 votes)
10 views

UNIT 1 - OOP - Notes

This document provides an overview of object-oriented programming concepts in Java. It discusses the key building blocks of OOP like classes and objects. It also explains the four main OOP principles - abstraction, encapsulation, inheritance, and polymorphism. The document then contrasts procedural programming with OOP. It includes sections on Java keywords, data types, variables, arrays, operators, control statements, and other core Java programming structures like methods, constructors, and access specifiers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

UNIT 1 - OOP - Notes

This document provides an overview of object-oriented programming concepts in Java. It discusses the key building blocks of OOP like classes and objects. It also explains the four main OOP principles - abstraction, encapsulation, inheritance, and polymorphism. The document then contrasts procedural programming with OOP. It includes sections on Java keywords, data types, variables, arrays, operators, control statements, and other core Java programming structures like methods, constructors, and access specifiers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Object Oriented Programming in Java (CS3391) SCE

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

Cloning an Array in Java ................................................................................................................. 52


Basic structure of a Java program .......................................................................................................... 54
Java Package.................................................................................................................................... 55
Access Modifiers .................................................................................................................................. 58
Default Access Modifier .................................................................................................................... 59
Private Access Modifier..................................................................................................................... 59
Protected Access Modifier ................................................................................................................. 61
Public Access Modifier...................................................................................................................... 62
this Keyword........................................................................................................................................ 62
Java Methods ....................................................................................................................................... 63
Calling a Method in Java ................................................................................................................... 64
Java Method Overloading ............................................................................................................... 69
Java Constructor ................................................................................................................................ 71
1. Java No-Arg Constructors........................................................................................................... 73
2. Java Parameterized Constructor ................................................................................................ 74
3. Java Default Constructor ............................................................................................................ 75
Constructors Overloading in Java .................................................................................................. 76

UNIT I INTRODUCTION TO OOP AND JAVA


Overview of OOP – Object oriented programming paradigms – Features of Object Oriented Programming
– Java Buzzwords – Overview of Java – Data Types, Variables and Arrays – Operators – Control
Statements – Programming Structures in Java – Defining classes in Java – Constructors-Methods -Access
specifiers - Static members- JavaDoc comments

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.

An object-oriented program can be characterized as data controlling access to code.

Building blocks of Object Oriented programming

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

The OOP Principles

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.

Let’s understand with the help of an example –

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.

The same concept is applicable in the programming implementation of Abstraction. Although


different programming has a different syntax of implementation of Abstraction. But the most
popular programming languages like JAVA use a keyword called abstract which applies to the
class and methods to make a class abstract and achieve abstraction. And it can also be achieved
using the interfaces in java. C++ achieves it by grouping the attributes and using an access
specifier allowing what data is to be visible outside.

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.

And this can be achieved using the concept of Data Hiding.


Encapsulation = Data Hiding + Abstraction.

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.

Let’s understand with the help of an example-

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 –

1. It provides extra security by the concept of Data Hiding.


2. It groups the data and operation in that data into a single unit.
3. It attaches an extra security layer to the data and allows to access data only to authorized
ones.

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.

Programming Implementation of Inheritance-


class Base{
data;
8
SCE/CSBS

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.

Derived class = feature1 (from base class),


feature2 (from base class),
data (from base class), and
feature3 (it’s own).

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.

OOPs states 2 types of Polymorphism –

1. Compile Time Polymorphism. Also called Static binding.(using method overloading)


2. Runtime Polymorphism. Also called Dynamic binding.(using method overriding)

PROCEDURAL LANGUAGE VS OOP

10
SCE/CSBS

Java Buzzwords or Features of Java

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.

Execution Process of Java Program


The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file uisng java command.

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:

local, instance and static.

Rules to Declare a Variable


1. A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and two
special characters such as _ underscore and $ dollar sign.
2. The first character must not be a digit.
3. Blank spaces cannot be used in variable names.
4. Java keywords cannot be used as variable names.
5. Variable names are case-sensitive.
6. There is no limit on the length of a variable name but by convention, it should be between 4 to 15
chars.
7. Variable names always should exist on the left-hand side of assignment operators.
few valid Java variable name examples:
myvar
myVar
MYVAR
_myVar
$myVar
myVar1
myVar_1

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);
}
}

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
 Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
 Non-primitive data types: The non-primitive data types include Classes
, Interfaces
, and Arrays

16
SCE/CSBS

Table 1: List of Java's primitive data types

Type Size Range Default value

byte 1 byte -128 to 127 0

short 2 bytes -32,768 to 32,767 0

int 4 bytes -2,147,483,648 to 2,147,483, 647 0

long 8 bytes -9,223,372,036,854,775,808 to 0


9,223,372,036,854,775,807

float 4 bytes approximately ±3.40282347E+38F 0.0f


(6-7 significant decimal digits)
Java implements IEEE 754 standard

double 8 bytes approximately ±1.79769313486231570E+308 0.0d


(15 significant decimal digits)

char 2 byte 0 to 65,536 (unsigned) '\u0000'

boolean 1 bit true or false false

Unicode is a universal international standard character encoding that is capable of representing


most of the world's written languages. In unicode, a character holds 2 byte, so java also uses 2
byte for characters.
lowest value:\u0000 highest value:\uFFFF

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

Decimal Scientific Notation : double d2 = 1.234e2;


Floating : float f1 = 123.4f;
Character and String Literals
Literals of types char and String may contain any Unicode (UTF-16) characters. Always use
‘single quotes’ for char literals and “double quotes” for String literals.Java also support few
special escape sequences for char and String literals:

\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

Examples of the operator are given below:

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

Type Conversion in Java


Type Conversion or Type Casting is the process of converting a variable of one predefined type into
another.
If these data types are compatible with each other, the compiler automatically converts them and if they
are not compatible, then the programmer needs to typecast them explicitly.
Implicit Type Conversion
Implicit Type Conversion or Automatic type conversion is a process of automatic conversion of one data
type to another by the compiler, without involving the programmer.
This process is also called Widening Conversion because the compiler converts the value of narrower
(smaller size) data type into a value of a broader (larger size) data type without loss of information. The
implicit data type conversion is possible only when:
 The two data types are compatible with each other.
 There is a need to convert a smaller or narrower data type to the larger type size.

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

System.out.println("Integer value is: " +intVariable);


System.out.println("Long value is: " +longVariable);
System.out.println("Float value is: " +floatVariable);
System.out.println("Double value is: " +doubleVariable);
}
}
Output:
Integer value is: 25
Long value is: 25
Float value is: 25.0
Double value is: 25.0

Explicit Type Conversion


The Explicit Type Conversion is a process of explicitly converting a type to a specific type. We also call
it Narrowing Conversion. The typecasting is done manually by the programmer, and not by the
compiler.
We need to do explicit or narrowing type conversion when the value of a broader (higher size) data type
needs to be converted to a value of a narrower (lower size) data type. For example, double data type
explicitly converted into int type.

Syntax of explicit type conversion in Java: (type) expression;


Example:
public class Test
{
public static void main(String[] argv)
{
int intVariable = 10;
long longVariable = 7878;
longVariable=intvariable; // implicit conversion
intVariable = longVariable; // error
intVariable = (int) longVariable; // correct explicit conversion using casting
}
}
A value of any integer type can be cast to a value of any other integer type. However, Integer types can
not be cast to a boolean value, nor can the boolean type be cast to an integer type value.

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.

Structure of a java Program

Example of a simple java program structure

25
SCE/CSBS

Conditional statements (Control Structures) in Java :


Statements in java source code generally executed from top to bottom, in the order they appear. However,
with control-flow statements, that order can be interrupted to implement decision making, branching or
looping so that the Java program can run particular blocks of code based on certain conditions. Control
flow statements categorize as below:

Java if...else Statement


In programming, we use the if..else statement to run a block of code among more than one
alternatives.
For example, assigning grades (A, B, C) based on the percentage obtained by a student.
if the percentage is above 90, assign grade A
if the percentage is above 75, assign grade B
if the percentage is above 65, assign grade C
Java if (if-then) Statement
The syntax of an if-then statement is:
if (condition) {
// statements
}
Here, condition is a boolean expression such as age >= 18.
 if condition evaluates to true, statements are executed
 if condition evaluates to false, statements are skipped
Working of if Statement

26
SCE/CSBS

Working of Java if statement

Java if...else (if-then-else) Statement


The if statement executes a certain section of code if the test expression is evaluated to
true. However, if the test expression is evaluated to false, it does nothing.
In this case, we can use an optional else block. Statements inside the body of else block
are executed if the test expression is evaluated to false. This is known as the if-...else statement
in Java.
The syntax of the if...else statement is:
if (condition) {
// codes in if block
}
else {
// codes in else block
}
Here, the program will do one task (codes inside if block) if the condition is true and another task
(codes inside else block) if the condition is false.
How the if...else statement works?

Working of Java if-else statements

27
SCE/CSBS

Example of if…else…
class Main {
public static void main(String[] args) {
int number = 10;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}
// execute this block
// if number is not greater than 0
else {
System.out.println("The number is not positive.");
}

System.out.println("Statement outside if...else block");


}
}

Java if...else...if Statement


In Java, we have an if...else...if ladder, that can be used to execute one block of code among multiple
other blocks.
if (condition1) {
// codes
}
else if(condition2) {
// codes
}
else if (condition3) {
// codes
}
.
else {
// codes
}

Working of if...else...if ladder

28
SCE/CSBS

Example:
class Main {
public static void main(String[] args) {
int number = 0;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// checks if number is less than 0


else if (number < 0) {
System.out.println("The number is negative.");
}

// if both condition is false


else {
System.out.println("The number is 0.");
}
}
}
In the above example, we are checking whether number is positive, negative, or zero. Here, we have two
condition expressions:
number > 0 - checks if number is greater than 0
number < 0 - checks if number is less than 0
Here, the value of number is 0. So both the conditions evaluate to false. Hence the statement inside the
body of else is executed.
Java Nested if..else Statement
In Java, it is also possible to use if..else statements inside an if...else statement. It's called the nested
if...else statement.
Here's a program to find the largest of 3 numbers using the nested if...else statement.

class Main {
public static void main(String[] args) {

// declaring double type variables


Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largest;

// checks if n1 is greater than or equal to n2


if (n1 >= n2) { // if 1

// if...else statement inside the if block


// checks if n1 is greater than or equal to n3
if (n1 >= n3) { // if 2
largest = n1;

29
SCE/CSBS

else { // else for if 2


largest = n3;
}
} else { // else for f1

// if..else statement inside else block


// checks if n2 is greater than or equal to n3
if (n2 >= n3) { // if 3
largest = n2;
}
else { // else for if 3
largest = n3;
}
} // block of if 1 over

System.out.println("Largest Number: " + largest);


}
}

Java switch Statement


The switch statement allows us to execute a block of code among many alternatives.
The syntax of the switch statement in Java is:
switch (expression) {

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

// Java Program to check the size


// using the switch...case statement

class Main {
public static void main(String[] args) {

int number = 44;


String size;

// switch statement to check size


switch (number) {

case 29:
size = "Small";
break;

case 42:
size = "Medium";
break;

// match the value of week


case 44:
size = "Large";
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.

Java for Loop


In computer programming, loops are used to repeat a block of code. For example, if you want to show a
message 100 times, then rather than typing the same code 100 times, you can use a loop.

31
SCE/CSBS

In Java, there are three types of loops.


 for loop
 while loop
 do...while loop

Java for Loop


Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:

for (initialExpression; testExpression; updateExpression) {


// body of the loop
}
Here,
 The initialExpression initializes and/or declares variables and executes only once.
 The condition is evaluated. If the condition is true, the body of the for loop is executed.
 The updateExpression updates the value of initialExpression.
 The condition is evaluated again. The process continues until the condition is false.

32
SCE/CSBS

Example 1: Display a Text Five Times


// Program to print a text 5 times

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

Iteration Variable Condition: i <= n Action

i=1 Java is fun is printed.


1st true
n=5 i is increased to 2.

i=2 Java is fun is printed.


2nd true
n=5 i is increased to 3.

i=3 Java is fun is printed.


3rd true
n=5 i is increased to 4.

i=4 Java is fun is printed.


4th true
n=5 i is increased to 5.

i=5 Java is fun is printed.


5th true
n=5 i is increased to 6.

i=6
6th false The loop is terminated.
n=5

33
SCE/CSBS

Java for-each Loop

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

// for each loop


for (int number: numbers) {
System.out.println(number);
}
}
}

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

In the first iteration, item will be 3.


In the second iteration, item will be 9.
In the third iteration, item will be 5.
In the fourth iteration, item will be -5.

Example 2 Using for-each Loop


class Main {
public static void main(String[] args) {

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

// iterating through an array using the for-each loop


for (char item: vowels) {
System.out.println(item);
}
}
}
Output:
a
e
i
o
u

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

Example 1: Display Numbers from 1 to 5


// Program to display numbers from 1 to 5

class Main {
public static void main(String[] args) {

// declare variables
int i = 1, n = 5;

// while loop from 1 to 5


while(i <= n) {
System.out.println(i);
i++;
}
}
}

Output

36
SCE/CSBS

Here is how this program works.

Iteration Variable Condition: i <= n Action

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.

i=6 The loop is


6th false
n=5 terminated

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

Example : Display Numbers from 1 to 5

// Java Program to display numbers from 1 to 5

import java.util.Scanner;

// Program to find the sum of natural numbers from 1 to 100.

class Main {
public static void main(String[] args) {

int i = 1, n = 5;

// do...while loop from 1 to 5


do {
System.out.println(i);
i++;
} while(i <= n);
}
}
Output

1
2
3
4
5
Here is how this program works.

38
SCE/CSBS

Iteration Variable Condition: i <= n Action

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.

i=6 The loop is


5th false
n=5 terminated

Infinite while loop


If the condition of a loop is always true, the loop runs for infinite times (until the memory is full).
For example,

// infinite while loop


while(true){
// body of loop
}
Here is an example of an infinite do...while loop.

// infinite do...while loop


int count = 1;
do {
// body of loop
} while(count == 1)
In the above programs, the textExpression is always true. Hence, the loop body will run for
infinite times.

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

Example : break statement


class Test {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if the value of i is 5 the loop terminates


if (i == 5) {
break;
}
System.out.println(i);
}
}
}
Output:

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.

Example: labelled break


class LabeledBreak {
public static void main(String[] args) {

// the for loop is labeled as first


first:
for( int i = 1; i < 5; i++) {
// the for loop is labeled as second
second:
for(int j = 1; j < 3; j ++ ) {
System.out.println("i = " + i + "; j = " +j);

// the break statement breaks the first for loop


if ( i == 2)
break first;
}
}
}
}

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

Example 1: Java continue statement


class Main {
public static void main(String[] args) {

// for loop
for (int i = 1; i <= 10; ++i) {

// if value of i is between 4 and 9


// continue is executed

42
SCE/CSBS

if (i > 4 && i < 9) {


continue;
}
System.out.println(i);
}
}
}
Output:

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

System.out.println("Outer Loop: " + i);

43
SCE/CSBS

// inner loop
while(j <= 3) {

if(j == 2) {
j++;
continue;
}

System.out.println("Inner Loop: " + j);


j++;
}
i++;
}
}
}
Output

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

// outer loop is labeled as first


first:
for (int i = 1; i < 6; ++i) {

// inner loop
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)

// skips the current iteration of outer loop


continue first;
System.out.println("i = " + i + "; j = " + j);
}
}
}
}

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

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Example of an aray
class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);

46
SCE/CSBS

System.out.println("Fifth Element: " + age[4]);


}
}
Output

Accessing Elements of Array:


First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5

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{

public static void main(String[] ar)


{
int result=-1;
int arr[]={-1,4,2,7,5,9};
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int i;
for(i=0;i<=arr.length;i++)
{
if(arr[i]==x)
{
result=1;
break;
}
}
if(result==1)
System.out.println("element fount at : "+(i+1));
else

System.out.println("element not found");


}

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.

nums = [2, 3, 5, 7, 8, 10, 12, 15, 18, 20]


target = 7

import java.util.*;

class BinarySearch{

public static void main(String[] ar)


{
int result=-1;
int arr[]={-1,2,4,7,9,12};
Scanner sc=new Scanner(System.in);
int key=sc.nextInt();
int first=0;
int last=arr.length-1;
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){

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
}
}

Multidimensional Array in Java


Data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;

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;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is
an array of arrays with different number of columns.

//Java Program to illustrate the jagged array


class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array

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

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
012
3456
78

Copying a Java Array

We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method


public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length
)
Example of Copying an Array in Java
//Java Program to copy a source array into a destination array in Java
class TestArrayCopyDemo {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}

51
SCE/CSBS

Output:
caffein

Cloning an Array in Java

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.

//Java Program to clone the array


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);

System.out.println("Printing clone of the array:");


int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);

System.out.println("Are both equal?");


System.out.println(arr==carr);

}}
Output:

Printing original array:


33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false
Example of two dimensional array: Addition of 2 Matrices in Java
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){

52
SCE/CSBS

//creating two matrices


int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}

Multiplication of 2 Matrices in Java


In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns
of the second matrix which can be understood by the image given below.

Matrix Multiplication in Java


Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

//Java Program to multiply two matrices


public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

53
SCE/CSBS

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}

Basic structure of a Java program

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.

Accessing classes inside a package


Consider following two statements :
// import the Vector class from util package.
import java.util.vector;

// import all the classes from util package


import java.util.*;
 First Statement is used to import Vector class from util package which is contained inside java.
 Second statement imports all the classes from util package.

How to create our own package:

55
SCE/CSBS

// Name of package to be created


package FirstPackage;

// Class in which the above created package belong to


class Welcome {
// main driver method
public static void main(String[] args)
{
// Print statement for the successful
// compilation and execution of the program
System.out.println("This Is The First Program inside package..");
}
}

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
{
}

Class Variables and Constants


In this section, we define variables
and constants that are to be used later in the program. In a Java program, the variables and constants are
defined just after the class definition. The variables and constants store values of the parameters. It is used

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:

class Student //class definition


{
String sname; //variable
int id;
double percentage;
}
Main Method Class
In this section, we define the main() method. It is essential for all Java programs. Because the execution
of all Java programs starts from the main() method. In other words, it is an entry point of the class. It must
be inside the class. Inside the main method, we create objects and call the methods. We use the following
statement to define the main() method:

public static void main(String args[])


{
}
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}

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

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
5. Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside package


Modifier class package subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Default Access Modifier


If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default the
default access modifier is considered. For example,
package defaultPackage;
class MyClaass {
void message(){
System.out.println("This is a message");
}
}

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

public class Main {


public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


d.name = "Saranathan";
}
}

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();

// access the private variable using the getter and setter


d.setName("Programiz");
System.out.println(d.getName());
}
}

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");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
dog.display();
}
}
Output:
I am an animal
In the above example, we have a protected method named display() inside the Animal class.
The Animal class is inherited by the Dog class. We then created an object dog of the Dog class. Using the
object we tried to access the protected method of the parent class.
Since protected methods can be accessed from the child classes, we are able to access the method
of Animal class from the Dog class.
Note: We cannot declare classes or interfaces protected in Java.

61
SCE/CSBS

Public Access Modifier


When methods, variables, classes, and so on are declared public, then we can access them from anywhere.
The public access modifier has no scope restriction. For example,
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;

// 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();

// accessing the public variable


animal.legCount = 4;
// accessing the public method
animal.display();
}
}
Output:
I am an animal.
I have 4 legs.
Here,
 The public class Animal is accessed from the Main class.
 The public variable legCount is accessed from the Main class.
 The public method display() is accessed from the Main class.

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);
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("object reference = " + obj);
}
}
Output:
this reference = Main@23fc625e
object reference = Main@23fc625e
In the above example, we created an object named obj of the class Main. We then print the reference to
the object obj and this keyword of the class.
Here, we can see that the reference of both obj and this is the same. It means this is nothing but the
reference to the current object.

Java Methods

A method is a block of code that performs a specific task.


Suppose you need to create a program to create a circle and color it. You can create two methods to solve
this problem:
 a method to draw the circle
 a method to color the circle
Dividing a complex problem into smaller chunks makes your program easy to understand and reusable.
In Java, there are two types of methods:
 User-defined Methods: We can create our own method based on our requirements.
 Standard Library Methods: These are built-in methods in Java that are available to use.
Let's first learn about user-defined methods.

Declaring a Java Method


The syntax to declare a method is:
returnType methodName() {

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.

Calling a Method in Java


In the above example, we have declared a method named addNumbers(). Now, to use the method, we
need to call it.
Here's is how we can call the addNumbers() method.
// calls the method
addNumbers();

64
SCE/CSBS

Working of Java Method Call

Example 1: Java Methods


class Main {

// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}

public static void main(String[] args) {

int num1 = 25;


int num2 = 15;

// create an object of Main


Main obj = new Main();
// calling method
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}
Output
Sum is: 40
In the above example, we have created a method named addNumbers(). The method takes two
parameters a and b. Notice the line,
int result = obj.addNumbers(num1, num2);

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.

Java Method Return Type


A Java method may or may not return a value to the function call. We use the return statement to return
any value. For example,
int addNumbers() {
...
return sum;
}
Here, we are returning the variable sum. Since the return type of the function is int. The sum variable
should be of int type. Otherwise, it will generate an error.
Example 2: Method Return Type
class Main {

// create a method
public static int square(int num) {

// return statement
return num * num;
}

public static void main(String[] args) {


int result;

// call the method


// store returned value to result
result = square(10);

System.out.println("Squared value of 10 is: " + result);


}
}

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);
}

Method Parameters in Java


A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any
number of parameters. For example,
// method with two parameters
int addNumbers(int a, int b) {
// code
}

// method with no parameter


int addNumbers(){
// code
}
If a method is created with parameters, we need to pass the corresponding values while calling the
method. For example,
// calling the method with two parameters
addNumbers(25, 15);

67
SCE/CSBS

// calling the method with no parameters


addNumbers()

Example 3: Method Parameters


class Main {

// method with no parameter


public void display1() {
System.out.println("Method without parameter");
}

// method with single parameter


public void display2(int a) {
System.out.println("Method with a single parameter: " + a);
}

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// calling method with no parameter


obj.display1();

// calling method with the single parameter


obj.display2(24);
}
}
Output
Method without parameter
Method with a single parameter: 24
Here, the parameter of the method is int. Hence, if we pass any other data type instead of int, the compiler
will throw an error. It is because Java is a strongly typed language.
Note: The argument 24 passed to the display2() method during the method call is called the actual
argument.
The parameter num accepted by the method definition is known as a formal argument. We need to specify
the type of formal arguments. And, the type of actual arguments and formal arguments should always
match.

68
SCE/CSBS

What are the advantages of using methods?


1. The main advantage is code reusability. We can write a method once, and use it multiple times. We do
not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times".
Example 5: Java Method for Code Reusability
public class Main {

// method defined
private static int getSquare(int x){
return x * x;
}

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {

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

float func(int a, float b) { ... }


Here, the func() method is overloaded. These methods have the same name but accept different
arguments.
Note: The return types of the above methods are not the same. It is because method overloading is not
associated with return types. Overloaded methods may have the same or different return types, but they
must differ in parameters.
Why method overloading?
Suppose, you have to perform the addition of given numbers but there can be any number of arguments
(let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods sum2num(int, int) and sum3num(int, int,
int) for two and three parameters respectively. However, other programmers, as well as you in the future
may get confused as the behavior of both methods are the same but they differ by name.
The better way to accomplish this task is by overloading methods. And, depending upon the argument
passed, one of the overloaded methods is called. This helps to increase the readability of the program.

How to perform method overloading in Java?


Here are different ways to perform method overloading:
1. Overloading by changing the number of parameters
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}
Output:
Arguments: 1
Arguments: 1 and 4

Example: 2
class HelperService {

70
SCE/CSBS

private String formatNumber(int value) {


return String.format("%d", value);
}

private String formatNumber(double value) {


return String.format("%.3f", value);
}

private String formatNumber(String value) {


return String.format("%.2f", Double.parseDouble(value));
}

public static void main(String[] args) {


HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}
When you run the program, the output will be:
500
89.993
550.00

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.

Example 1: Java Constructor


class Main {
private String name;

// constructor
Main() {
System.out.println("Constructor Called:");
name = "Saranathan";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}
Output:
Constructor Called:
The name is Saranathan
In the above example, we have created a constructor named Main(). Inside the constructor, we are
initializing the value of the name variable.
Notice the statement of creating an object of the Main class.
Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And, the value of the name variable is
initialized.
Hence, the program prints the value of the name variables as Saranathan.

Types of Constructor

72
SCE/CSBS

In Java, constructors can be divided into 3 types:


1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,
private Constructor() {
// body of the constructor
}

Example 2: Java private no-arg constructor


class Main {

int i;

// constructor with no parameter


private Main() {
i = 5;
System.out.println("Constructor is called");
}

public static void main(String[] args) {

// calling the constructor without any parameter


Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Output:
Constructor is called
Value of i: 5
In the above example, we have created a constructor Main(). Here, the constructor does not accept any
parameters. Hence, it is known as a no-arg constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private, it cannot be accessed from outside the class. So, creating objects
from outside the class is prohibited using the private constructor.

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

// object is created in another class


Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}

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;

// constructor accepting single value


Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {

74
SCE/CSBS

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output:
Java Programming Language
Python Programming Language
C Programming Language
In the above example, we have created a constructor named Main(). Here, the constructor takes a single
parameter. Notice the expression,
Main obj1 = new Main("Java");
Here, we are passing the single value to the constructor. Based on the argument passed, the language
variable is initialized inside the constructor.

3. Java Default Constructor


If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the
execution of the program. This constructor is called default constructor.
Example 5: Default Constructor
class Main {

int a;
boolean b;

public static void main(String[] args) {

// A default constructor is called


Main obj = new Main();

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.

Example 6: Java Constructor Overloading


class Main {

String language;

// constructor with no parameter


Main() {
this.language = "Java";
}

// constructor with a single parameter


Main(String language) {
this.language = language;

76
SCE/CSBS

public void getName() {


System.out.println("Programming Langauage: " + this.language);
}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

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.

static keyword in Java

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 block or static initialization block, and,


 static class

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

public class Main {

public static void main( String[] args ) {

78
SCE/CSBS

// create an instance of the StaticTest class


StaticTest st = new StaticTest();

// call the nonstatic method


System.out.println(" 2 * 2 = " + st.multiply(2,2));

// call the static method


System.out.println(" 2 + 3 = " + StaticTest.add(2,3));
}
}
Output:
2*2=4
2+3=5
In the above program, we have declared a non-static method named multiply() and a static method
named add() inside the class StaticTest.
Inside the Main class, we can see that we are calling the non-static method using the object of the class
(st.multiply(2, 2)). However, we are calling the static method by using the class name (StaticTest.add(2,
3)).
Static Variables
In Java, when we create objects of a class, then every object will have its own copy of all the variables of
the class. For example,
class Test {
// regular variable
int age;
}

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() {

System.out.println("a = " + a);


System.out.println("b = " + b);
System.out.println("max = " + max);
}

public static void main(String args[]) {


// calling the static method
display();
}
}
Output:
First Static block.
Second Static block.
a = 23
b = 92
max = 30

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

1. Single Line Comment - //This is single line comment


2. Multi Line Comment -
/*
This
is
multi line
comment
*/

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:

Tag Syntax Description

{@docRoot} {@docRoot} to depict relative path to root directory of generated


document from any page.

@author @author name - text To add the author of the class.

@code {@code text} To show the text in code font without interpreting it
as html markup or nested javadoc tag.

@version @version version-text To specify "Version" subheading and version-text


when -version option is used.

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

Let's use the Javadoc tag in a Java program.

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
*/

public class Calculate{


/**
* This method calculates the summation of two integers.
* @param input1 This is the first parameter to sum() method
* @param input2 This is the second parameter to the sum() method.
* @return int This returns the addition of input1 and input2
*/
public int sum(int input1, int input2){
return input1 + input2;
}
/**
* This is the main method uses of sum() method.
* @param args Unused

83
SCE/CSBS

* @see IOException
*/
public static void main(String[] args) {
Calculate obj = new Calculate();
int result = obj.sum(40, 20);

System.out.println("Addition of numbers: " + result);


}
}
Compile it by javac tool and run. The output is Addition of numbers: 60

Create documentation API by javadoc tool:


Cmd prompt:> javadoc calculate.java
Now, the HTML files are created for the Calculate class in the current directory, i.e., abcDemo. Open the
HTML files, and we can see the explanation of Calculate class provided through the documentation
comment.

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

13 Assess with example what is meant by parameter passing Create


constructor.
14 Quote the purpose of finalize methods. Remember
15 List out the type of Arrays. Apply
16 Illustrate the working of Java Virtual Machine (JVM). Remember
17 Define static variable and static method. Remember
18 Explain what is meant by Java package. Analyze
19 Infer how to import a single package. Apply
20 Summarize any four Java doc comments Evaluate
P
A
R
T

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

8 i.Summarize about access specifier in Java. Understand


ii.Describe the term static fields and methods and explain its
types with example.
9 i) Define Arrays. What is array sorting and explain with an Remember
example.
ii)Tabulate and explain documentation comments in Java.
10 Illustrate what is meant by package? How its types are Apply
created and implemented in Java.
11 Write the techniques to design classes in Java using Create
JavaDoc.
12 Explain with example passing objects as parameters to Analyze
methods and returning objects from methods in Java.

85
SCE/CSBS

13 Explain packages in Java with example. Analyze


14 Interpret with an example what is method overloading and Understand
method overriding.
PART C
1 Develop a Java application to generate Electricity bill. Create Create
a class with the following members: Consumer no., consumer
name, previous month reading, current month reading, type of
EB connection (i.e domestic or commercial). Compute the bill
amount using the following tariff.
If the type of the EB connection is domestic, calculate
theamount to be paid as follows:
i. First 100 units - Rs. 1 per unit
ii. 101-200 units - Rs. 2.50 per unit
iii. 201 -500 units - Rs. 4 per unit
iv. > 501 units - Rs. 6 per unit
2 Evaluate a Java program to find a smallest number in the Evaluate
given array by creating one dimensional array and two
dimensional array using new operator.
3 Explain class hierarchy and explain its types with suitable Evaluate
examples.

4 Develop a Java application with Employee class with Create


Emp_name, Emp_id, Address, Mail_id, Mobile_no as
members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from employee
class. Add Basic Pay (BP) as the member of all the inherited
classes with 97% of BP as DA, 10 % of BP as HRA, 12% of
BP as PF, 0.1% of BP for staff club fund. Generate pay slips
for the employees with their gross and net salary.
2 Evaluate a Java program to find a smallest number in the Evaluate
given array by creating one dimensional array and two
dimensional array using new operator.
3 Explain class hierarchy and explain its types with suitable Evaluate
examples.
4 Develop a Java application with Employee class with Create
Emp_name, Emp_id, Address, Mail_id, Mobile_no as
members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from employee
class. Add Basic Pay (BP) as the member of all the inherited
classes with 97% of BP as DA, 10 % of BP as HRA, 12% of
BP as PF, 0.1% of BP for staff club fund. Generate pay slips
for the employees with their gross and net salary.

86

You might also like