0% found this document useful (0 votes)
5 views44 pages

OOP Unit1

The document provides an introduction to Java, detailing its lineage from C and C++, the motivations for its creation, and its key features such as portability, security, and object-oriented programming principles. It discusses Java's architecture, including the use of bytecode and the Java Virtual Machine (JVM), as well as fundamental concepts like classes, encapsulation, inheritance, and polymorphism. Additionally, it covers practical aspects of Java programming, including data types, arrays, and garbage collection.

Uploaded by

agrawalmilan08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

OOP Unit1

The document provides an introduction to Java, detailing its lineage from C and C++, the motivations for its creation, and its key features such as portability, security, and object-oriented programming principles. It discusses Java's architecture, including the use of bytecode and the Java Virtual Machine (JVM), as well as fundamental concepts like classes, encapsulation, inheritance, and polymorphism. Additionally, it covers practical aspects of Java programming, including data types, arrays, and garbage collection.

Uploaded by

agrawalmilan08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

INTRODUCTION TO JAVA

Prof. Lavanya Naik


Dept of Data Science

Data Science 2023-2024


Java’s Lineage

• Java is related to C++, which is a direct descendant of C.


• Much of the character of Java is inherited from these two languages.
• From C, Java derives its syntax.
• Many of Java’s object-oriented features were influenced by C++.

Data Science 2023-2024


The Birth of Modern Programming: C

• The C language shook the computer world.


• When a computer language is designed, trade-offs are often made, such as the following:
a. Ease-of-use versus power
b. Safety versus efficiency
c. Rigidity versus extensibility
• Invented and first implemented by Dennis Ritchie C in the 1970s.
• C was formally standardized in December 1989, when the American National Standards
Institute (ANSI) standard for C was adopted.
• C is a language designed by and for programmers.

Data Science 2023-2024


C++: The Next Step

• C is a successful and useful language, you might ask why a need for something else
existed.
• The answer is complexity.
• To solve this problem, a new way to program was invented, called object-oriented
programming (OOP).
• C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell
Laboratories in Murray Hill, New Jersey.
• Initially called the language “C with Classes.”
• However, in 1983, the name was changed to C++.
• C++ extends C by adding object-oriented features.

Data Science 2023-2024


The Stage Is Set for Java

• By the end of the 1980s and the early 1990s, object-oriented programming using C++
took hold.
• Within a few years, the World Wide Web and the Internet would reach critical mass.
• This event would precipitate another revolution in programming.
• Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991.
• It took 18 months to develop the first working version. This language was initially called
“Oak,” but was renamed “Java” in 1995.

Data Science 2023-2024


The Creation of Java

• Primary motivation was the need for a platform independent (that is,
architecture-neutral) language that could be used to create software to be embedded in
various consumer electronic devices, such as microwave ovens and remote controls.
• The problem is that compilers are expensive and time-consuming to create.
• Solution, a portable, platform-independent language
• The second force was, of course, the World Wide Web.
• The emergence of the World Wide Web, Java was propelled to the forefront of computer
language design, because the Web, too, demanded portable programs.
• The Internet ultimately led to Java’s large-scale success
• Java is simply the “Internet version of C++.”

Data Science 2023-2024


Java’s Magic: The Bytecode

• The key that allows Java to solve both the security and the portability, the output of a Java
compiler is not executable code. Rather, it is bytecode.
• Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM).

Execution flow of Java Program

Data Science 2023-2024


Java’s Magic: The Bytecode

• In essence, the original JVM was designed as an interpreter for bytecode.


• Translating a Java program into bytecode makes it much easier to run a program in a wide
variety of environments because only the JVM needs to be implemented for each
platform.
• Once the run-time package exists for a given system, any Java program can run on it.
• Remember, although the details of the JVM will differ from platform to platform, all
understand the same Java bytecode.
• The execution of bytecode by the JVM is the easiest way to create truly portable programs

Data Science 2023-2024


The Java Buzzwords

• Although the fundamental forces that necessitated the invention of Java are portability
and security, other factors also played an important role in molding the final form of the
language.
1. Simple - Because Java inherits the C/C++ syntax and many of the object oriented
features of C++, most programmers have little trouble learning Java.
2. Secure - Because the JVM is in control, it can contain the program and prevent it
from generating side effects outside of the system.
3.Portable - WORA
4. Object-oriented - Problems and their solutions are packaged in terms of classes.
The information in a class is the data.
The functionality in a class is the method.
Class provides the framework for building objects

Data Science 2023-2024


