Unit 1 2022 OOP-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

UNIT I CS3391- INTRODUCTION TO OOP AND JAVA

Overvew 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- Java Doc comments

1.Overview of OOP

1.1 Object oriented programming paradigms

The major motivating factor in the invention of object-oriented approach is to remove some of the
flaws encountered in the procedural approach.

OOP treats data as a critical element in the program development and does not allow it to flow
freely aroundthe system. It ties data more closely to the function that operate on it, and protects
itfrom accidental modification from outside function.

OOP allows decomposition of aproblem into a number of entities called objects and then builds data
and functionaround these objects.

Fig:Organization of data and function in OOP

Some Characteristics of Object Oriented Programming


• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the datastructure.
• Data is hidden and cannot be accessed by external function.
•Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.

1. Object-Oriented Programming (OOP) is the term used to describe a programming approach


based on objects and classes. The object-oriented paradigm allows us to organize software as
a collection of objects that consist of both data and behaviour.
2. Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs are toat
least some extent object-oriented.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 1


OOP allows decomposition of a problem into a number of entities called objects and then builds data
and functions around these objects.

3. The software is divided into a number of small units called objects. The data and functions
are built around these objects.
4. The data of the objects can be accessed only by the functions associated with that object.
5. The functions of one object can access the functions of another object.

The object-oriented programming approach encourages:

1. Modularisation: where the application can be decomposed into modules.

 Software re-use: where an application can be composed from existing and new modules.
To support the principles of object-oriented programming, all OOP languages, have the following
characteristics
1.2 Features of Object Oriented Programming

Abstraction
Abstraction refers to the act of representing essential features without including the background
details or explanation.
 Abstraction is one of the key concepts of object-oriented programming (OOP) languages.
 Data Abstraction can be defined as the process of identifying only the required(essential)
characteristics of an object ignoring the irrelevant details.
 Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
 Its main goal is to handle complexity by hiding unnecessary details from the user. That
enables the user to implement more complex logic on top of the provided abstraction without
understanding or even thinking about all the hidden complexity.
 Abstraction is a process where you show only “relevant” data and “hide” unnecessary details
of an object from the user.
Example1:
when you login to your bank account online, you enter your user_id and password and press
login, what happens when you press login, how the input data sent to server, how it gets
verified is all abstracted away from the you.
Example2:
When you press a key on your keyboard the character appears on the screen, you need to
know only this, but how exactly it works based on the electronically is not needed.
This is called Abstraction.
• Abstraction is achieved by using Interface and abstract class in java

Encapsulation
The wrapping up of data and functions into a single unit (called class) is known as Encapsulation.
 Data Encapsulation is the most striking feature of a class.
 The data is not accessible to the outside world, and only those functions which are wrapped
in the class can access it.
 These functions provide the interface between the object’s data and the program.
 Encapsulation is a process of combining data and function into a single unit like capsule.
This is to avoid the access of private data members from outside the class.

 Encapsulation simply means binding object state(fields) and behaviour(methods) together.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 2


 Encapsulation is a way to achieve "information hiding“
o The insulation of the data from direct access by the program is called data hiding or
information hiding.
 CLASS is the best example for encapsulation

Inheritance

Inheritance is the process by which one object acquires the properties of another object.
The mechanism of deriving a new class from existing/old class is called “inheritance”.
 The old class is known as “base” class, “super” class or “parent” class”; and the new
class is known as “sub” class, “derived” class, or “child” class.

 Thisis important because it supports the concept of hierarchical classification. (that is, top-
down classifications.)
 For example, a Golden Retriever is part of the classification dog, which in turn is part of
themammal class, which is under the larger class animal. Without the use of hierarchies,
eachobject would need to define all of its characteristics explicitly.
 Using inheritance, an object need only define those qualities that make it unique within its
class. It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism
that makes it possible for one object to be a specific instance of a more general case

Polymorphism
 Polymorphism,a Greek term ,means the ability to take more than one form.
 In Java, polymorphism refers to the fact that you can have multiple methods with the
same name in the same class.

There are two kinds of polymorphism:


1. Overloading
Two or more methods with different signatures
2.Overriding
Replacing an inherited method with another having the same signature.
Method Overloading
Method overloading: having multiple methods with the same name but different
signatures in a class

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 3


int add (int a, int b)
floatadd (float a, int b) float
add (int a, float b) void
add (float a)

int add (int a)

Method Overriding
 If a derived class has a method found within its base class, that method will override the base
class’s method
 The keyword super can be used to gain access to superclass methods overridden by the
base class
 A subclass method must have the same return type as the corresponding superclass
 Method.This is called overriding a method
 Method print in Dog overrides method print in Animal
 A subclass variable can shadow a superclass variable, but a subclass method can
override a superclass method.
Example
class Animal
{
void print()
{
System.out.println("Superclass Animal");
}
}

public class Dog extends Animal


{
void print()
{
System.out.println("Subclass Dog");
}
public static void main(String args[])
{
Animal animal = new Animal();
Dog dog = new Dog();
animal.print();
dog.print();
}
}

Overriding vs Overloading
 A method is overloaded if it has multiple definitions that are distinguished from one
another by having different numbers or types of arguments
 A method is overridden when a subclass gives a different definition of the method with
the same number and types of arguments

program to display details of student using class and object


