Functional Programming vs Object Oriented Programming
Functional programming is a declarative programming paradigm that writes
in pure functions, meaning that these functions do not modify variables but
instead generate new ones as an output. In other words, the output of a pure
function only depends on the input parameters; thus, there is no external
impact, which avoids side effects. Moreover, writing pure functions also helps
developers avert mutable data and shared state.
Therefore, functional programming has many benefits and is used in a lot of
programming languages and frameworks. It is a popular programming
paradigm due to its ability to create maintainable and clean software by using
functions, which are vital to code organization.
Object-oriented programming is a programming paradigm that organizes
data and the software structure based on the concept of classes and objects.
Classes are a set of instructions (or blueprints) that establish a data structure
for a specific object, determining what the object will contain (the types of
variables that can exist in an object) and how it will behave (the methods or
member functions that define how to operate on the variables). Thus, objects
are instances of classes since classes work as "templates" to create objects.
Plus, objects can contain data in the form of fields (also known as attributes)
and code in the form of procedures (also named methods).
Functional Programming Object Oriented Programming
This programming paradigm is based
This programming paradigm emphasizes
on object oriented concept. Classes are
on the use of functions where each function
used where instance of objects are
performs a specific task.
created
Functional Programming Object Oriented Programming
Fundamental elements used are variables
Fundamental elements used are objects
and functions.The data in the functions are
and methods and the data used here are
immutable(cannot be changed after
mutable data.
creation).
Importance is not given to data but to Importance is given to data rather than
functions. procedures.
It follows imperative programming
It follows declarative programming model.
model.
It uses recursion for iteration. It uses loops for iteration.
It does not support parallel
It is parallel programming supported.
programming.
The statements in this programming The statements in this programming
paradigm does not need to follow a paradigm need to follow an order i.e.,
particular order while execution. bottom up approach while execution.
Has three access specifiers namely,
Does not have any access specifier.
Public, Private and Protected.
To add new data and functions is not so Provides an easy way to add new data
easy. and functions.
No data hiding is possible. Hence, Security Provides data hiding. Hence, secured
is not possible. programs are possible.
https://medium.com/@shaistha24/functional-programming-vs-object-oriented-programming-oop-
which-is-better-82172e53a526
Introduction to JAVA
Java is a class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible. JAVA was developed by James Gosling at Sun
Microsystems Inc in the year 1995 and 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.
Implementation of a Java application program involves a following step.
They include:
1. Creating the program
2. Compiling the program
3. Running the program
Why Use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming language in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful1) Object-Oriented
Portable
Secure
Robust
Platform Independent
Architecture neutral
Java is an object oriented language which gives a clear structure to programs and allows code
to be reused, lowering development costs.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing
are used in Java for creating standalone applications.
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
An application that is distributed in nature, such as banking applications, etc. is called
an enterprise application. It has advantages like high-level security, load balancing,
and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang,
java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like
OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking,
AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise
applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP,
Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
Java Virtual Machine (JVM)
JVM as it is required to run the java program and interprets the program.
The phases are as follows:
Compile the Code: The Java Development Kit(JDK) provides us with the JAVAC compiler to get
through this step. We basically require the JDK to convert our source code into a specific
format (compiled code) that can be easily interpreted by the Java Runtime Environment(JRE).
Run the Code: JVM runs the bytecode provided by the compiler. Since Java is a platform-
independent language, the compiled code produced by the JAVAC compiler is converted to
machine code using platform specific JVMs. Different platforms have different JVMs. JVMs
convert the bytecode into platform specific machine code.
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:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an 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 incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
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. 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
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:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o 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.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o 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
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the 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. 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
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.
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++.
Java supports dynamic compilation and automatic memory management (garbage
collection).
What is Java Bytecode?
Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a
.class file. With the help of java bytecode we achieve platform independence in java.
How does it works?
When we write a program in Java, firstly, the compiler compiles that program and a bytecode
is generated for that piece of code. When we wish to run this .class file on any other platform,
we can do so. After the first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration. This essentially means that we only need to
have basic java installation on any platforms that we want to run our code on. Resources
required to run the bytecode are made available by theJava Virtual Machine, which calls the
processor to allocate the required resources. JVM's are stack-based so they stack
implementation to read the codes.
JVM (Java Virtual Machine) Architecture
1. Java Virtual Machine
2. Internal Architecture of JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
What is JVM
It is:
1. A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM provides definitions for the:
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
VM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run
the java program, it is loaded first by the classloader. There are three built-in
classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes,
java.util package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath"
switch. It is also known as Application classloader.
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.
5) Program Counter Register
PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT
compiles parts of the byte code that have similar functionality at the same time,
and hence reduces the amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, Assembly etc. Java
uses JNI framework to send output to the Console or interact with OS libraries.
Garbage collection
Garbage collection in Java is the automated process of deleting code that’s no longer
needed or used. This automatically frees up memory space and ideally makes coding
Java apps easier for developers.
Java applications are compiled into bytecode that may be executed by a JVM. Objects
are produced on the heap (the memory space used for dynamic allocation), which are
then monitored and tracked by garbage collection operations. Most objects used in
Java code are short-lived and can be reclaimed shortly after they are created. The
garbage collector uses a mark-and-sweep algorithm to mark all unreachable objects
as garbage collection, then scans through live objects to find objects that are still
reachable.
In C/C++, a programmer is responsible for both the creation and destruction of
objects. Usually, programmer neglects the destruction of useless objects. Due to this
negligence, at a certain point, sufficient memory may not be available to create new
objects, and the entire program will terminate abnormally, causing
OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer in
use. Garbage collector destroys these objects. The main objective of Garbage Collector
is to free heap memory by destroying unreachable objects. The garbage collector is
the best example of the Daemon thread as it is always running in the background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection is the
process of looking at heap memory, identifying which objects are in use and which are
not, and deleting the unused objects. An in-use object, or a referenced object, means
that some part of your program still maintains a pointer to that object. An unused or
unreferenced object is no longer referenced by any part of your program. So the
memory used by an unreferenced object can be reclaimed. The programmer does not
need to mark objects to be deleted explicitly. The garbage collection implementation
lives in the JVM.
Types of Activities in Java Garbage Collection
Two types of garbage collection activity usually happen in Java. These are:
Minor or incremental Garbage Collection: It is said to have occurred when
unreachable objects in the young generation heap memory are removed.
Major or Full Garbage Collection: It is said to have occurred when the objects that
survived the minor garbage collection are copied into the old generation or permanent
generation heap memory are removed. When compared to the young generation,
garbage collection happens less frequently in the old generation.
The advantages of Garbage Collection in Java are:
It makes java memory-efficient because the garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM), so we don’t need extra
effort.
Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
How can an object be unreferenced?
There are many ways:
1.By nulling the reference
2.By assigning a reference to another
3.By anonymous object
4.finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:
protected void finalize(){}
5.gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc(){}
JAVA APPLETS
An applet is a special kind of Java program that runs in a Java enabled browser.
This is the first Java program that can run over the network using the browser.
Applet is typically embedded inside a web page and runs in the browser.
Applets are small Java applications that can be accessed on an Internet server,
transported over Internet, and can be automatically installed and run as apart of a web
document.
After a user receives an applet, the applet can produce a graphical user interface. It
has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The JVM can
use either a plug-in of the Web browser or a separate runtime environment to run an
applet application.
JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.
Life Cycle of an Applet
init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
start − This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing the
applet after having gone off to other pages.
stop − This method is automatically called when the user moves off the page
on which the applet sits. It can, therefore, be called repeatedly in the same
applet.
destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally
leave resources behind after a user leaves the page that contains the applet.
paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.
Applet class
Applet class provides all necessary support for applet execution, such as initializing
and destroying of applet. It also provide methods that load and display images and
methods that load and play audio clips.
An Applet Skeleton
Most applets override these four methods. These four methods forms Applet lifecycle.
init() : init() is the first method to be called. This is where variable are initialized.
This method is called only once during the runtime of applet.
start() : start() method is called after init(). This method is called to restart an applet
after it has been stopped.
stop() : stop() method is called to suspend thread that does not need to run when
applet is not visible.
destroy() : destroy() method is called when your applet needs to be removed
completely from memory.
Note: The stop() method is always called before destroy() method.
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-
based, graphical user interface. java.applet.* imports the applet package, which contains the
class Applet. Every applet that you create must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed by code that
is outside the program.Every Applet application must declare a paint() method. This method is
defined by AWT class and must be overridden by the applet. The paint() method is called each
time when an applet needs to redisplay its output. Another important thing to notice about
applet application is that, execution of an applet does not begin at main() method. In fact an
applet application does not have any main() method.
Features of Applets over HTML
Displaying dynamic web pages of a web application.
Playing sound files.
Displaying documents
Playing animations
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java
applets:
1. An applet cannot load libraries or define native methods.
2. An applet cannot ordinarily read or write files on the execution host.
3. An applet cannot read certain system properties.
4. An applet cannot make network connections except to the host that it
came from.
5. An applet cannot start any program on the host that’s executing it.
Lexical Issues
Now that you have seen several short Java programs, it is time to more formally
describe the atomic elements of Java. Java programs are a collection of
whitespace, identifiers, literals, comments, operators, separators, and keywords.
The operators are described in the next chapter. The others are described next.
Whitespace
Java is a free-form language. This means that you do not need to follow any
special indentation rules. For instance, the Example program could have been
written all on one line or in any other strange way you felt like typing it, as long
as there was at least one whitespace character between each token that was not
already delineated by an operator or separator. In Java, whitespace is a space, tab,
or newline.
Identifiers
Identifiers are used to name things, such as classes, variables, and methods. An
identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters. (The dollar-sign character
is not intended for general use.) They must not begin with a number, lest they be
confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a
different identifier than Value. Some examples of valid identifiers are
Literals
A constant value in Java is created by using a literal representation of it. For
example, here are some literals:
Left to right, the first literal specifies an integer, the next is a floating-point value,
the third is a character constant, and the last is a string. A literal can be used
anywhere a value of its type is allowed.
Comments
As mentioned, there are three types of comments defined by Java. You have
already seen two: single-line and multiline. The third type is called
a documentation comment. This type of comment is used to produce an HTML
file that documents your program. The documentation comment begins with a /**
and ends with a */. Documentation comments are explained in the Appendix.
Separators
In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon. As you have seen, it is used
to terminate statements. The separators are shown in the following table:
The Java Keywords
There are 50 keywords currently defined in the Java language .These keywords,
combined with the syntax of the operators and separators, form the foundation of
the Java language. These keywords cannot be used as identifiers. Thus, they
cannot be used as names for a variable, class, or method.
The keywords const and goto are reserved but not used. In the early days of
Java, several other keywords were reserved for possible future use. In addition to
the keywords, Java reserves the following: true, false, and null. These are values
defined by Java. You may not use these words for the names of variables, classes,
and so on.