Module-1 - Java Basics and OOPS Overview
Module-1 - Java Basics and OOPS Overview
Module - 1
What is Java?
Where it is used?
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
applications 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 dynamic page, is called 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 enterprise
application. It has the advantage of high level security, load balancing and clustering. In
java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
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 from 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. But, it was 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".
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major points that describes the history of java.
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) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and 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 choosen as a national tree of many countries like
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 choosen java name 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.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
10) Originally 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.
C++ vs Java
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. interpreter for printing systems but
It was an extension of C later extended as a support network
programming language. computing. It was designed with a
goal of being easy to use and
accessible to a wider audience.
Goto C++ supports goto statement. Java doesn't support goto statement.
Pointers C++ supports pointers. You can Java supports pointer internally. But
write pointer program in C++. you can't write the pointer program in
java. It means java has restricted
pointer support in java.
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter
Interpreter compiled and run using both. Java source code is converted
compiler which converts source into byte code at compilation time.
code into machine code so, C++ The interpreter executes this byte
is platform dependent. code at run time and produces output.
Java is interpreted that is why it is
platform independent.
Call by Value and C++ supports both call by value Java supports call by value only.
Call by reference and call by reference. There is no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.
Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide whether or override all non-static methods by
not override a function. default. In other words, non-static
methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the top
for the negative numbers. For
positive numbers, it works same like
>> operator.
Inheritance Tree C++ creates a new inheritance Java uses single inheritance tree
tree always. always because all classes are the
child of Object class in java. Object
class is the root of inheritance tree in
java.
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
To set the temporary path of JDK, you need to follow following steps:
For Example:
For setting the permanent path of JDK, you need to follow these steps:
o Go to MyComputer properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable value -
> ok -> ok -> ok
For Example:
1)Go to MyComputer properties
8)click on ok button
9)click on ok button
Now your permanent path is set. You can now execute any program of java from any drive.
tool rather than set. Let's see how to set path in Linux OS:
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called virtual machine because it
doesn't physically exist. It is a specification that provides runtime environment in which java
bytecode can be executed. It can also run those programs which are written in other languages
and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS are different from each other. But, Java is platform
independent. There are three notions of the JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
1) 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
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.
PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
7) Execution Engine
It contains:
1) A virtual processor
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing java applications.
Implementations of JVMs are also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) etc. to complete the development of a Java Application.
Java Variables
A variable is a container which holds the value while the java program is executed. A variable is
assigned with a datatype.
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
Types of Variable
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in the memory.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include Integer, Character, Boolean, and
Floating Point.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. It is generally used as the default data type for decimal values. Its
default value is 0.0d.
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency.Its default value is 0.0d.
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
The popular object-oriented languages are Java, C#, PHP, Python, C++ etc.
The main aim of object oriented programming is to implement real world entities i.e. object,
classes, abstraction, inheritance, polymorphism etc.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing details of each other's data or
code, the only necessary thing is that the type of message accepted and type of response returned
by the objects.
Example: A dog is an object because it has states i.e. color, name, breed etc. as well as
behaviors i.e. wagging the tail, barking, eating etc.
Class
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn?t store any space.
Inheritance
When one object acquires all the properties and behaviours of parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
3) OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object attributes:
public Main() {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
// Outputs 5
The following example adds an int y parameter to the constructor. Inside the constructor we set x
to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will
set the value of x to 5:
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
int modelYear;
String modelName;
modelYear = year;
modelName = name;
Java Modifiers
The public keyword is an access modifier, meaning that it is used to set the access level for
classes, attributes, methods and constructors.
Access Modifiers
Modifier Description
default The class is only accessible by classes in the same package. This is used when you
don't specify a modifier.
Modifier Description
default The code is only accessible in the same package. This is used when you don't
specify a modifier.
Non-Access Modifiers
Modifier Description
abstract The class cannot be used to create objects (To access an abstract class, it must be
inherited from another class.
Modifier Description
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The method
does not have a body, for example abstract void run();. The body is provided by the
subclass (inherited from).
transient Attributes and methods are skipped when serializing the object containing them
volatile The value of an attribute is not cached thread-locally, and is always read from the
"main memory"
Java Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
• provide public get and set methods to access and update the value of a private variable
You learned from the previous chapter that private variables can only be accessed within the
same class (an outside class has no access to it). However, it is possible to access them if we
provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable, with
the first letter in upper case:
// Getter
return name;
// Setter
this.name = newName;
Example explained
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.
However, as the name variable is declared as private, we cannot access it from outside this class:
System.out.println(myObj.getName());
// Outputs "John"
In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
System.out.println("Tuut, tuut!");
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single
action in different ways.
For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
Java Abstraction
Data abstraction is the process of hiding certain details and showing only essential information
to the user.
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).
// Abstract class
// Regular method
System.out.println("Zzz");
myPig.animalSound();
myPig.sleep();
Java Interfaces
An interface is a completely "abstract class" that is used to group related methods with empty
bodies.
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
System.out.println("Zzz");
myPig.animalSound();
myPig.sleep();
To create an enum, use the enum keyword (instead of class or interface), and separate the
constants with a comma. Note that they should be in uppercase letters:
enum Result {
FCD,
FC,
SC
enum Result {
FCD,
FC,
SC
System.out.println(myVar);
In Java Enums, values() and valueOf() are methods commonly associated with enumerations
(enums).
1. values() Method
• Purpose: The values() method returns an array of all the constants defined within an
enum.
• Usage: This method is implicitly declared by the compiler for all enums, and you don’t
need to define it manually.
• Returns: An array of the enum type, containing all the enum constants.
Example:
enum Day {
System.out.println(day);
Output:
Copy code
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
2. valueOf() Method
• Purpose: The valueOf() method is used to return the enum constant of the specified
string name.
• Usage: It takes a string as a parameter and returns the enum constant with that name. The
name must exactly match the identifier used to declare the enum constant in this type.
• Returns: The enum constant whose name matches the provided string.
• Throws: IllegalArgumentException if the specified enum type has no constant with the
specified name.
Example:
enum Day {
Output:
Day: MONDAY
JAVA Annotations
java annotations are a form of metadata that provide data about a program but are not part of the
program itself. They are used to provide additional information about the code to the compiler,
development tools, and libraries without modifying the behavior of the code directly.
1. Metadata for Code: Annotations are used to add metadata to Java code, such as classes,
methods, variables, parameters, and packages.
2. No Direct Effect on Code Execution: Annotations do not directly affect the execution of
code but can be used by compilers, tools, or libraries to enforce certain behaviors.
1. Built-in Annotations:
o @Target: Specifies the kinds of program elements to which the annotation type is
applicable (e.g., methods, fields).
3. Custom Annotations:
o You can create your own annotations by defining a new annotation type using the
@interface keyword.
Retention Policies
• SOURCE: Annotations are discarded by the compiler and not included in the compiled
.class files.
• CLASS: Annotations are retained in the .class files but are not available at runtime.
• RUNTIME: Annotations are retained at runtime and can be accessed using reflection.
Java Collections and Frameworks form the backbone of data management in Java applications,
providing a standardized way to handle groups of objects. Here's an overview of Java Collections
and the Java Collections Framework (JCF):
The Java Collections Framework is a unified architecture for representing and manipulating
collections of objects. It includes interfaces, implementations (classes), and algorithms to work
with data structures such as lists, sets, queues, and maps.
1. Collection Interface: The root interface that represents a group of objects. It includes
methods to add, remove, and access elements.
2. List Interface: An ordered collection (also known as a sequence) that allows duplicate
elements.
4. Queue Interface: Designed to hold elements before processing. Typically follows a First-
In-First-Out (FIFO) order.
5. Deque Interface: A double-ended queue that allows the insertion and removal of elements
from both ends.
6. Map Interface: Represents a collection of key-value pairs, where each key is unique.
• LinkedList: Doubly linked list implementation of the List and Deque interfaces, allowing
fast insertions or deletions.
• HashSet: A Set implementation backed by a hash table, which does not guarantee any
order.
• HashMap: A Map implementation backed by a hash table, allowing null keys and values
but with no guaranteed order.
• TreeMap: A Map implementation that keeps the keys sorted, offering log(n) time
complexity for insertions and lookups.
1. Consistency: Common methods across all collections (add(), remove(), contains(), etc.),
making it easier to learn and use.
2. Efficiency: Collections are optimized for performance, with each data structure designed
for specific use cases.
3. Thread Safety: Some implementations, like Vector and Hashtable, are synchronized, but
newer ones like ArrayList and HashMap are not. Thread-safe versions
(Collections.synchronizedList(), ConcurrentHashMap) are also available.
5. Algorithm Support: The framework provides algorithms such as sorting, searching, and
shuffling that can operate on collections.
• Reduces programming effort by providing data structures and algorithms out of the box.
• Enhances code reusability by offering a wide range of collection types and algorithms.
• Data storage and retrieval: Use Lists and Maps to store data that needs frequent updates
or lookups.
• Sorting and searching: Use TreeSet or TreeMap for naturally ordered data.
ArrayList is one of the most commonly used implementations of the List interface. It allows
duplicate elements, maintains insertion order, and provides random access to elements.
import java.util.ArrayList;
import java.util.Collections;
// Accessing elements
System.out.println("First fruit: " + fruits.get(0)); // Output: Apple
// Removing an element
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);
}
}
HashSet is an implementation of the Set interface that does not allow duplicate elements and
does not maintain any order.
import java.util.HashSet;
// Removing an element
numbers.remove(3);
System.out.println("After removing 3: " + numbers);
}
}
HashMap is an implementation of the Map interface that stores key-value pairs, allowing null
keys and values.
import java.util.HashMap;
import java.util.Map;
PriorityQueue is a Queue implementation that orders its elements according to their natural order
or by a custom comparator.
import java.util.PriorityQueue;
ArrayDeque is a resizable array implementation of the Deque interface that allows adding or
removing elements from both ends.
import java.util.ArrayDeque;
These examples demonstrate the core functionalities of Java Collections and how they can be
used for different data manipulation tasks in a Java application.