//Program to display the details of a student using class and
object class Student
{
int rollNo; //properties -- variables
String name;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 4


void display () //method -- action
{ System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo
{
public static void main(String args[])
{
//create an object to Student
class Student s = new Student ();
//call display () method inside Student class using
object s s.display ();
}
}

2. Java Buzzwords (JAVA FEATURES)

1.Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand.
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many confusing and rarely-used features e.g. explicit pointers, operator
overloading etc.
There is no need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
2.Object-oriented programming
Java is object-oriented programming language. Everything in Java is an object. Object-
oriented means we

organize our software as a combination of different types of objects that incorporates both data
and behaviour.

3.Platform independent
Java is platform independent because it is different from other languages like C, C++ etc.

which are compiled into platform specific machines while Java is a write once, run anywhere
language
compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based.


Java provides software-based platform.

4.Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
No explicit pointer. Java Programs run inside virtual machine sandbox

5.Java is robust
It uses strong memory management.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 5


There are lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore. There is exception handling
and type checking mechanism in java.
All these points makes java robust.

6.Architecture neutral
Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture.
But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.

7.Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't
require any type of implementation.

8.High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. (JIT)

9.Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI and
EJB are used for creating distributed applications.
This feature of Java makes us able to access files by calling the methods from any machine on
the internet.

10.Multi-threaded.
A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each thread.
It shares a common memory area.
Threads are important for multi-media, Web applications etc.
Objects are dynamically allocated by using the new operator, dynamically allocated objects
must be manually released by use of a delete operator.

11.Garbage collection
Java takes a different approach; it handles deallocation automatically this is called garbage
collection.
When no references to an object exist, that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 6


12.Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand.
It also supports functions from its native languages i.e. C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection.

3. OVERVIEW OF JAVA
 JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later
acquired by Oracle Corporation.
 It is a simple programming language. Java makes writing, compiling, and debugging
programming easy.
 It helps to create reusable code and modular programs. Java is a class-based, object-oriented
programming language and is designed to have as few implementation dependencies as
possible.
 A general-purpose programming language made for developers to write once run anywhere
that is compiled Java code can run on all platforms that support Java.
 Java applications are compiled to byte code that can run on any Java Virtual Machine. The
syntax of Java is similar to c/c++

History: Java’s history is very interesting.


 It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick
Naughton, a team of Sun engineers known as the Green team initiated the Java language in
1991.
 Sun Microsystems released its first public implementation in 1996 as Java 1.0.
 It provides no-cost -run-times on popular platforms. Java1.0 compiler was re-written in Java
by Arthur Van Hoff to strictly comply with its specifications.
 With the arrival of Java 2, new versions had multiple configurations built for different types
of platforms.

Java Environment

JRE
• JRE is an acronym for Java Runtime Environment.
• .The Java Runtime Environment is a set of software tools which are used for developing java
applications.
• It is used to provide runtime environment.
• It is the implementation of JVM. It physically exists.
• It contains set of libraries + other files that JVM uses at runtime

• The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as
an interpreter/loader (Java),
• compiler (javac),
• archiver (jar),
• a documentation generator (Javadoc) etc

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 7


• JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).

The JVM performs following operation:


1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment
1.Classloader
Classloader is a subsystem of JVM that is used to load class files.
2.Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3.Heap
It is the runtime data area in which objects are allocated.
4.Stack
 Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
 Each thread has a private JVM stack, created at the same time as thread.
 A new frame is created each time a method is invoked. A frame is destroyed when
its method invocation completes.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 8


 We can download the JDK (Java Development Kit) including the compiler and
runtimeengine from Sun at: http://java.sun.com/javase.
 Install JDK after downloading, by default JDK will be installed in
 C:\Program Files\Java\jdk1.5.0_05 (Here jdk1.5.0_05 is JDK‟s version)

Setting up Java Environment: After installing the JDK, we need to set at least oneenvironment
variable in order to able to compile and run Java programs.
A PATH environment variable enables the operating system to find the JDK executables when
ourworking directory is not the JDK's binary directory.

Setting environment variables from a command prompt: If we set the variables from a command
prompt, they will only hold for that session.
To set the PATH from acommand prompt:
set PATH=C:\Program Files\Java\jdk1.5.0_05\bin;

Setting environment variables as system variables:


If we set the variables assystem variables they will hold continuously.
 Right-click on My ComputerChoose PropertiesSelect the Advanced tab
 Click the Environment Variablesbutton at the bottomIn system variables tab,
selectpath (system variable) andclick on edit button
 A window with variable namepathand its value will bedisplayed.
 Don’t disturb the default pathvalue that is appearing andjust append (add) to that pathat the
end:
 C:\ProgramFiles\Java\jdk1.5.0_05\bin;Finally press OK button.

4.Data Types, Variables and Arrays


Data type specifies the size and type of values that can be stored in an identifier.
 The Java language is rich in its data types.
 Different data types allow you to select the type appropriate to the needs of the application.
 Based on the data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory.
 Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables.

Data types in Java are classified into two types:

1. Primitive—which include Integer, Character, Boolean, and Floating Point.


2. Non-primitive—which include Classes, Interfaces, and Arrays.

Data Types: The classification of data item is called data type. Java defines eight simple types
ofdata. byte, short, int, long, char, float, double and boolean. These can be put in four groups:

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 9


1. Integer Data Types: These data types store integer numbers

Data Type Memory size Range

byte 1 byte -128 to 127

short 2 bytes -32768to 32767

int 4 bytes -2147483648to 2147483647

long 8 bytes -9223372036854775808 to 9223372036854775807

e.g.: byte rno = 10;


long x = 150L; L means forcing JVM to allot 8 bytes
2. Float Data Types: These data types handle floating point numbers

Data Type Memory size Range

float 4 bytes -3.4e38 to 3.4e38

double 8 bytes -1.7e308 to 1.7e308

e.g.: float pi = 3.142f;


double distance = 1.98e8;

3.Character Data Type: This data type represents a single character. char data type injava uses
two bytes of memory also called Unicode system. Unicode is a specification to include alphabets of
all international languages into the character set of java.

Data Type Memory size Range

char 2 bytes 0 to 65535

e.g.: char ch = 'x';

4.Boolean Data Type: can handle truth values either true or falsee.g.:-
boolean response = true;

Variables in Java
A variable is the name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
 In Java, all the variables must be declared before they can be used.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 10


Variable Declaration:
We can declare variables in java as follows:
Syntax:
type variable_name;

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Rules of Declaring variables in Java

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. Variable name can begin with special characters such as $ and _
As per the java coding standards,the first character must be a letter.
3. Blank spaces cannot be used in variable names.
4. Java keywords cannot be used as variable names.
5. Variable names are case-sensitive

There are three types of variables in Java:


1) Local Variable
A variable declared inside the method is called local variable.

