0% found this document useful (0 votes)
23 views

Module-1 - Java Basics and OOPS Overview

Uploaded by

Rupith Kumar .N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Module-1 - Java Basics and OOPS Overview

Uploaded by

Rupith Kumar .N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Prepared by Mr. Lohith C, Professor, Department of Dr.

APJ Kalam School of Engineering

Subject: Advanced Java and J2EE


Module 1
Prepared By Mr. Lohith C
Professor
Dept of APJ Abdul Kalam School of Engineering
Garden City University

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Module - 1

What is Java?

Java is a programming language and a platform.

Java is a high level, robust, secured and object-oriented programming language.

Platform: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has its own runtime environment (JRE) and API, it is called platform.

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:

1. Desktop Applications such as acrobat reader, media player, antivirus etc.


2. Web Applications such as irctc.co.in, vtu.ac.in etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc

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. Example of standalone

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

Why Java named as "Oak"

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.

Why Java Programming named as "Java"

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

9) Notice that Java is just a name not an acronym.

10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996).

C++ vs Java

Comparison Index C++ Java

Platform- C++ is platform-dependent. Java is platform-independent.


independent

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.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by interfaces in java.

Operator C++ supports operator Java doesn't support operator

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Overloading overloading. overloading.

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.

Documentation C++ doesn't support Java supports documentation


comment documentation comment. comment (/** ...**/) to create
documentation for java source code.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

Hardware C++ is more nearer to hardware. Java is not so interactive with


hardware.

Object oriented C++ is an object-oriented Java is also an object-


language. But in C++ language, oriented language. But in Java,
single root hierarchy is not everything (except fundamental
possible. types) is an object in Java. It is a
single root hierarchy as everything
gets derived from java.lang.Object.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.

What happens at runtime?

At runtime, following steps are performed:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Classloader: is the subsystem of JVM that is used to load class files.

Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.

Interpreter: read bytecode stream then execute the instructions.

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

o Open command prompt


o Copy the path of jdk/bin directory
o Write in command prompt: set path=copied_path

For Example:

set path=C:\Program Files\Java\jdk1.6.0_23\bin

Let's see it in the figure given below:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

2) How to set Permanent Path of JDK in Windows

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

2)click on advanced tab

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

3)click on environment variables

4)click on new tab of user variables

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

5)write path in variable name

6)Copy the path of bin folder

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

7)paste path of bin folder in variable value

8)click on ok button

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

9)click on ok button

Now your permanent path is set. You can now execute any program of java from any drive.

Setting Java Path in Linux OS


Setting path in Linux OS is same as setting path in the Windows OS. But here we use export

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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

Difference between JDK, JRE and JVM

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.

The JVM performs following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.

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.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

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.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

It is used to provide runtime environment. It is the implementation of JVM. It physically exists.


It contains set of libraries + other files that JVM uses at runtime.

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:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

1. int data=50;//Here data is variable

Types of Variable

There are three types of variables in java:

o local variable
o instance variable
o static variable

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

A local variable cannot be defined with "static" keyword.

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.

Example to understand the types of variables in java


class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Data Types in Java

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.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared


before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

• boolean data type


• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Data Type Default Value Default size

Boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Float 0.0f 4 byte

Double 0.0d 8 byte

Boolean Data Type

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.

Example: Boolean one = false

Byte Data Type

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.

Example: byte a = 10, byte b = -20

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

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Example: short s = 10000, short r = -5000

Int Data Type

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.

Example: int a = 100000, int b = -200000

Long Data Type

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.

Example: long a = 100000L, long b = -200000L

Float Data Type

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.

Example: float f1 = 234.5f

Double Data Type

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

Example: double d1 = 12.3

Char Data Type

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.

Example: char letterA = 'A'

Java OOPs Concepts

Object Oriented Programming is a paradigm that provides many concepts such


as inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object, is known as truly object-oriented
programming language.

Smalltalk is considered as the first truly object-oriented programming language.

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.

