OOPs Using Java Notes UNIT-1 (1)
OOPs Using Java Notes UNIT-1 (1)
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his team changed
the name from Oak to Java.
Java Example
class Abc
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Application Of Java
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.
3) Enterprise Application
4) Mobile Application
It is used to develop rich internet applications. It uses a lightweight user interface API.
History of Java
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at
the time. The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital devices
such as set-top boxes, televisions, etc. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is
known as the father of Java, in 1995. James Gosling and his team members started the
project in the early '90s.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2) 2) Initially it was designed for small, embedded systems in electronic appliances
like set-top boxes.
3) 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was
.gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Why had they chose the name Java for Java language? The team gathered to choose
a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA",
etc. They wanted something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since
Java was so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee).
It is a kind of espresso bean. Java name was chosen by James Gosling while having a
cup of coffee nearby his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have
been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java.
Features 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.
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
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
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 a virtual machine sandbox
Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
Distributed
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.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.
Compilation Flow
When we compile Java program using javac tool, the Java compiler converts the source
code into byte code.
What happens at runtime?
Bytecode Verifier: Checks the code fragments for illegal code that
can violate access rights to objects.
Ques.1 Can you save a Java source file by another name than the
class name?
Yes, if the class is not public. It is explained in the figure given below:
Fundam
entals of
Object
Oriented
Programming – Procedure Oriented Programming Vs. Object Oriented
Programming (OOP)
Object-oriented Programming is a
programming language that uses classes
and objects to create models based on
the real world environment. These objects
contain data in the form of attributes and
program codes in the form of methods or
functions. In OOP, the computer programs
are designed by using the concept of
objects that can interact with the real
world entities.
10. Importance It gives importance to functions over data. It gives importance to data over
functions.
1. Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student named
Ravi is an object.
Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.
Data member
Method
Constructor
Nested Class
Interface
class Student {
int id;
String name;
System.out.println(s1.name);
RESULT:
NULL
class Student {
int id=5;
String name=”Ravi”;
System.out.println(s1.id);
System.out.println(s1.name);
RESULT:
Ravi
2. Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-
life entities. Objects are the instances of a class that are created to use the attributes
and methods of a class. A typical Java program creates many objects, which as you
know, interact by invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Class Object
Class is the blueprint of an object. It is An object is an instance of the class.
used to create objects.
No memory is allocated when a class is Memory is allocated as soon as an object
declared. is created.
A class is a group of similar objects. An object is a real-world entity such as a
book, car, etc.
Class is a logical entity. An object is a physical entity.
A class can only be declared once. Objects can be created many times as per
requirement.
An example of class can be a car. Objects of the class car can be BMW,
Mercedes, Ferrari, etc.
Example
int x=5;
int y=3;
2. Accessing Attributes
We can access attributes by creating an object of the class, and by using the dot syntax
(.):
The following example will create an object of the Main class, with the name myObj. We
use the x attribute on the object to print its value:
int x = 5;
System.out.println(myObj.x);
3. Modify Attributes
int x;
myObj.x = 40;
System.out.println(myObj.x);
}
}
int x = 10;
System.out.println(myObj.x);
If you don't want the ability to override existing values, declare the
attribute as “final”:
System.out.println(myObj.x);
The final keyword is useful when you want a variable to always store the same value.
4. Multiple Objects
If we create multiple objects of one class, we can change the attribute values in one
object, without affecting the attribute values in the other:
public class Main {
int x = 5;
myObj2.x = 25;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
Result:
5
25
5. Multiple Attributes
We can specify as many attributes as we want:
}
Result:
4. Object Reference
When we create an object with new, the computer creates the object in the
program and then gives us some information about where the object is located.
That location information is what gets stored in the object variable. This is
illustated in the picture below, which shows the object itself as an entity that
exists separate from the variable “a”. The variable a stores information about
where the object is located, which is shown in the picture as an arrow running
from the variable a to the object itself.
Object variables in Java are sometimes referred to as object reference variables,
because their purpose is to refer or point you to the actual object.
Reference variables offer several benefits and play a crucial role in Java programming:
It's important to note that reference variables are distinct from primitive variables in
Java. Primitive variables directly hold the actual values (e.g., int, boolean, etc.) rather
than references to objects.
Example:
import java.io.*;
class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}
class Main {
public static void main(String[] args)
{
Demo D1 = new Demo();
System.out.println(D1);
System.out.println(D1.display());
}
}
Output:
Demo@214c265e
x = 10
0
import java.io.*;
class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}
class Main {
public static void main(String[] args)
{
Demo D1 = new Demo();
Demo G1 = D1;
Demo Q1 = M1;
G1.x = 25;
System.out.println(G1.x);
System.out.println(D1.x);
}
}
Output:
25
25
import java.io.*;
class Demo {
int x = 10;
int y = 20;
return 0;
}
}
class Main {
public static void main(String[] args)
{
Demo C = new Demo();
D.y = 55;
C.display(C, D);
D.display(C, D);
}
}
Output:
x = 95
y = 20
x = 10
y = 55
import java.io.*;
class Demo {
C.Swap(C, D);
}
}
Output:
??
??
1. Java Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to the
user.
Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the subclass (inherited from).
Note: To access the abstract class, it must be inherited from another class.
Example:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Output:
Zzz
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the method.
Java Interface
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
interface Animal{
Note:To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface method is
provided by the "implement" class.
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
Note:
Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not
possible to create an "Animal" object in the MyMainClass).
Interface methods do not have a body - the body is provided by the "implement" class.
On implementation of an interface, you must override all of its methods.
Interface methods are by default abstract and public.
Interface attributes are by default public, static and final.
An interface cannot contain a constructor (as it cannot be used to create objects).
2. Java Encapsulation
Encapsulation is a concept in Java that binds together the data and the methods that manipulate
that data, and keeps both safe from outside interference and misuse. In other words, it's a way to
hide the implementation details of an object from the outside world and only expose the necessary
3. Java Polymorphism
Polymorphism is a concept in Java that allows objects of different classes to be treated
as objects of a common superclass. This means that objects of different classes can be
used interchangeably, as long as they share a common interface or superclass.
Polymorphism allows for more flexibility and generic code, making it easier to write programs that
can work with different types of objects.
public class Animal {
public void sound() {
System.out.println("The animal makes a sound");
}
}
animal.sound();
dog.sound();
cat.sound();
}
}
4. Java Inheritance
Inheritance is a mechanism in Java that allows one class to inherit the properties and behavior
of another class. The class that is being inherited from is called the superclass or parent class,
and the class that is doing the inheriting is called the subclass or child class.
Super Class:
A super class is a class that is being inherited from. It provides the common attributes and methods
Sub Class:
A sub class is a class that inherits from a super class. It inherits all the attributes and methods of the
super class and can also add new attributes and methods or override the ones inherited from the
super class.
// Super class
class Animal {
void sound() {
// Sub class
void sound() {
Overriding:
Overriding is a mechanism in Java that allows a sub class to provide a specific implementation for a
method that is already defined in its super class. The method in the sub class has the same name,
return type, and parameter list as the method in the super class, but it can have a different
implementation.
// Super class
class Shape {
void draw() {
System.out.println("Drawing a shape");
// Sub class
void draw() {
System.out.println("Drawing a circle");
Overloading:
Overloading is a mechanism in Java that allows multiple methods with the same name to be defined, as
long as they have different parameter lists. This allows for more flexibility in method calls, as the correct
method to call can be determined based on the number and types of arguments passed.
class Calculator {
int add(int a, int b) {
return a + b;
}
Defining Package:
In Java, a package is a way to group related classes and interfaces together. A package is defined using
the package keyword followed by the name of the package.
This defines a package named com.example.myapp. All classes and interfaces in this file will be part of
this package.
CLASSPATH Setting for Packages:
The CLASSPATH environment variable tells Java where to find the classes and packages. To use a package,
you need to set the CLASSPATH to include the directory where the package is located.
For example, if you have a package com.example.myapp in a directory C:\MyApp, you would set
the CLASSPATH as follows:
set CLASSPATH=C:\MyApp
Alternatively, you can use the -cp or -classpath option when compiling or running your Java program:
javac -cp C:\MyApp MyProgram.java
java -cp C:\MyApp MyProgram
A JAR (Java Archive) file is a way to package multiple classes and resources into a single file. To create a JAR
file, you can use the jar command:
This creates a JAR file named myapp.jar that contains all the classes in the com.example.myapp package.
To use a JAR file, you need to add it to the CLASSPATH. For example:
set CLASSPATH=C:\MyApp\myapp.jar
To use a class or interface from a package, you need to import it using the import statement. For example:
import com.example.myapp.MyClass;
You can also use static import to import static members of a class. For example:
This imports the MY_CONSTANT static variable from the MyClass class.
Naming Convention for Packages:
The naming convention for packages is to use a reverse domain name format, such
as com.example.myapp. This helps to avoid naming conflicts and makes it easier to identify the origin of
the package.
By following these conventions, you can create packages that are easy to use and maintain.