2) Instance Variable
A variable declared inside the class but outside the method, is called instance variable . It is not
declared as static.

3) Static variable
A variable which is declared as static is called static variable. It cannot be local.

Example to understand the types of variables in java


class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 11


1.Local Variables: A variable defined inside the method or constructor is called local variable.
 These variable are created when the block in entered or the function is called and destroyed
after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is declared. i.e.
we can access these variable only within that block.

Sample Program 1:
public class StudentDetails
{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}

public static void main(String args[])


{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}
Output:
Student age is :5
In the above program the variable age is local variable to the function StudentAge(). If we use the
variable age outside StudentAge() function, the compiler will produce an error as shown in below
program.
Sample Program 2:
public class StudentDetails
{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
}

public static void main(String args[])


{
//using local variable age outside it's scope
System.out.println("Student age is : " + age);
}
}

Output:
error: cannot find symbol”+ age

2.Instance Variables:
A variable declared inside the class but outside the method, is called instance variable. It is not
declared as static.
Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 12


 As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not specify
any access specifier then the default access specifier will be used
Example:
import java.io.*;
class Marks
{
//These variables are instance variables.
//These variables are in a class and are not inside any function
int mathsMarks;
int phyMarks;
}

class MarksDemo
{
public static void main(String args[])
{ //first object
Marks obj1 = new Marks();
obj1.mathsMarks = 80;
obj1.phyMarks = 90;

//second object
Marks obj2 = new Marks();
obj2.mathsMarks = 60;
obj2.phyMarks = 85;

//displaying marks for first object


System.out.println("Marks for first object:");
System.out.println(obj1.mathsMarks);
System.out.println(obj1.phyMarks);

//displaying marks for second object


System.out.println("Marks for second object:");
System.out.println(obj2.mathsMarks);
System.out.println(obj2.phyMarks);
}
}

Output:
Marks for first object:
80
90
Marks for second object:
60
85
 As you can see in the above program the variables mathsMarks , phyMarksare instance
variables.
 In case we have multiple objects as in the above program, each object will have its own
copies of instance variables.
 It is clear from the above output that each object will have its own copy of instance variable.

3.Static Variables:
A variable which is declared as static is called static variable. It cannot be local.
Static variables are also known as Class variables.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 13


 These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method constructor or
block.
 Unlike instance variables, we can only have one copy of a static variable per class irrespective
of how many objects we create.
 Static variables are created at start of program execution and destroyed automatically when
execution ends.

Syntax for static and instance variables:


class Example
{
static int a; //static variable
int b; //instance variable
}

To access static variables, we need not to create any object of that class, we can simply access the
variable as:
class_name.variable_name;
Sample Program:
import java.io.*;
class Emp
{

// static variable salary


public static double salary;
public static String name = "Harsh";
}

public class EmpDemo


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

//accessing static variable without object


Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}

}
output:
Harsh's average salary:1000.0

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 14


Instance variable Vs Static variable

Arrays

An array represents a group of elements of same data type. Arrays are generallycategorized into two
types:

· Single Dimensional arrays (or 1 Dimensional arrays)

· Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)

Single Dimensional Arrays


A one dimensional array or single dimensional arrayrepresents a row or a column of elements. For
example, the marks obtained by a student in 5 different subjects can be represented by a 1D array.
·
int marks[] = {50, 60, 55, 67, 70};

We can create a 1D array by declaring the array first and then allocate memory for it by
using new operator, as:
int marks[]; //declare marks array
marks = new int[5];//allot memory for storing 5 elements

These two statements also can be written as:


int marks [] = new int [5];

Advantage of Java Array


 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.
Disadvantage of Java Array
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size
at runtime.
 To solve this problem, collection framework is used in java.[ArrayList]
Types of Array in java
1. One- Dimensional Array
2. Multidimensional Array

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 15


Declaration, Instantiation and Initialization of Java Array
Example:1-->Single dimensional array
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Output:
10
20
70
40
50
Example:2
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaration, instantiation and initialization

//printing array
for(int i=0;i<a.length;i++)
System.out.print(a[i]);
}}
Output:
33 3 4 5
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.
Example:
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 16


Output:
3
Multi-Dimensional Arrays (2D, 3D … arrays):
Multi dimensional arrays represent 2D, 3D…arrays. A two dimensional array is a combination of
two or more (1D) one dimensional arrays. A three dimensional array is a combination of two or more
(2D) two dimensional arrays.

Two Dimensional Arrays (2d array)


A two dimensional array represents severalrows and columns of data. To represent a two
dimensional array, we should use two pairs of square braces [ ] [ ] after the array name. For
example, the marks obtained by a group of students in five different subjects can be represented
by a 2D array.

o We can declare a two dimensional array and directly store elements at the time ofits
declaration, as:

int marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };

We can create a two dimensional array by declaring the array first and then we can allotmemory
for it by using new operator as:

int marks[ ] [ ]; //declare marks array

marks = new int[3][5]; //allot memory for storing 15 elements.

These two statements also can be written as: int marks [ ][ ] = new int[3][5];
Program 2: Write a program to take a 2D array and display its elements in the form of a
matrix. //Displaying a 2D array as a matrix
class Matrix
{
public static void main(String args[])
{
//take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} };
// display the array elements
for (int i = 0 ; i < 2 ; i++)
{
System.out.println (); for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] + “\t”);
}
}
}
Three Dimensional arrays (3D arrays)
We can consider a three dimensional arrayas a combination of several two dimensional arrays. To
represent a three dimensional array, we should use three pairs of square braces [ ] [ ] after the array
name.

o We can declare a three dimensional array and directly store elements at the time ofits
declaration, as:
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};

o We can create a three dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:

int arr[ ] [ ][ ] = new int[2][2][3]; //allot memory for storing 15 elements.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 17


5.Operators
An operator is a symbol that performs an operation. An operator acts onvariables called
operands.
Operators are special symbols (characters) that carry out operations on operands (variables and
values). For example, + is an operator that performs addition.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups

1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
1.Arithmetic operators: These operators are used to perform fundamental operationslike addition,
subtraction, multiplication etc.

Operator Meaning Example Result

+ Addition 3+4 7

- Subtraction 5-7 -2

* Multiplication 5*5 25

/ Division (gives quotient) 14 / 7 2

% Modulus (gives remainder) 20 % 7 6

2.Assignment operator: This operator (=) is used to store some value into a variable.

Simple Assignment Compound Assignment

x=x+y x += y
x=x–y x -= y
x=x*y x *= y
x=x y x /= y

3. Unary operators: As the name indicates unary operator’s act only on one operand.

Operator Meaning Example Explanation


- Unary minus j = -k; k value is negated and stored into j
b value will be incremented by 1
Increment b++; (called as post increment)
++
Operator ++b; b value will be incremented by 1
(called as pre increment)
b value will be decremented by 1
Decrement b--; (called as post decrement)
--
Operator --b; b value will be decremented by 1
(called as pre decrement)

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 18


· 4. Relational operators: These operators are used for comparison purpose.

Operator Meaning Example


== Equal x == 3
!= Not equal x != 3

< Less than x<3

> Greater than x>3

<= Less than or equal to x <= 3

· 5.Logical operators: Logical operators are used to construct compound conditions. A


compound condition is a combination of several simple conditions.

Operator Meaning Example Explanation


if(a>b && a>c) If a value is greater than b and c
&& and operator
System.out.print(“yes”); then only yes is displayed
if(a==1 || b==1) If either a value is 1 or b value is 1
|| or operator
System.out.print(“yes”); then yes is displayed
if( !(a==0) ) If a value is not equal to zero then
! not operator
System.out.print(“yes”); only yes is displayed
6. Bitwise operators: These operators act on individual bits (0 and 1) of the operands.They act
only on integer data types, i.e. byte, short, long and int.
Operator Meaning Explanation
& Bitwise AND Multiplies the individual bits of operands
| Bitwise OR Adds the individual bits of operands
^ Bitwise XOR Performs Exclusive OR operation
<< Left shift Shifts the bits of the number towards left a specified
number of positions
>> Right shift Shifts the bits of the number towards right a
specified number of positions and also preserves the
sign bit.
>>> Zero fill right shift Shifts the bits of the number towards right a
specified number of positions and it stores 0 (Zero)
in the sign bit.
~ Bitwise complement Gives the complement form of a given number by
changing 0‟s as 1‟s and vice versa.

7. Ternary Operator or Conditional Operator (? :):


This operator is called ternarybecause it acts on 3 variables. The syntax for this operator is:
Variable = Expression1? Expression2: Expression3;

First Expression1 is evaluated. If it is true, then Expression2 value is stored into variable otherwise
Expression3 value is stored into the variable.
e.g.: max = (a>b) ? a: b;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 19


Example programs :
1.Arithmetic Operators
import java.util.Scanner;

public class ArithmeticOperation


{

public static void main(String[] args)


{

// Create scanner class object


Scanner in = new Scanner(System.in);

// Input two numbers from user


System.out.println("Enter first number :");
int num1 = in.nextInt();
System.out.println("Enter second number :");
int num2 = in.nextInt();

// Perform arithmetic operations.


int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
int quotient = num1 / num2;
int modulo = num1 % num2;

// Print result to console.


System.out.println("Sum : " + sum);
System.out.println("Difference : " + difference);
System.out.println("Product : " + product);
System.out.println("Quotient : " + quotient);
System.out.println("Modulo : " + modulo);
}
}
Output:
Enter first number : 15
Enter second number : 4

Sum : 19
Difference : 11
Product : 60
Quotient : 3
Remainder : 3

2.Increment and Decrement Operators


Example:
// Demonstrate ++.
class IncDec
{

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 20


public static void main(String args[])
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b; //++23
d = a++; //d=1,a=2
c++; //c=3, c4

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


System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
Output:
a=2
b=3
c=4
d=1
3.Relational Operators
public class Test
{

public static void main(String args[]) {


int a = 10;
int b = 20;

System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

4.Logical Operators
class Logicalop
{
public static void main(String[] args)
{

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 21


// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Output
truefalse
true
true
false
true
false

5.Bitwise Operators
class Test
{

public static void main(String args[])


{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */


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

c = a << 2; /* 240 = 1111 0000 */


System.out.println("a << 2 = " + c );

c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );

c = a >>> 2; /* 15 = 0000 1111 */


System.out.println("a >>> 2 = " + c );
}
}

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 22


Output
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15

6. Control Statements

Java provides three types of control flow statements.

1. Decision Making statements


o if statements(i
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Conditional Statements( or )Decision Making Statements( or)Selection Statements in Java


• A programming language uses control statements to control the flow of execution of program
based on certain conditions.
If Statement:
In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

1.if Statement
• if statement is the most simple decision making statement.
• It is used to decide whether a certain statement or block of statements will be executed
or not that is if a certain condition is true then a block of statement is executed otherwise not.

Syntax:
if(condition)
{
//statements to execute if
//condition is true
}

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 23


Example:
class IfSample
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
if(x < y)
System.out.println("x is less than y");
x = x * 2;
if(x == y)
System.out.println("x now equal to y");
x = x * 2;
if(x > y)
System.out.println("x now greater than y");
// this won't display anything
if(x == y)
System.out.println("you won't see this");
}
}
Output:
x is less than y
x now equal to y
x now greater than y
2.if-else Statement
• The Java if-else statement also tests the condition.
• It executes the if block if condition is true else if it is false the else block is executed.
Syntax:.
If(condition)
{
//Executes this block if
//condition is true
}
else
{
//Executes this block if
//condition is false
}
Program:
public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 24


Output:
odd number

3.Nested if Statement
Nested if-else statements, is that using one if or else if statement inside another if or else if statement
Example:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12

4.if-else-if ladder statement


• The if statements are executed from the top down. The conditions controlling the if is true,
the statement associated with that if is executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be executed.
Syntax:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;

Example:
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 25


}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade

5.Switch Statements
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression.
Syntax:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
Example:
// A simple example of the switch.
class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:
System.out.println("i is zero.");
break;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 26


case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.

2.ITERATIVE STATEMENTS ( or )LOOPING STSTEMENTS


• In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. There are three types of loops in java.
1. while loop
2. do-while loop
3. For loop
1.while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition.
The while loop can be thought of as a repeating if statement.
Syntax:
while(condition) {
// body of loop
}

Example:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 5;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Output:
tick 5
tick 4
tick 3
tick 2
tick 1

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 27


2.do-while loop:
do while loop checks for condition after executing the statements, and therefore it is called as
Exit Controlled Loop.
Syntax:
do {
// body of loop
} while (condition);

Example
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5

3.for loop
• For loop provides a concise way of writing the loop structure.
• A for statement consumes the initialization,
condition and increment/decrement in one line.
Syntax
for(initialization; condition; iteration) {
// body
}
Example
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
System.out.println(i);
}
}}
Output:
1
2
3
4
5