OOPs (Object Oriented Programming System)

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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

Collection of objects is called class. It is a logical entity.

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.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

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.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier where as in Procedure-oriented


programming language it is not easy to manage if code grows as project size grows.

2) OOPs provides data hiding whereas in Procedure-oriented programming language a global


data can be accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming

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.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This will call the constructor)

System.out.println(myObj.x); // Print the value of x

// Outputs 5

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Constructor with Parameters

Constructors can also take parameters, which is used to initialize attributes.

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:

public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

// Outputs 5

public class Main {

int modelYear;

String modelName;

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

public Main(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

Main myCar = new Main(1969, "Mustang");

System.out.println(myCar.modelYear + " " + myCar.modelName);

// Outputs 1969 Mustang

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.

We divide modifiers into two groups:

• Access Modifiers - controls the access level


• Non-Access Modifiers - do not control access level, but provides other functionality

Access Modifiers

Modifier Description

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

public The class is accessible by any other class

default The class is only accessible by classes in the same package. This is used when you
don't specify a modifier.

Modifier Description

public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This is used when you don't
specify a modifier.

protected The code is accessible in the same package and subclasses.

Non-Access Modifiers

For classes, you can use either final or abstract:

Modifier Description

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

final The class cannot be inherited by other classes

abstract The class cannot be used to create objects (To access an abstract class, it must be
inherited from another class.

Modifier Description

final Attributes and methods cannot be overridden/modified

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

synchronized Methods can only be accessed by one thread at a time

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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:

• declare class variables/attributes as private

• provide public get and set methods to access and update the value of a private variable

Get and Set

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:

public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

// Setter

public void setName(String newName) {

this.name = newName;

Example explained

The get method returns the value of the variable name.

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:

public class Main {

public static void main(String[] args) {

Person myObj = new Person();

myObj.setName("John"); // Set the value of the name variable to "John"

System.out.println(myObj.getName());

// Outputs "John"

Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:

• subclass (child) - the class that inherits from another class

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

• superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

public class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

public void honk() { // Vehicle method

System.out.println("Tuut, tuut!");

public class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute

public static void main(String[] args) {

// Create a myCar object

Car myCar = new Car();

// 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

System.out.println(myCar.brand + " " + myCar.modelName);

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.):

public class Animal {

public void animalSound() {

System.out.println("The animal makes a sound");

public Pig extends Animal {

public void animalSound() {

System.out.println("The pig says: wee wee");

public class Dog extends Animal {

public void animalSound() {

System.out.println("The dog says: bow wow");

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

public class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

Animal myPig = new Pig(); // Create a Pig object

Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();

myPig.animalSound();

myDog.animalSound();

Java Abstraction

Abstract Classes and Methods

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

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

An abstract class can have both abstract and regular methods:

To access the abstract class, it must be inherited from another class.

// Abstract class

public abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

System.out.println("Zzz");

// Subclass (inherit from Animal)

public class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

public class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

myPig.animalSound();

myPig.sleep();

Java Interfaces

Another way to achieve abstraction in Java, is with 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

public interface Animal {

public void animalSound(); // interface method (does not have a body)

public void sleep(); // interface method (does not have a body)

// Pig "implements" the Animal interface

public class Pig implements Animal {

public void animalSound() {

// The body of animalSound() is provided here

System.out.println("The pig says: wee wee");

public void sleep() {

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

// The body of sleep() is provided here

System.out.println("Zzz");

public class Main {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

Java Enumerations (Enums)

An enum is a special "class" that represents a group of constants (unchangeable variables,


like final variables).

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

You can access enum constants with the dot syntax:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Result myVar = Result.FC;

Enum inside a class

public class Main {

enum Result {

FCD,

FC,

SC

public static void main(String[] args) {

Result myVar = Result.FC;

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:

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

public class EnumValuesExample {

enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

public static void main(String[] args) {

// Use the values() method to iterate over enum constants

for (Day day : Day.values()) {

System.out.println(day);

Output:

Copy code

SUNDAY

MONDAY

TUESDAY

WEDNESDAY

THURSDAY

FRIDAY

SATURDAY

2. valueOf() Method

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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

public class EnumValueOfExample {

enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

public static void main(String[] args) {

// Use the valueOf() method to get an enum constant

Day day = Day.valueOf("MONDAY");

System.out.println("Day: " + day);

Output:

Day: MONDAY

JAVA Annotations

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

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.

Key Features of Java Annotations

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.

3. Used for Various Purposes:

o Compile-time instructions: Provide information to the compiler (e.g.,


@Override, @Deprecated).

o Runtime processing: Provide information that can be used by frameworks at


runtime (e.g., Spring, Hibernate).

o Documentation: Enhance code readability by providing information about the


code.

Commonly Used Java Annotations

1. Built-in Annotations:

o @Override: Indicates that a method overrides a method in the superclass.

o @Deprecated: Marks a method, class, or field as deprecated, suggesting that it


should not be used anymore.

o @SuppressWarnings: Instructs the compiler to suppress specific warnings.

2. Meta-annotations (annotations that apply to other annotations):

o @Retention: Specifies how long the annotation is retained (e.g., SOURCE,


CLASS, RUNTIME).

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

o @Target: Specifies the kinds of program elements to which the annotation type is
applicable (e.g., methods, fields).

o @Inherited: Allows an annotation to be inherited from a superclass.

o @Documented: Indicates that an annotation should be included in the generated


Javadoc.

3. Custom Annotations:

o You can create your own annotations by defining a new annotation type using the
@interface keyword.

4. Annotations in Popular Frameworks:

o Spring: @Autowired, @Component, @Service, @Controller, etc.

o JUnit: @Test, @Before, @After, etc.

o Hibernate: @Entity, @Table, @Column, etc.

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.

Benefits of Using Annotations

• Simplify code by reducing boilerplate.

• Enhance readability and maintainability.

• Provide a standard way to configure and interact with frameworks.

• Enable declarative programming and reduce configuration errors.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Collections and Frameworks

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):

Java Collections Framework Overview

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.

Key Interfaces in Java Collections Framework

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.

• Implementations: ArrayList, LinkedList, Vector, Stack.

3. Set Interface: A collection that does not allow duplicate elements.

• Implementations: HashSet, LinkedHashSet, TreeSet.

4. Queue Interface: Designed to hold elements before processing. Typically follows a First-
In-First-Out (FIFO) order.

• Implementations: PriorityQueue, LinkedList.

5. Deque Interface: A double-ended queue that allows the insertion and removal of elements
from both ends.

• Implementations: ArrayDeque, LinkedList.

6. Map Interface: Represents a collection of key-value pairs, where each key is unique.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

• Implementations: HashMap, LinkedHashMap, TreeMap, Hashtable.

Common Classes in Java Collections Framework

• ArrayList: Resizable array implementation of the List interface, which maintains


insertion order and allows random access.

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

• TreeSet: A NavigableSet implementation based on a TreeMap, ensuring elements are


sorted.

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

Core Features of Java Collections Framework

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.

4. Extensibility: Easily extendable to create custom collection implementations.

5. Algorithm Support: The framework provides algorithms such as sorting, searching, and
shuffling that can operate on collections.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

Benefits of Using Java Collections Framework

• Reduces programming effort by providing data structures and algorithms out of the box.

• Increases performance due to high-efficiency data structures.

• Enhances code reusability by offering a wide range of collection types and algorithms.

• Provides interoperability between unrelated APIs by establishing a common set of


interfaces.

Use Cases of Java Collections Framework

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

• Concurrent programming: Use thread-safe collections like ConcurrentHashMap in multi-


threaded environments.

Java Collections in Practice

• Sorting a List: Collections.sort(list)

• Searching in a List: Collections.binarySearch(list, key)

• Finding max/min: Collections.max(list), Collections.min(list)

1. List Interface Example (ArrayList)

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;

public class ArrayListExample {


public static void main(String[] args) {
Garden City University
Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

// Creating an ArrayList of String type


ArrayList<String> fruits = new ArrayList<>();

// Adding elements to the ArrayList


fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add("Apple"); // Allows duplicate

// Accessing elements
System.out.println("First fruit: " + fruits.get(0)); // Output: Apple

// Iterating over the ArrayList


System.out.println("List of fruits:");
for (String fruit : fruits) {
System.out.println(fruit);
}

// Sorting the ArrayList


Collections.sort(fruits);
System.out.println("Sorted fruits: " + fruits);

// Removing an element
fruits.remove("Banana");
System.out.println("After removing Banana: " + fruits);
}
}

2. Set Interface Example (HashSet)

HashSet is an implementation of the Set interface that does not allow duplicate elements and
does not maintain any order.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

import java.util.HashSet;

public class HashSetExample {


public static void main(String[] args) {
// Creating a HashSet of integers
HashSet<Integer> numbers = new HashSet<>();

// Adding elements to the HashSet


numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(1); // Duplicate element, will not be added

// Displaying the HashSet


System.out.println("HashSet: " + numbers); // Output: [1, 2, 3]

// Checking if an element exists


if (numbers.contains(2)) {
System.out.println("HashSet contains 2");
}

// Removing an element
numbers.remove(3);
System.out.println("After removing 3: " + numbers);
}
}

3. Map Interface Example (HashMap)

HashMap is an implementation of the Map interface that stores key-value pairs, allowing null
keys and values.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {


public static void main(String[] args) {
// Creating a HashMap of String keys and Integer values
HashMap<String, Integer> scores = new HashMap<>();

// Adding key-value pairs to the HashMap


scores.put("Alice", 85);
scores.put("Bob", 90);
scores.put("Charlie", 75);
scores.put("Alice", 95); // Updates Alice's score

// Accessing a value by its key


System.out.println("Alice's score: " + scores.get("Alice")); // Output: 95

// Iterating over the HashMap


for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Removing a key-value pair


scores.remove("Charlie");
System.out.println("After removing Charlie: " + scores);
}
}

4. Queue Interface Example (PriorityQueue)

PriorityQueue is a Queue implementation that orders its elements according to their natural order
or by a custom comparator.

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

import java.util.PriorityQueue;

public class PriorityQueueExample {


public static void main(String[] args) {
// Creating a PriorityQueue of integers
PriorityQueue<Integer> queue = new PriorityQueue<>();

// Adding elements to the PriorityQueue


queue.add(10);
queue.add(5);
queue.add(20);
queue.add(1);

// Displaying the top element


System.out.println("Top element: " + queue.peek()); // Output: 1

// Removing elements from the PriorityQueue


System.out.println("Polling element: " + queue.poll()); // Removes 1
System.out.println("After polling, top element: " + queue.peek()); // Output: 5
}
}

5. Deque Interface Example (ArrayDeque)

ArrayDeque is a resizable array implementation of the Deque interface that allows adding or
removing elements from both ends.

import java.util.ArrayDeque;

public class ArrayDequeExample {


public static void main(String[] args) {
// Creating an ArrayDeque of integers

Garden City University


Prepared by Mr. Lohith C, Professor, Department of Dr. APJ Kalam School of Engineering

ArrayDeque<Integer> deque = new ArrayDeque<>();

// Adding elements to both ends


deque.addFirst(1);
deque.addLast(2);
deque.addFirst(0);

// Displaying the Deque


System.out.println("Deque: " + deque); // Output: [0, 1, 2]

// Removing elements from both ends


deque.removeFirst();
deque.removeLast();
System.out.println("After removals: " + deque); // Output: [1]
}
}

These examples demonstrate the core functionalities of Java Collections and how they can be
used for different data manipulation tasks in a Java application.

Garden City University

You might also like