The Java Buzzwords
5.Robust
• Program must execute reliably in a variety of systems.
• Reliability
– early (compile time) checking
– dynamic (runtime) checking
– eliminating situations that are error prone.
6. Multi-threaded
• Java supports multithreaded programming, which allows you to write programs that do
many things simultaneously.
• A thread is a part of the program that can operate independently of its other parts
• Multi-threaded programs can do multiple things at once
example: download a file from the web while still looking at other web pages

Data Science 2023-2024


The Java Buzzwords
7. 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.

Data Science 2023-2024


Object-Oriented Programming

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

Data Science 2023-2024


Abstraction

• An essential element of object-oriented programming is abstraction.


• Humans manage complexity through abstraction.
• Example, people do not think of a car as a set of tens of thousands of individual parts.
Instead, they are free to utilize the object as a whole.
• Abstraction is a way of representing some specific data.
• This allows you to layer the semantics of complex systems, breaking them into more
manageable pieces.

Data Science 2023-2024


The Three OOP Principles

1. Encapsulation
2. Inheritance
3. Polymorphism

Data Science 2023-2024


Encapsulation

• Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse.
• One way to think about encapsulation is as a protective wrapper that prevents the code
and data from being arbitrarily accessed by other code defined outside the wrapper.
• In Java, the basis of encapsulation is the class.

• A class defines the structure and behavior (data and code) that will be shared by a set of
objects.
• Objects are sometimes referred to as instances of a class.
• Thus, a class is a logical construct; an object has physical reality

Data Science 2023-2024


Encapsulation

• When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class.
• Specifically, the data defined by the class are referred to as variables. The code that
operates on that data is referred to as Methods.
• Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding
the complexity of the implementation inside the class.
• Each method or variable in a class may be marked private or public

Data Science 2023-2024


Data Science 2023-2024
Data Science 2023-2024
Inheritance

• When you create a class, you will specify the code and data that constitute
that class. Collectively, these elements are called members of the class.
• Inheritance is the process by which one object acquires the properties of
another object. This is important because it supports the concept of hierarchical
classification.
• 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.
• A deeply inherited subclass inherits all of the attributes from each of its ancestors in the
class hierarchy.

Data Science 2023-2024


Polymorphism

• Polymorphism (from Greek, meaning “many forms”) is a feature that allows one
interface to be used for a general class of actions.
• Ex:- Consider 3 stack (which is a last-in, first-out list).
• One stack is used for integer values, one for floating point values, and one for characters.
The algorithm that implements each stack is the same, even though the data being stored
differs.
• The concept of polymorphism is often expressed by the phrase “one interface, multiple
methods.”
• This means that it is possible to design a generic interface to a group of related activities.
• This helps reduce complexity by allowing the same interface to be used to specify a
general class of action.

Data Science 2023-2024


Polymorphism, Encapsulation, and Inheritance Work Together

• When properly applied, polymorphism, encapsulation, and inheritance combine to


produce a programming environment that supports the development of far more robust
and scalable programs than does the process oriented model.
• A well-designed hierarchy of classes is the basis for reusing the code in which you have
invested time and effort developing and testing.
• Encapsulation allows you to migrate your implementations over time without breaking the
code that depends on the public interface of your classes.
• Polymorphism allows you to create clean, sensible, readable, and resilient code

Data Science 2023-2024


Simple JAVA Program

Data Science 2023-2024


Data Types in Java

BYTE
Width : 8 bits
Range : -128 to 127

Data Science 2023-2024


Arrays

• An array is a group of like-typed variables that are referred to by a common name.


• Arrays of any type can be created and may have one or more dimensions.
• A specific element in an array is accessed by its index.
• Arrays offer a convenient means of grouping related information.
• If you are familiar with C/C++, be careful. Arrays in Java work differently than they do in
those languages.
• Normally, an array is a collection of similar type of elements which have a contiguous
memory location.

Data Science 2023-2024


One-Dimensional Arrays

• A one-dimensional array is, essentially, a list of like-typed variables.


type var-name[ ]; (or)
dataType[] arr; (or)
dataType []arr;
• Here, type declares the base type of the array
int month_days[];
myarray = new int[10];

Data Science 2023-2024


One-Dimensional Arrays

• Arrays can be initialized when they are declared.


• An array initializer is a list of comma-separated expressions surrounded by curly braces.
The commas separate the values of the array elements.
int a[]={1,2,3,4,5};
• We can also print the Java array using for-each loop.
• The Java for-each loop prints the array elements one by one.
• It holds an array element in a variable, then executes the body of the loop.

Data Science 2023-2024


Class Fundamentals