4.for-each Loop
• The for-each loop is used to traverse array or collection in java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.
• It works on elements basis not index.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 28


• It returns element one by one in the defined variable.
Syntax:
for(type itr-var : collection) statement-block

Example:
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

5.Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
Example:
// Loops may be nested.
class Nested {
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}}
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 29


3.JUMP STATEMENTS
Java Break Statement
• When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
• The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition.
• In case of inner loop, it breaks only inner loop.
Example:
// Using break to exit a loop.
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++) {
if(i == 5)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
Loop complete.

Java Continue Statement


• The continue statement is used in loop control structure when you need to immediately
jump to the next iteration of the loop.
• It can be used with for loop or while loop.
• The Java continue statement is used to continue loop.
• It continues the current flow of the program and skips the remaining code at specified
condition.
• In case of inner loop, it continues only inner loop.
Example:
public class ContinueExample
{
public static void main(String args[])
{
for (int j=0; j<=6; j++)
{
if (j==4)
{ continue;
}
System.out.print(j+" ");
}
}
}
Output:
012356

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 30


7.Programming Structures in Java
As all other programming languages, Java also has a structure.
 The first line of the C/C++ program contains include statement. For example, <stdio.h> isthe
header file that contains functions, like printf (), scanf () etc. So if we want to use anyof these
functions, we should include this header file in C/ C++ program.
 Similarly in Java first we need to import the required packages. By default java.lang.*
isimported. Java has several such packages in its library. A package is a kind of directory
thatcontains a group of related classes and interfaces. A class or interface contains methods.
 Since Java is purely an Object Oriented Programming language, we cannot write a
Javaprogram without having at least one class or object. So, it is mandatory to write a class
inJava program. We should use class keyword for this purpose and then write class name.
 In C/C++, program starts executing from main method similarly in Java, program
starts executing from main method. The return type of main method is void because
program starts executing from main method and it returns nothing.
Java Source File –Structure

• A package is a collection of classes, interfaces and sub-packages.


• Class is keyword used for developing user defined data type
• ClassName" represent a java valid variable name

Sample Program:

//A Simple Java Program


import java.lang.System;
import java.lang.String;
class Simple
{
public static void main(String args[])
{
System.out.print ("Hello world");
}
}
 save this file as Simple.java
 To compile:javac Simple.java
 To execute:java Simple
 Output:Hello Java

 Since Java is purely an Object Oriented Programming language, without creating anobject to
a class it is not possible to access methods and members of a class. Butmain method is also a
method inside a class, since program execution starts frommain method we need to call main
method without creating an object.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 31


 Static methods are the methods, which can be called and executed without creating
objects.Since we want to call main () method without using an object, we should declare
main ()method as static. JVM calls main () method using its Classname.main () at the time
ofrunning the program.
 JVM is a program written by Java Soft people (Java development team) and main () isthe
method written by us. Since, main () method should be available to the JVM, itshould be
declared as public. If we don’t declare main () method as public, then itdoesn’t make itself
available to JVM and JVM cannot execute it.
 JVM always looks for main () method with String type array as parameter otherwiseJVM
cannot recognize the main () method, so we must provide String type array asparameter to
main () method.
 A class code starts with a {and ends with a}. A class or an object contains variablesand
methods (functions). We can create any number of variables and methods insidethe class.
This is our first program, so we had written only one method called main ().
 Our aim of writing this program is just to display a string “Hello world”. In Java, print
()method is used to display something on the monitor.
 A method should be called by using objectname.methodname (). So, to call print ()
method, create an object to PrintStream class then call objectname.print () method.

Interesting points about main function


1 Since main() method of java is not returning any value and hence its return type must be void.
2 Since main() method of java executes only once throughout the java program execution and
hence its nature must be static.
3 Since main() method must be accessed by every java programmer and hence whose access
specifier must be public.
4 Each and every main() method of java must take array of objects of String.
5 The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java

Popular Java Editors/IDE :


1 Notepad/gedit : They are simple text-editor for writing java programs. Notepad is available on
Windows and gedit is available on Linux.
2 Eclipse IDE : It is most widely used IDE(Integrated Development Environment) for developing
softwares in java.

Escape Sequence:
 Java supports all escape sequence which is supported by C/ C++. Acharacter preceded by a
backslash (\) is an escape sequence and has special meaningto the compiler.
 When an escape sequence is encountered in a print statement, thecompiler interprets it
accordingly.

Escape Sequence Description


\t -Insert a tab in the text at this point.
\b- Insert a backspace in the text at this point.
\n- Insert a newline in the text at this point.
\r -Insert a carriage return in the text at this point.
\f -Insert a form feed in the text at this point.
\'- Insert a single quote character in the text at this point.
\"- Insert a double quote character in the text at this point.
\\ -Insert a backslash character in the text at this point.

Creating a Source File:

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 32


 Type the program in a text editor (i.e. Notepad, WordPad, Microsoft Word or Edit Plus).
Wecan launch the Notepad editor from the Start menu by selecting Programs >accessories
>
 Notepad. In a new document, type the above code (i.e. Sample Program).
Save the program with filename same as Class_name (i.e. Sample.java) in which mainmethod
is written. To do this in Notepad, first choose the File > Save menu item. Then, inthe Save
dialog box:
i. Using the Save in combo box, specify the folder (directory) where you'll save yourfile.
In this example, the directory is JQR on the D drive.
ii. In the File name text field, type "Sample.java", including the quotation marks.
iii. Then the dialog box should look like this:Now click Save, and exit Notepad.

Compiling the Source File into a class File:


 To Compile the Sample.java program go to DOS prompt. We can do this from the
Start menu by choosing Run... and then entering cmd. The window should look
similar to the following figure.
 The prompt shows current directory. To compile Sample.java source file, change
currentdirectory to the directory where Sample.java file is located. For example, if source
directory isJQR on the D drive, type the following commands at the prompt and press Enter:
 Now the prompt should change to D:\JQR>At the prompt, type the following command and
press Enter.javac Sample.java.The compiler generates byte code and Sample.class will be
created.

Executing the Program (Sample.class):


 To run the program, enter java followed by the class name created at the time of
compilation at the command prompt in the same directory as:java Sample
 The program interpreted and the output is displayed.

8. Defining classes in Java


CLASS
A class is the blueprint from which individual objects are created.
A class is a collection of fields (data) and methods (procedure or function) that operateon that data.

 In object-oriented programming, a class is a programming language construct that is used as a


blueprint to create objects. This blueprint includes attributes and methods that the created
objects all share.
 Usually, a class represents a person, place, or thing - it is an abstraction of a concept within a
computer program.

General form of a class:


Aclass is declared by use of the class keyword.
class className

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 33


{
Fields (properties) declaration
Methods (Actions)Declaration
}
e.g.: Classes contain data definitions(Fields Declaration)
class Dog
{
String name;
int age;
}
Adding Methods
A class with only data fields has no life. Objects created by such a class cannot respondto any
messages.
Methods are declared inside the body of the class but immediately after the declarationof data fields.
The general form of a method declaration is:

A class may contain methods that describe the behavior of objects


Example:
class Dog
{
void bark()
{
System.out.println("Woof!");
}
}

Example:Adding Methods to Class


class Dog
{
String name;
int age;
void display()
{
System.out.println("NAME OF STUDENT="+name);
System.out.println("AGE OF STUDENT="+age);
}
}

 Once a class has been defined, we can create any number of objects belonging to that class
 A class is thus a collection of objects similar types
 For examples, guava, mango and orange are objects of the class fruit.

OBJECTS

An Object is a real time entity. An object is an instance of a class.


Objects are the basic run time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle.
 The objects which exhibit similar properties and actions are grouped under one class. “To give a
real world analogy, a house is constructed according to a specification. Here, the specification is
a blueprint that represents a class, and the constructed house represents the object”.
 To access the properties and methods of a class, we must declare a variable of

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 34


that class type. This variable does not define an object.
 Instead, it is simply a variable that can refer to an object.
 We must acquire an actual, physical copy of the object and assign it to that variable.
We can do this using new operator. The new operator dynamically allocates memory for an
object and returns a reference to it.
 This reference is, more or less, the address in memory of the object allocated by new. This
reference is then stored in the variable.
 Thus, in Java, all class objects must be dynamically allocated.
General form of an Object:
Classname variablename; // declare reference to object
variablename = new Classname ( ); // allocate an object

e.g.:
Student s; // s is reference variable
s = new Student (); // allocate an object to reference variable s
The above two steps can be combined and rewritten in a single statement as:
Classname variable_name= new Classname ( ); // allocate an object

Student s = new Student ();


Now we can access the properties and methods of a class by using object with dot operator as:
s.rollNo, s.name, s.display ()

 When a program is executed, the objects interact by sending messages to one another. For
example, if “customer” and “account” are to object in a program, then the customer object
may send a message to the count object requesting for the bank balance.
 Each object contain data, and code to manipulate data. Objects can interact without having to
know details of each other’s data or code. It is sufficient to know the type of message
accepted, and the type of response returned by the objects.

9. Constructors & Methods


 A constructor is similar to a method that initializes the instance variables of a
class.
 A constructor name and classname must be same.

 A constructor may have or may not have parameters. Parameters are local
variables to receive data.

Rules for writing Constructor:


1 Constructor(s) of a class must has same name as the class name in which it resides.
2 A constructor in Java can not be abstract, final, static and Synchronized.
3 Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 35


Types of constructor

1. Default (No- Argument )constructor


2. Parameterized (Argument)constructor
3. Copy Constructor
1.Default (No- Argument )constructor

A constructor without any parameters is called default constructor.

e.g. class Student


{
int rollNo;-instance variable
String name;
Student( )
{
rollNo = 101;
name=“Kiran”;
}
}

Example:
Program to initialize student details using default constructor and display the
same.

//Program to initialize student details using default constructor and displaying the same.

class Student
{
int rollNo;
String name;
Student ()
{
rollNo = 101;
name = "Suresh";
}

void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}

class StudentDemo

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

Student s1 = new Student ();


System.out.println ("s1 object contains:");
s1.display ();
Student s2 = new Student ();

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 36


System.out.println ("s2 object contains:");
s2.display ();
}
}

