Unit 1 Oopj
Unit 1 Oopj
1. Herbert Schilt, “JAVA Complete Reference”, Tata McGraw Hill, (9 th Edition), (2014)
2. Eckel B., "Thinking in Java", Pearson Education, (3 rd Edition)
Reference Books:
1. Kathy Sierra & Bert Bates, “Head First Java”, Oreilly publication,(2 nd Edition) (2009)
2. Barry Burd “Beginning Programming with Java for Dummies”, Oreilly publication, (5 th Edition)
(2017)
3. Paul Deital and Harvey Deital,”Java How to program”, Prentice Hall Publication,(9 th Edition)
(2011)
Unit-I : Introduction to Object Oriented Paradigm in Java
1. Object - This is the basic unit of object-oriented programming. That is both data and function that
operate on data are bundled as a unit called an object.
2. Class - When you define a class, you define a blueprint for an object. This doesn't actually define
any data, but it does define what the class name means, that is, what an object of the class will
consist of and what operations can be performed on such an object.
Need for Object Oriented Paradigm (OOP):
➢ the data is protected because it can be altered only by the encapsulated methods.
➢ it is more efficient to write programs which use predefined objects.
➢ the storage structure and/or procedures within an object type could be altered if required
without affecting programs that make use of that object type.
➢ new functions can easily be added to objects by using inheritance
➢ the code produced is likely to contain fewer errors because pretested objects are being
used.
➢ less maintenance effort will be required by the developer because objects can be reused.
5. Polymorphism is the ability of an inherited class to customize an inherited method. Two
different classes may inherit a particular method from a common parent, but they may redefine
it in different ways.
OOP Concepts
Basic concept of Object Oriented Paradigm (OOP):
1. Encapsulation
Encapsulation in Java is a mechanism for wrapping the data (variables) and
code acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes and can be accessed only
through the methods of their current class. Therefore, it is also known as data
hiding. In Java, to achieve encapsulation −
a. Declare the variables of a class as private.
b. Provide public setter and getter methods to modify and view the variables
values.
Basic concept of Object Oriented Paradigm (OOP):
2. Abstraction
Abstraction is a process of hiding the implementation details from the user, only
the functionality will be provided to the user. In other words, the user will have
the information on what the object does instead of how it does it. In Java,
abstraction is achieved using Abstract classes and interfaces.
3. Inheritance
Inheritance can be defined as the process where one (parent/super) class
acquires the properties (methods and fields) of another (child/sub). With the use
of inheritance, the information is made manageable in a hierarchical order.
Basic concept of Object Oriented Paradigm (OOP):
4. Polymorphism
Polymorphism is the ability of an object to perform different actions (or, exhibit different
behaviors) based on the context.
Benefits of Object Oriented Paradigm (OOP):
➢ The programs are modularized based on the principles of classes and objects. Linking code and object allows
related objects to share common code. This reduces code duplication and code reusability.
➢ Creation and implementation of OOP code is easy and reduces software development time.
➢ The concept of data abstraction separates object specification and object implementation.
➢ Data encapsulated along with functions. Therefore external non- member function cannot access or modify
data, thus proving data security.
➢ Easier to develop complex software, because complexity can be minimized through inheritance.
➢ OOP can communicate through message passing which makes interface description with outside system very
simple
Drawbacks of Object Oriented Paradigm (OOP):
➢ The objects can be made user defined data types with the help of a class.
➢ A class is a collection of objects that have identical properties, common
behavior and shared relationship.
➢ Once class is defined, any number of objects of that class is created.
➢ Classes are user defined data types.
➢ A class can hold both data and functions.
➢ For example: class solar system consists of members or objects - planets,
sun, moon.
Class:
What is Java?
Java is an object oriented, simple, distributed, interpreted, robust, architecture
neutral, portable, high performance, multithreaded, dynamic, powerful and
versatile programming language originally developed by Sun Microsystems and
released in 1995 for developing software running on the mobile device, desktop
computer, and server.
History
● James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. initiated the Java language project in
June 1991.
● Java was originally designed used to create software to be embedded in
various consumer electronic devices, such as microwave ovens and remote
controls.
● This language was initially called “Oak,” but was renamed “Java” in 1995.
Version till date:
Java 8 is free officially supported. Major release versions of Java, along with their release
dates:
● JDK 1.0 (January 23, 1996)[38]
● JDK 1.1 (February 19, 1997)
● J2SE 1.2 (December 8, 1998)
● J2SE 1.3 (May 8, 2000)
● J2SE 1.4 (February 6, 2002)
● J2SE 5.0 (September 30, 2004)
● Java SE 6 (December 11, 2006)
● Java SE 7 (July 28, 2011)
● Java SE 8 (LTS) (March 18, 2014)
● Java SE 9 (September 2017)
● Java SE 10 (March 2018)
● Java SE 11 (LTS) (September 2018)
● Java SE 12 (March 2019)
● C -> C++ -> Java
● Java derives its syntax - > C
● Java's OO features -> C++
● C:
○ First powerful, efficient, structured language that was relatively easy to learn.
○ Programmer's language
○ Java inherited this legacy..!!
Features of java
Features of Java
● Simple
○ If you already understand the basic concepts of object-oriented
programming, learning Java will be even easier.
○ It inherits the syntax from C/C++ and many object-oriented features of C++.
● Object-Oriented
○ All programs in java are based on objects.
○ Object model in Java is simple and easy to extend.
○ Supports Encapsulation, Inheritance, Polymorphism, Dynamic Binding.
Features of Java
● Robust
○ Java is a strictly typed language, it checks your code at compile
time. However it also checks your code at run-time.
○ Two of the main reasons for program failure:
■ memory management mistakes
■ mishandled exceptional conditions
○ Java virtually eliminates these problems by managing memory
allocation and deallocation (Garbage Collection Mechanism).
○ Java helps in this area by providing object-oriented exception
handling.
Features of Java
● Multithreaded
○ Java was designed to meet the real-world requirement of
creating interactive, networked programs.
○ To accomplish this, Java supports multithreaded programming,
which allows you to write programs that do many things
simultaneously.
● Architecture-Neutral and Portable
○ Before Java, central issue was of code longevity and
portability.
○ Operating system upgrades, processor upgrades, and changes
in core system resources all combined to make a program
Features:
● Interpreted and High Performance
○ Java enables the creation of cross-platform programs by compiling into
an intermediate representation called Java bytecode.
○ This code can be executed on any system that implements the Java
Virtual Machine.
○ The Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by
using a just-in-time compiler.
● Distributed
○ Java is designed for the distributed environment of the Internet because
it handles TCP/IP protocols.
○ Java also supports Remote Method Invocation (RMI). This feature
enables a program to invoke methods across a network.
Features:
● Dynamic
○ Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run
time.
○ This makes it possible to dynamically link code in a safe and expedient
manner.
○ This is crucial to the robustness of the Java environment, in which small
fragments of byte-code may be dynamically updated on a running system.
● Secure
○ Java does not use memory pointers explicitly
○ All programs are executed under Sand Box.
○ It uses public key encryption system to allow the java application to transmit
over the Internet.
Java and Internet
● Java Applets - An applet is a special kind of program that is transmitted over the Internet and automatically
executed by the Java-compatible web browser. Applets are usually small programs and these helped in
moving some user interactive programs from server to client, hence improving the usability of the web
application. The typical examples of applets are tax calculator or some forms with input fields having lots of
interaction between them.
● Security - Since applets are automatically downloaded and run on the client machine, there are restrictions
on what can be done in Applets. They can use only a subset of all the functions supported by Java. e.g., They
can not access local file system or they can not launch other programs on the client system. Java achieved
this protection by restricting an applet to Java execution environment and not allowing it access to other
parts of the computer.
● Portability - Since Internet is comprised of many different types of computers and operating systems, it is
important for the programs to run on all these systems. Either we have to have a separate program for every
operating system or write a portable (or platform independent) program like Java Applet which runs
everywhere. This portability is achieved by using Bytecode In Java
Java Translation
1. The Java compiler translates Java source code into a special
representation called bytecode
2. Java bytecode is not the machine language for any traditional CPU
3. Another software tool, called an interpreter, translates bytecode into
machine language and executes it
4. Therefore the Java compiler is not tied to any particular machine
class Simple{
System.out.println("Hello World!");
}
Hello (standalone)
Note that String is built in
Main is method of the class..
All the program enclosed into the class..Hello
println is a member function for the System.out class
Command Line Argument
● Java command-line argument is an argument i.e. passed at the time of running the java
program.
● The arguments passed from the console can be received in the java program and it can be
used as an input.
● So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass
at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
____________________________________________________________________
Output: Your first argument is: sonoo
Java Programming elements:
● Data types
● Arrays
● Control Structures
● Class
● Object
● Method
● constructor
● Encapsulation
● Abstraction and Polymorphism
Java Programming elements:
1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Java Programming elements:
1. Data types
2. Arrays
3. Control Structures
4. Class 1 Primitive types
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Data Types
A set of values together with a set of operations.
Primitive Data Types
1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Arrays
1. Java array is an object which contains elements of a similar data type.
2. The elements of an array are stored in a contiguous memory location
3. fixed set of elements in a Java array
Arrays
Advantages
1. Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
2. Random access: We can get any data located at an index position.
Disadvantages
1. 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.
Arrays
Types of Array in java
1. Single Dimensional Array 2. Multidimensional Array
Operations on Array in Java
1. Array Declaration
2. Access the Elements of an Array
3. Array Length
4. Passing array to a method
5. Returning array from a method
6. Array of object
Arrays Declaration
An array declaration has two components: the type and the name.
In C Programming language you have used sizeof( ), but in java you have in-build function
Examples:
Or ClassName[] objArray;
Or ClassName objeArray[];
Example:
Employee department1[20];
Employee department2[20];
Employee department3[20];
Java Programming elements:
1. Data types 1 if
1. Data types
2. Arrays
2. Arrays 2 switch
3. Control Structures
3. Control Structures
4. Class
4. Encapsulation 3 for
5. Object
5. Abstraction and
6. Method 4 while
Polymorphism
7. constructor
6.
8.
Class
Encapsulation
5 do-while
7. object
9. Abstraction and
8. constructor
Polymorphism
Control Statements are like C
3. Nested if statement
Control Structure
1. if
2. switch
3. for
4. while
5. do-while
if condition
Syntax: Example:
{ {
} }
if-else condition
Syntax:
Example:
if (condition)
if (20 > 18)
{
{
// block of code to be executed if the condition is
true System.out.println("20 is greater than 18");
}
}
else
Else{
{
System.out.println("20 is smaller than 18");
// block of code to be executed if the condition
is false }
}
switch statement
Syntax: Example :
switch (n + 1) {
case 0: m = n - 1; break; switch(expression) { int day = 4;
case 1: m = n + 1; break; case x: switch (day) {
case 3: m = m * n; break;
default: m = -n; break; // code block
case 1:
} break;
System.out.println("Monday");
case y:
break;
// code block
case 2:
break;
default: System.out.println("Tuesday");
} }
for loop
Syntax:
for (statement 1; statement 2; statement 3) Example:
{
for (int i = 0; i < 5; i++)
// code block to be executed
{
}
System.out.println(i);
Statement 1: initialization
}
Statement 2: condition
Syntax: Example:
int i = 0;
while (condition)
while (i < 5)
{
{
// code block to be executed System.out.println(i);
} i++;
}
do-while loop
Example:
Syntax:
do { int i = 0;
} System.out.println(i);
1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
A typical Java file looks like:
import java.lang.*;
import java.util.*;
public class SomethingOrOther {
// object definitions go here
. . .
}
This must be in a file named SomethingOrOther.java !
Class
1. The class is at the core of Java.
2. It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.
3. Any concept you wish to implement in a Java program must be
encapsulated within a class.
4. While defining a class, you declare its exact form and nature, by
specifying the data that it contains and the code that operates on that
data.
5. While very simple classes may contain only code or only data, most
real-world classes contain both.
Class (cont.)
class classname
{
1. A class is declared by use of the class type instance-variable1;
type instance-variable2;
keyword. // …………
type instance-variableN;
2. The data, or variables, defined within a
class are called instance variables. type methodname1(parameter-list)
{
3. The code is contained within methods. // body of method
}
4. Collectively, the methods and variables type methodname2(parameter-list)
defined within a class are called {
// body of method
members of the class. }
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Class deceleration
Example:
Syntax
class Student
class class_name
{
{
int roll;
Attribute declaration;
char name;;
//data members
//data members
Function declaration;
int getdata();
// member function
void marks();
} // member function
}
Class
1. A class consists of a collection of fields, or variables, very
much like the named fields of a struct all the operations (called
methods) that can be performed on those fields
1. Data types
2. Arrays
3. Control Structures
4. Class
5. Method
6. object
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Declaring Object in Java
1. When you create a class, you are creating a new data type. You can
use this type to declare objects of that type.
2. Obtaining objects of a class is a two-step process:
a. First, you must declare a variable of the class type.
i. This variable does not define an object.
ii. Instead, it is simply a variable that can refer to an object.
b. Second, you must acquire an actual, physical copy of the object
and assign it to that variable.
i. This is achieved using the new operator.
Declaring Object in Java
1. The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it.
2. This reference is, more or less, the address in memory of the object
allocated by new.
3. This reference is then stored in the variable.
Box mybox = new Box();
1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Methods
1. Syntax:
type name(parameter-list)
{
// body of method
}
2. type specifies the type of data returned by the method.
a. This can be any valid type, including class types that you create.
b. If the method does not return a value, its return type must be
void.
Methods
1. The name of the method is specified by name.
a. This can be any legal identifier other than those already used by
other items within the current scope.
2. The parameter-list is a sequence of type and identifier pairs
separated by commas.
a. Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called.
b. If the method has no parameters, then the parameter list will be
empty.
Methods
1. Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:
2. return value;
a. Here, value is the value returned.
Adding Methods
Adding Methods
Output:
Volume is 3000.0
Volume is 162.0
Adding Methods
1. Inside the volume( ) method: the instance variables width, height, and
depth are referred to directly, without preceding them with an object
name or the dot operator.
2. When a method uses an instance variable that is defined by its class, it
does so directly, without explicit reference to an object and without use of
the dot operator.
3. A method is always invoked relative to some object of its class.
4. Once this invocation has occurred, the object is known.
5. Thus, within a method, there is no need to specify the object a second
time.
6. This means that width, height, and depth inside volume( ) implicitly refer
to the copies of those variables found in the object that invokes volume( )
.
Returning a Value
Returning
a Value
Example
public class example {
class Rect { public static void main(String[]
int len; args) {
int bth; Rect r = new Rect();
int area() { r.len = 5;
int y; r.bth = 2;
y = len * bth; int x;
x = r.area();
return y;
System.out.println("Area of
} rectangle is: " + x);
} }
}
Method with Parameter
1. Parameters allow a method to be generalized.
2. That is, a parameterized method can operate on a variety of
data and/or be used in a number of slightly different situations.
1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Constructors
● A constructor is a block of codes similar to the method.
● Java constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as constructor
● At the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of method which is used to initialize the internal
state of the object.
● Every time an object is created using the new() keyword, at least one
constructor is called.
Constructors
● It has the same name as the class in which it resides and is syntactically similar
to a method.
● Once defined, the constructor is automatically called when the object is created,
before the new operator completes.
● Constructors have no return type, not even void.
● This is because the implicit return type of a class’ constructor is the class type
itself.
● It is the constructor’s job to initialize the internal state of an object so that the
code creating an instance will have a fully initialized, usable object immediately.
Example with method
Types of constructors
2. Parameterized constructor
Java Default Constructor
}
Output:
Bike is created
If there is no constructor in a class, compiler automatically creates a
default constructor. Default constructor provides the default values to
the object which are zero, null, and false, for numeric types,
reference types, and boolean, respectively.
class Student{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1=new Student();
s1.display();
}
}
Output: 0 null
Example with constructor:
Parameterized constructor