Object Oriented Programming(1&2)
Object Oriented Programming(1&2)
UNIT -1
Object-oriented programming (OOP) is at the core of Java. In fact, all Java
programs are to at least some extent object-oriented. OOP is so integral to Java that
it is best to understand its basic principles before you begin writing even simple
Java programs. Therefore, this chapter begins with a discussion of the theoretical
aspects of OOP.
Two Paradigms
All computer programs consist of two elements: code and data. Furthermore, a
program can be conceptually organized around its code or around its data. That is,
some programs are written around “what is happening” and others are written
around “who is being affected.” These are the two paradigms that govern how a
program is constructed. The first way is called the process-oriented model. This
approach characterizes a program as a series of linear steps (that is, code). The
process- oriented model can be thought of as code acting on data. Procedural
languages such as C employ this model to considerable success. However, as
mentioned in Chapter 1, problems with this approach appear as programs grow
larger and more complex.
To manage increasing complexity, the second approach, called object-oriented
programming, was conceived. Object-oriented programming organizes a program
around its data (that is, objects) and a set of well-defined interfaces to that data. An
object-oriented program can be characterized as data controlling access to code. As
you will see, by switching the controlling entity to data, you can achieve several
organizational benefits.
Abstraction
An essential element of object-oriented programming is abstraction. Humans
manage complexity through abstraction. For example, people do not think of a car
as a set of tens of thousands of individual parts. They think of it as a well-defined
object with its own unique behavior. This abstraction allows people to use a car to
drive to the grocery store without being overwhelmed by the complexity of the
individual parts. They can ignore the details of how the engine, transmission, and
braking systems work. Instead, they are free to utilize the object as a whole.
A powerful way to manage abstraction is through the use of hierarchical
classifications. This allows you to layer the semantics of complex systems,
breaking them into more manageable pieces. From the outside, the car is a single
object. Once inside, you see that the car consists of several subsystems: steering,
brakes, sound system, seat belts, heating, cellular phone, and so on. In turn, each of
JIMS EMTC
these subsystems is made up of more specialized units. For instance, the sound
system might consist of a radio, a CD player, and/or MP3 player. The point is that
you manage the complexity of the car (or any other complex system) through the
use of hierarchical abstractions.
Hierarchical abstractions of complex systems can also be applied to computer
programs. The data from a traditional process-oriented program can be transformed
by abstraction into its component objects. A sequence of process steps can become
a collection of messages between these objects. Thus, each of these objects
describes its own unique behavior. You can treat these objects as concrete entities
that respond to messages telling them to do something. This is the essence of
object-oriented Programming.
EX. class Geeks {
public static void main(String[] args)
{
System.out.println("I am AIML");
}
}
OUTPUT:
I am AIML
OOPs Concepts:
● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding
1. Class:
A class is a user-defined data type. It consists of data members and member
functions, which can be accessed and used by creating an instance of that class. It
represents the set of properties or methods that are common to all objects of one
type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of
JIMS EMTC
them will have 4 wheels, Speed Limit, Mileage range, etc. So here, cars are the
class, and wheels, speed limits, mileage are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents real-life entities.
An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is allocated.
An object has an identity, state, and behavior. Each object contains data and code
to manipulate the 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 type
of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color,
Breed, Bark, Sleep, and Eats.
Object
Example:
public class Main {
int x = 5;
3. Data Abstraction:
JIMS EMTC
Data abstraction is one of the most essential and important features of object-
oriented programming. Data abstraction refers to providing only essential
information about the data to the outside world, hiding the background details or
implementation. Consider a real-life example of a man driving a car. The man only
knows that pressing the accelerators will increase the speed of the car or applying
brakes will stop the car, but he does not know about how on pressing the
accelerator the speed is increasing, he does not know about the inner mechanism of
the car or the implementation of the accelerator, brakes, etc in the car. This is what
abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. In Encapsulation,
the variables or data of a class are hidden from any other class and can be accessed
only through any member function of their class in which they are declared. As in
encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
and then request him to give the particular data. This is what encapsulation is. Here
the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The
capability of a class to derive properties and characteristics from another class is
called Inheritance. When we write a class, we inherit properties from other classes.
JIMS EMTC
So when we create a class, we do not need to write all the properties and functions
again and again, as these can be inherited from another class that possesses it.
Inheritance allows the user to reuse the code whenever possible and reduce its
redundancy.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
JIMS EMTC
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one
form. For example, A person at the same time can have different characteristics.
Like a man at the same time is a father, a husband, an employee. So the same
person possesses different behavior in different situations. This is called
polymorphism.
Parent.Java:
class Parent {
void v1() //Declaring function
{
System.out.println("Inside the Parent Class");
}
}
JIMS EMTC
Child.java:
7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is
decided at runtime. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. Dynamic Method
Binding One of the main advantages of inheritance is that some derived class D
has all the members of its base class B. Once D is not hiding any of the public
members of B, then an object of D can represent B in any context where a B could
be used. This feature is known as subtype polymorphism.
● When the type of the object is determined at run-time, it is known as
dynamic binding.
a.eat();
}
}
Benefits of OOP
● We can build the programs from standard working modules that
communicate with one another, rather than having to start writing the
code from scratch which leads to saving of development time and higher
productivity,
● OOP language allows to break the program into bit-sized problems that
can be solved easily (one object at a time).
● The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost.
● OOP systems can be easily upgraded from small to large systems.
● It is possible that multiple instances of objects co-exist without any
interference,
● It is very easy to partition the work in a project based on objects.
● It is possible to map the objects in the problem domain to those in the
program.
● The principle of data hiding helps the programmer to build secure
programs which cannot be invaded by the code in other parts of the
program.
● By using inheritance, we can eliminate redundant code and extend the
use of existing classes.
● Message passing techniques is used for communication between objects
which makes the interface descriptions with external systems much
simpler.
● The data-centered design approach enables us to capture more details of
model in an implementable form.
Introduction to Java
JIMS EMTC
Java is known for its simplicity, robustness, and security features, making it a
popular choice for enterprise-level applications. Java applications are compiled to
byte code that can run on any Java Virtual Machine. The syntax of Java is similar
to C/C++.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs.
Key Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the
bytecode generated by the compiler. This byte code can run on any platform be it
Windows, Linux, or macOS which means if we compile a program on Windows,
then we can run it on Linux and vice versa. Each operating system has a different
JVM, but the output produced by all the OS is the same after the execution of the
byte code. That is why we call java a platform-independent language.
2. Object-Oriented Programming
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C+
+. It eliminates complex features like pointers and multiple inheritances, making it
easier to write, debug, and maintain code.
4. Robustness
Java language is robust which means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not easy to detect by another
programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation.
5. Security
6. Distributed
7. Multithreading
8. Portability
JIMS EMTC
As we know, java code written on one machine can be run on another machine.
The platform-independent feature of java in which its platform-independent
bytecode can be taken to any platform for execution makes java portable.
WORA(Write Once Run Anywhere) makes java application to generates a ‘.class’
file that corresponds to our applications(program) but contains code in 0binary
format. It provides ease t architecture-neutral ease as bytecode is not dependent on
any machine architecture. It is the primary reason java is used in the enterprising
IT industry globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during the
runtime and at some times java uses Just In Time (JIT) compiler where the
compiler compiles code on-demand basis where it only compiles those methods
that are called making applications to execute faster.
How Java Code Executes?
The execution of a Java application code involves three main steps:
The Java compiler (javac) converts the source code into bytecode, which is stored
in a .class file. This bytecode is platform-independent and can be executed on any
machine with a JVM.
The JVM executes the compiled bytecode, translating it into machine code specific
to the operating system and hardware.
Example Program:
System.out.println("Hello, World!");
Characteristics of java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are also
some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
JIMS EMTC
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
The sandbox model aims to strike a balance between the ability to run untrusted
code and maintaining system security. It's especially important in scenarios where
users interact with content from untrusted sources, such as web browsers running
Java applets.
Access Control Lists (ACLs): The security manager uses access control lists to
define what actions or resources are allowed or denied. Developers can configure
these ACLs to specify fine-grained security policies.
3. Restricted Actions:
Within the sandbox, certain actions are typically restricted or prohibited. These
actions may include:
4. Permission Model:
In Java, permissions are used to grant or deny specific actions to code running in
the sandbox. Permissions are organized into permission classes, each representing
a specific type of action, such as file access, network access, or reflection.
JIMS EMTC
5. Code Signing:
6. Applet Security:
Historically, Java applets were a common use case for the sandbox model. Applets
were small Java applications embedded within web pages. They ran in a restricted
environment, ensuring that they couldn't harm the user's computer. However, due
to security concerns, many modern web browsers have deprecated or removed
support for Java applets.
7. Evolving Security:
● The essence of the sandbox model is that local code is trusted to have full
access to vital system resources (such as the file system) while
downloaded remote code (an applet) is not trusted and can access only
the limited resources provided inside the sandbox.
● A sandbox typically provides a tightly controlled set of resources for guest
programs to run in, such as limited space on disk and memory.
class AreaOfCircle
double r= s.nextDouble();
double area=(22*r*r)/7 ;
class Factorial
int n=5,fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
System.out.println("factorial="+fact);
int i;
JIMS EMTC
int n=sc.nextInt();
double avg=0;
System.out.println("Enter marks");
for( i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
for( i=0;i<n;i++)
{
avg=avg+a[i];
}
System.out.print("Average of (");
for(i=0;i<n-1;i++)
{
System.out.print(a[i]+",");
}
System.out.println(a[i]+") ="+avg/n);
}
}
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(int i=0;i<n;i++)
result=result+a[i];
System.out.println("average of
("+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+") is ="+result/n);
}
}
// Main class
class GFG {
// via remainder
if (num % 2 == 0) {
else {
import java.util.Scanner;
class ArmstrongWhile
{
public static void main(String[] arg)
{
int i=100,arm;
System.out.println("Armstrong numbers between 100 to 999");
while(i<1000)
{
arm=armstrongOrNot(i);
if(arm==i)
System.out.println(i);
i++;
}
}
static int armstrongOrNot(int num)
{
int x,a=0;
JIMS EMTC
while(num!=0)
{
x=num%10;
a=a+(x*x*x);
num/=10 ;
}
return a;
}
}
UNIT-2
Data types in Java are of different sizes and values that can be
stored in the variable that is made as per convenience and
circumstances to cover up all test cases. Java has two categories in
which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float,
and double. The Boolean with uppercase B is a wrapper class for the
primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
class GFG
{
public static void main (String[] args)
{
// declaring two int variables
int a = 10;
int b = 20;
System.out.println( a + b );
}
}
JIMS EMTC
The boolean data type represents a logical value that can be either true or false.
Conceptually, it represents a single bit of information, but the actual size used by
the virtual machine is implementation-dependent and typically at least one byte
(eight bits) in practice. Values of the boolean type are not implicitly or explicitly
converted to any other type using casts. However, programmers can write
conversion code if needed.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
The byte data type is an 8-bit signed two’s complement integer. The byte data type
is useful for saving memory in large arrays.
Syntax:
JIMS EMTC
byte byteVar;
Size : 1 byte (8 bits)-
The short data type is a 16-bit signed two’s complement integer. Similar to byte, a
short is used when memory savings matter, especially in large arrays where space
is constrained.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
The long data type is a 64-bit signed two’s complement integer. It is used when an
int is not large enough to hold a value, offering a much broader range.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point
numbers. The size of the float data type is 4 bytes (32 bits).
Syntax:
JIMS EMTC
float floatVar;
Size : 4 bytes (32 bits)
The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice. The size of the
double data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)
Note: Both float and double data types were designed especially for scientific
calculations, where approximation errors are acceptable. If accuracy is the most
prior concern then, it is recommended not to use these data types and use
BigDecimal class instead.
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16
bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Non-Primitive (Reference) Data Types
1. Strings
Literal: Any constant value which can be assigned to the variable is called
literal/constant.
// Here 100 is a constant/literal.
int x = 100;
Floating-Point literal
For Floating-point data types, we can specify literals in only decimal form, and we
cant specify in octal and Hexadecimal forms.
Decimal literals(Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;
Char literals
specified either in Decimal, Octal, and Hexadecimal forms. But the allowed range
is 0 to 65535.
char ch = 062;
Unicode Representation: We can specify char literals in Unicode representation ‘\
uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represents a.
Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';
String literals