Ex:2
class Box
{
double width;
double height;
double depth;
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0

2.Parameterized (Argument)constructor
A constructor with one or more parameters is called parameterized constructor.

e.g. class Student

{
int rollNo;
String name;

Student (int r, String n)


{
rollNo = r;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 37


name = n;}
}
}
o A constructor does not return any value, not even void.A constructor is called and
executed at the time of creating an object. A constructor is called only once per object.

o Default constructor is used to initialize every object with same data where
asparameterized constructor is used to initialize each object with different data.
o If no constructor is written in a class then java compiler will provide default values.

Example:Program to initialize student details using Parameterized constructor


and display the same.

//Program to initialize student details using parameterizedconstructor


class Student
{
int rollNo;
String name;

Student (int r, String n)

{ rollNo = r;
name = n;

void display ()

{ System.out.println ("Student Roll Number is: " + rollNo);


System.out.println ("Student Name is: " + name);

}
class StudentDemo

{
public static void main(String args[])

{
Student s1 = new Student(101, “Suresh”);
System.out.println (“s1 object contains: “ );
s1.display();
Student s2 = new Student (102, “Ramesh”);

System.out.println (“s2 object contains:“ );


s2.display();
}
}
EXAMPLE:
class Box
{
double width;
double height;
double depth;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 38


Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len)
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mybox3 = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mybox3.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mybox3 is 343.0

3.Java Copy Constructor


A copy constructor is used for copying the values of one object to another object.
There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
1. By constructor
2. By assigning the values of one object into another
3. By clone() method of Object class

Example:To copy the values of one object into another using java copy constructor.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 39


class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}

Student(Student s) //copy constructor


{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[]){


Student s1 = new Student(111,"Bala");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Output:
111 Bala
111 Bala

COSTRUCTOR OVERLOADING

In Java, we can overload constructors like methods. The constructor overloading can be defined as
the concept of having more than one constructor with different parameters so that every constructor
can perform a different task.

Example:

Consider the following Java program, in which we have used different constructors in the class.

public class Student


{
//instance variables of the class
int id;
String name;
Student() // default constructor
{
System.out.println("this a default constructor");
}

Student(int i, String n) // parameterized constructor


{
id = i;
name = n;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 40


}
Student(Student s) //copy constructor
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(“ID=”+id);
System.out.println(NAME=”+name);
}
}

public static void main(String[] args)


{
//object creation
System.out.println("\nDefault Constructor values: \n");
Student s = new Student();
s.display():

System.out.println("\nParameterized Constructor values: \n");


Student s1 = new Student(10, "David");
s1.display();

Student s2 = new Student(s1);


S2.display();

}
}