• Class is the logical construct upon which the entire Java language is built because it
defines the shape and nature of an object.
• A class, defines a new data type.
• Once defined, this new type can be used to create objects of that type.
• Thus, a class is a template for an object, and an object is an instance of a class.
• Because an object is an instance of a class, the two words object and instance used
interchangeably.
• A class is declared by use of the class keyword.

Data Science 2023-2024


Class Fundamentals

Data Science 2023-2024


The General Form of a Class

• The data, or variables, defined within a class are called instance variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are called members of the
class.
• Variables defined within a class are called instance variables because each instance of the
class (that is, each object of the class) contains its own copy of these variables. Thus, the
data for one object is separate and unique from the data for another

Data Science 2023-2024


A Simple Class

• A class declaration only creates a template;


class Box {
double width;
double height;
double depth;
}
• Box mybox = new Box(); // create a Box object called mybox
• mybox will be an instance of Box. Thus, it will have “physical” reality.
• To access class variables, use the dot (.) operator.
• The dot operator links the name of the object with the name of an instance variable.
• mybox.width = 100;

Data Science 2023-2024


A Simple Class Example

OUTPUT :

Data Science 2023-2024


Declaring Objects

• Obtaining objects of a class is a two-step process.


• First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
Box mybox; // declare reference to object
• Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator.
mybox = new Box(); // allocate a Box object
• The new operator dynamically allocates (that is, allocates at run time) 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

Data Science 2023-2024


Declaring Objects

Data Science 2023-2024


A Closer Look at new

• the new operator dynamically allocates memory for an object.


class-var = new classname( );
• class-var is a variable of the class type being created.
• The classname is the name of the class that is being instantiated.
• The class name followed by parentheses specifies the constructor for the class.
• A constructor defines what occurs when an object of a class is created.

Data Science 2023-2024


Assigning Object Reference Variables

• Object reference variables act differently when an assignment takes place.


Box b1 = new Box();
Box b2 = b1;
b1 = null;
• Here, b1 has been set to null, but b2 still points
to the original object.
• When you assign one object reference variable to another object reference variable, you
are not creating a copy of the object, you are only making a copy of the reference

Data Science 2023-2024


Introducing Methods

• “type” specifies the type of data returned by the method.


• This can be any valid type, including class types that you create. If
the method does not return a value, its return type must be void.
• The name of the method is specified by name. This can be any
legal identifier other than those already used by other items
within the current scope.
• The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called.
• If the method has no parameters, then the parameter list will be empty.
• value is the value returned

Data Science 2023-2024


Garbage Collection

▪ Garbage collection is a mechanism to remove objects from memory when they are no
longer needed.
▪ Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many references an object has.
2) It removes an object from memory when it has no longer any references.
3) Thereafter, the memory occupied by the object can be allocated again.
4) The garbage collector invokes the finalize method.

Data Science 2023-2024


finalize() Method

▪ A constructor helps to initialize an object just after it has been created.


▪ In contrast, the finalize method is invoked just before the object is destroyed:
1) implemented inside a class as:
protected void finalize() { … }
2) implemented when the usual way of removing objects from memory is insufficient, and
some special actions has to be carried out

Data Science 2023-2024


Keyword “this”

▪ Keyword ‘this’ allows a method to refer to the object that invoked it.
▪ It can be used inside any method to refer to the current object:
Example:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

Data Science 2023-2024


A Stack Class

▪ A stack stores data using last-in, first-out ordering.


▪ That is, a stack is like a stack of plates on a table—the first plate put down on the table is
the lastplate to be used.
▪ Stacks are controlled through two operations traditionally called push and pop.
▪ To put an item on top of the stack, you will use push.
▪ To take an item off the stack, you will use pop.

Data Science 2023-2024


A Stack Class

Data Science 2023-2024


Overloading Methods

▪ In Java, it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declaration is different
▪ When this is the case, methods are said to be overloaded and the process is referred to as
method overloading
▪ Method overloading is one of the ways java supports polymorphism.
▪ When an overloaded method is invoked, Java uses the type or number of arguments as its
guide to determine which version of the overloaded method to call
▪ Thus overloaded method must differ in type or number or sequence of their parameters.

Data Science 2023-2024


Overloading Methods

Three ways to overload a method


1. Number of parameters.
▪ add(int, int)
▪ add(int, int, int)
2. Data type of parameters.
▪ add(int, int)
▪ add(int, float)
3. Sequence of Data type of parameters.
▪ add(int, float)
▪ add(float, int)

Data Science 2023-2024


Overloading Methods

Data Science 2023-2024

You might also like