The this Keyword


The keyword ‘this’: There will be situations where a method wants to refer to the objectwhich
invoked it. To perform this we use „this‟ keyword.
 There are no restrictions to use „this‟ keyword we can use this inside any method for
referring the current object.
 This keyword is always a reference to the object on which the method was invoked.
 We can use „this‟ keyword wherever a reference to an object of the current class type is
permitted. „this‟ is a key word that refers to present class object.
It refers to

1. Present class instance variables

2. Present class methods.

3. Present class constructor.

Program : Write a program to use „this‟ to refer the current class parameterized
constructor and current class instance variable.

//this demo

class Person

{
String name;

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 41


Person ( )

{
this (“Ravi Sekhar”); // calling present class parameterized constructor
this.display ( ); // calling present class method
}

Person (String name)

{
this.name = name; // assigning present class variable with parameter “name”
}

void display( )
{
System.out.println ("Person Name is = " + name);
}
}

class ThisDemo

{
public static void main(String args[])

{
Person p = new Person ( );
}
}
Example:2
class Student
{
int id;
String name;
Student(int id, String name)
{

this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);

}
public static void main(String args[])

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 42


{
Student stud1 = new Student(01,"Tarun");
Student stud2 = new Student(02,"Barun");

stud1.display();
stud2.display();
}
}

Output:
01 Tarun

02 Barun

Java – Methods
A Java method is a collection of statements that are grouped together to perform an operation.
 A method is a collection of statements that perform some specific task and return result to
the caller.
 A method can perform some specific task without returning anything.
 Methods are time savers and help us to reuse the code without retyping the code.
 Methods allow us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
1. Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 3 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
2. The return type : The data type of the value returned by the method ,or void if does not
return a value.
3. Method Name : the rules for variable names apply to method names as well, but the
convention is a little different.
4. Parameter list : Comma separated list of the input parameters are defined, If there are no
parameters, you must use empty parentheses ().
5. Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 43


Method signature: It consists of method name and parameter list (number of parameters, type of
the parameters and order of the parameters). Return type and exceptions are not considered as part
of it.
Method Signature of above function:

max(int x, int y)
Example:

// Program to illustrate methodsin java


import java.io.*;
class Addition
{
int sum = 0;
public int addTwoInt(int a, int b)
{
// adding two integer value.
sum = a + b;
//returning summation of two values.
return sum;
}

class addexample
{
public static void main (String[] args)
{
// creating an instance of Addition class
Addition add = new Addition();
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);
}
}
Output :

Sum of two integer values :3

Types of Java methods


Depending on whether a method is defined by the user, or available in standard library, there are two
types of methods:
1. Standard Library Methods(Built In Methods)
2. User-defined Methods

Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between
methods with different method signatures. This means that methods within a class can have the
same name if they have different parameter lists

 In the Java programming language, you can use the same name for all the drawing methods
but pass a different argument list to each method.
 Thus, the data drawing class might declare four methods named draw, each of which has a


 different parameter list.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 44


Program:

class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Method Overriding
• When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
• When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass.
Example:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 45


}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show();
subOb.show();
}
}
Output:
k: 3
K:3

10. Access specifiers


The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class.
There are 4 types of java access specifiers
1. private
2. default
3. protected
4. public
1) Private access specifiers
The private access specifiers is accessible only within classclass

EXAMPLE:
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
Role of Private Constructor
• If you make any class constructor private, you instance of that class from outside the class.
For example:

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 46


class A{
private A(){} //private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default access specifiers
• If you don't use any modifier, it is treated as default. The default modifier is accessible only
within package.
//save by A.java
package pack;
class A{
void msg()
{
System.out.println("Hello");
}
} //save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
3) Protected access specifiers
The protected access specifiers is accessible within package and outside the package but through
inheritance only.
• The protected access specifiers can be applied on the data member, method and constructor.
It can't be applied on the class.
//save by A.java
package pack;
public class A
{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:
Hello
4) Public Access Modifier

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 47


• The public access specifiers is accessible everywhere. It has the widest scope among all
other modifiers
Example:
//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello

11.Static members

Static is a non-access modifier in Java which is applicable for the following:


1. blocks
2. variables
3. methods

1.Static blocks
• If you need to do computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded.

Example:
class Test
{
static int a = 10;
static int b;
static {
System.out.println("Static block initialized.");

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 48


b = a * 4;
}
public static void main(String[] args)
{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40
2.Static variables
• When a variable is declared as static, then a single copy of variable is created and shared
among all objects at class level.
• Static variables are, essentially, global variables. All instances of the class share the same
static variable.
Example:
class demo
{
static int a = 3;
static int b;
static void display(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
display(42);
}
}
Output:
Static block initialized.
x = 42
a=3
b = 12

3.Static methods
• When a method is declared with static keyword, it is known as static method.
• When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.
• The most common example of a static method is main( ) method.
Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
Syntax:

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 49


classname.method( )
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Output:
a = 42
Differnce between Static and Non Ststic Members
1. Differnce between Static variable and Non Static Variable

Static variable Non static variable


Non static variables can be accessed using instance
Static variables can be accessed using class name
of a class
Static variables can be accessed by static and non Non static variables cannot be accessed inside a
static methods static method.
Static variables reduce the amount of memory used Non static variables do not reduce the amount of
by a program. memory used by a program
Static variables are shared among all instances of a Non static variables are specific to that instance of a
class. class.
Static variable is like a global variable and is Non static variable is like a local variable and they
available to all methods. can be accessed through only instance of a class.
2.. Differnce between Static Block and Non Static Block

Static Block Non-static block


1. A static block is a block of code which contains code 1.A non-static block executes when the object
that executes at class loading time. is created, before the constructor
2. A static keyword is prefixed before the start of the 2. There is no keyword prefix to make a block
block. non-static block,unlike static blocks.
3. All static variables can be accessed freely 3. All static and non-static fields can be access
4. Multiple static blocks would execute in the order freely
they are defined in the class. 4. Incase of multiple non-static blocks , the
5. All static blocks executes only once per classloader block executes the order in which it is
6. A typical static block looks like defined in the class
5. All non-static block executes everytime an
static{ object of the containing class is created.
// code for static block 6. A typical non-static block looks like below
}
{
// non static block
}

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 50


3... Differnce between Static Methods and Non Static Methods

Points Static method Non-static method


A static method is a method that belongs Every method in java defaults to a non-
to a class, but it does not belong to an static method without a static keyword
Definition instance of that class and this method can preceding it. non-static methods can access
be called without the instance or object of any static method and static variable also,
that class. without using the object of the class.
In the static method, the method can only In the non-static method, the method can
Accessing access only static data members and static access static data members and static
members and methods of another class or same class but methods as well as non-static members and
methods cannot access non-static methods and methods of another class or same class.
variables.
Binding The static method uses compile-time or The non-static method uses runtime or
process early binding. dynamic binding.
The static method cannot be overridden The non-static method can be overridden
Overriding
because of early binding. because of runtime binding.
In the static method, less memory is used
In the non-static method, much memory is
for execution because memory allocation
used for execution because here memory
Memory happens only once because the static
allocation happens when the method is
allocation keyword fixed a particular memory for that
invoked and the memory is allocated every
method in ram.
time when the method is called

12. Java Doc comments


Java comments

The Java language supports three types of comments –


Sr.No. Comment & Description

1 /* text */
The compiler ignores everything from /* to */.

2 //text
The compiler ignores everything from // to the end of the line.

3 /** documentation */
This is a documentation comment and in general its called doc comment.
The JDK javadoc tool uses doc comments when preparing automatically
generated documentation.

Java Doc comments


javadoc tool
The JDK contains a very useful tool, called javadoc, that generates HTML documentation from your
source files .

Following is a simple example where the lines inside /*….*/ are Java multi-line comments.
Similarly, the line which preceeds // is Java single-line comment.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 51


You can include required HTML tags inside the description part. For instance, the following
example makes use of <h1>....</h1> for heading and <p> has been used for creating paragraph
break −

Example
/**
* <h1>Hello, World!</h1>
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output.
* <p>
* Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
*/
public class HelloWorld
{

public static void main(String[] args)


{
System.out.println("Hello World!");
}

1.Comment Insertion
The javadoc utility extracts information for the following items:
1. Packages
2. Public classes and interfaces
3. Public and protected fields
4. Public and protected constructors and methods

i) Class Comments
The class comment must be placed after any import statements, directly before the class
definition.
ii) Method Comments
Each method comment must immediately precede the method that it describes. In addition to the
general-purpose tags, you can use the following tags:
• @param variable description
This tag adds an entry to the “parameters” section of the current method. The description can span
multiple lines and can use HTML tags. All @param tags for one method must be kept together.
• @return description
This tag adds a “returns” section to the current method. The description can span multiple lines and
can use HTML tags.
• @throws class description
iii) Field Comments
You only need to document public fields—generally that means static constants. For example:
/**
* The "Hearts" card suit
*/
public static final int HEARTS = 1;
iv) General Comments
The following tags can be used in class documentation comments:
• @author name
This tag makes an “author” entry. You can have multiple @author tags, one for each author.
• @version text
This tag makes a “version” entry. The text can be any description of the current version.
The following tags can be used in all documentation comments:
• @since text

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 52


This tag makes a “since” entry. The text can be any description of the version that introduced this
feature. For example, @since version 1.7.1
• @deprecated text
This tag adds a comment that the class, method, or variable should no longer be used. The text
should suggest a replacement. For example:
@deprecated Use <code>setVisible(true)</code> instead

V)Package and Overview Comments


You place the class, method, and variable comments directly into the Java source files, delimited
by /** . . . */ documentation comments. However, to generate package comments, you need to add a
separate file in each package directory. You have two choices:
1. Supply an HTML file named package.html. All text between the tags <body>...</body>is
extracted.
2. Supply a Java file named package-info.java. The file must contain an initial Javadoc
comment, delimited with /** and */, followed by a package statement. It should contain no
further code or comments.

CS3391-OBJECT ORIENTED PROGRAMMING UNIT1 53

You might also like