Java Unit 1
Java Unit 1
Introduction
1 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Class: A class is a user-defined blueprint or prototype from which objects are created.
It represents the set of properties or methods that are common to all objects of one type.
Using classes, we can create multiple objects with the same behavior instead of writing
their code multiple times. This includes classes for objects occurring more than once in
our code.
Object: An object is a basic unit of Object-Oriented Programming that represents real-
life entities. A typical Java program creates many objects, which interact by invoking
methods.
These are the part of our code visible to the viewer/user. An object mainly consists of:
1. State: It is represented by the attributes of an object. It also reflects the properties
of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact with
other objects
4. Method: A method is a collection of statements that perform some specific task
and return the result to the caller. A method can perform some specific task
without returning anything. Methods allow us to reuse the code without retyping
it, which is why they are considered time savers. In Java, every method must be
part of some class, which is different from languages like C, C++, and Python.
2 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Pillar 1: Abstraction:
Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or non-essential units are not displayed to the user. Ex:
A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object, ignoring the irrelevant details. The properties and
behaviours of an object differentiate it from other objects of similar type and also help
in classifying/grouping the object.
In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together the code and the data it manipulates. Another way to think about
encapsulation is that it is a protective shield that prevents the data from being accessed
by the code outside this shield.
• Technically, in encapsulation, the variables or the data in a class is hidden from
any other class and can be accessed only through any member function of the
class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes, which is similar
to what data-hiding does. So, the terms “encapsulation” and “data-hiding” are
used interchangeably.
• Encapsulation can be achieved by declaring all the variables in a class as private
and writing public methods in the class to set and get the values of the variables.
//Encapsulation using private modifier
//Employee class contains private data called employee id and employee name
class Employee {
private int empid;
private String ename;
3 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
Pillar 3: Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features (fields and
methods) of another class. We are achieving inheritance by using extends keyword.
Inheritance is also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
• Superclass: The class whose features are inherited is known as superclass (also
known as base or parent class).
• Subclass: The class that inherits the other class is known as subclass (also known
as derived or extended or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
4 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Pillar 4: Polymorphism
It refers to the ability of object-oriented programming languages to differentiate
between entities with the same name efficiently. This is done by Java with the help of
the signature and declaration of these entities. The ability to appear in many forms is
called polymorphism.
Types of Polymorphism
5 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
1. Method Overloading:
class Calculator {
int add(int a, int b) {
return a + b;
}
6 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Method Overriding:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
a = new Dog();
[Link](); // Output: Dog barks
7 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
a = new Cat();
[Link](); // Output: Cat meows
}
}
8 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Introduction to Java
Java as a programming language was originally developed by James Gosling and his
team at Sun Microsystems and released in 1995 as a core component of Sun
Microsystems’ Java platform.
The language derives much of its syntax from C and C++ but has a simpler object model
and fewer low-level facilities.
Java applications are typically compiled to bytecode that can run on any Java Virtual
Machine (JVM) regardless of computer architecture.
The term Java actual refers to more than just a particular language like C or
Pascal. Java encompasses several parts, including:
♦ A high level language: Java is a high level language that at a glance looks very similar
to C and C++ but offers many unique features of its own.
♦ Java bytecode: a compiler, such as Oracle’s javac, transforms the Java language
source code to bytecode that runs in the JVM.
♦ Java Virtual Machine (JVM): a program, such as Sun’s java, that runs on a given
platform and takes the bytecode programs as input and interprets them just as if it were
a physical processor executing machine code.
Oracle provides a set of programming tools such as javac, java and others in a bundle
that it calls a Java Development Kit for each version of the language and for different
platforms such as Windows, Linux, etc. Oracle also provides a runtime bundle with just
the JVM when the programming tools are not needed.
There are mainly four types of applications that can be created using Java
programming language —
1) Stand-alone Application
Stand-alone applications are also known as desktop applications or window-based
applications. These are traditional softwares that we need to install on every machine.
Examples of standalone application are Media player, anti-virus, etc. AWT and Swing
are used in Java for creating standalone applications.
2) Web Application
9 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
This is a type of 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
This is a type of application that is distributed in nature, such as banking applications,
etc. is called enterprise application. It has advantages of the high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
This is a type of 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 four platforms or editions of Java —
1) Java SE (Java Standard Edition)
This is the Java programming platform. It includes Java programming APIs such as
[Link], [Link], [Link], [Link], [Link], [Link] 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)
This is the enterprise platform which is mainly used to develop web and enterprise
applications. It is built on the top of the Java SE platform. It includes topics like Servlet,
JSP, Web Services, EJB, Java Persistence API (JPA), etc.
3) Java ME (Java Micro Edition)
This is the micro platform which is mainly used to develop mobile applications.
4) JavaFX
This is used to develop rich internet applications (RIA). It uses a light-weight user
interface API.
10 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Java Features
1. Platform Independent
• Unlike many other programming languages including C and C++ when Java is
compiled, it is not compiled into platform specific machine, rather into platform
independent byte code.
• This byte code is distributed over the web and interpreted by JVM on whichever
platform it is being run.
2. Object Oriented
• Object oriented throughout – no coding outside of class definitions, including
main().
• An extensive class library available in the core language packages.
3. Compiler/Interpreter Combo
• Code is compiled to bytecodes that are interpreted by Java virtual machines
(JVM).
• This provides portability to any machine for which a virtual machine has been
written.
• The two steps of compilation and interpretation allow for extensive code
checking and improved security.
4. Robust
Exception handling built-in, strong type checking (that is, all data must be declared an
explicit type), local variables must be initialized.
11 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
7. Secure
♦ No memory pointers
♦ Programs run inside the virtual machine sandbox.
♦ Array index limit checking
♦ Code managed by
1. bytecode verifier – checks classes after loading
2. class loader – confines objects to unique namespaces. Prevents
loading a hacked “[Link]” class, for example.
3. security manager – determines what resources a class can access
such as reading and writing to the local disk.
8. Dynamic Binding
• The linking of data and methods to where they are located is done at run-time.
• New classes can be loaded while a program is running. Linking is done on the
fly.
• Even if libraries are recompiled, there is no need to recompile code that uses
classes in those libraries.
This differs from C++, which uses static binding. This can result in fragile classes for
cases where linked code is changed and memory pointers then point to the wrong
addresses.
12 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
9. High Performance
Interpretation of bytecodes slowed performance in early versions, but advanced virtual
machines with adaptive and just-in-time compilation and other techniques now
typically provide performance up to 50% to 100% the speed of C++ programs.
[Link]
• Lightweight processes, called threads, can easily be spun off to perform
multiprocessing.
• Can take advantage of multiprocessors where available
• Great for multimedia displays.
[Link]-in Networking
Java was designed with networking in mind and comes with many classes to develop
sophisticated Internet communications.
Reasons why you should learn Java programming. Why I think Java is the best
programming language created ever.
1. Platform Independence: Java code can be run on any device that supports Java
Virtual Machine (JVM), making it platform-independent. This "write once, run
anywhere" feature is particularly useful for developing applications that need to
run on diverse platforms.
2. Strong Community and Ecosystem: Java has a vast ecosystem of libraries,
frameworks, and tools supported by a large community of developers. This makes
it easier to find solutions to problems, get support, and collaborate with other
developers.
13 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
JDK in Java
14 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
JDK contains:
• Java Runtime Environment (JRE),
• An interpreter/loader (Java),
• A compiler (javac),
• An archiver (jar) and many more.
The Java Runtime Environment in JDK is usually called Private Runtime because it is
separated from the regular JRE and has extra content. The Private Runtime in JDK
contains a JVM and all the class libraries present in the production environment, as well
as additional libraries useful to developers, e.g, internationalization libraries and the IDL
libraries.
15 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
• OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,
• Azul Systems Zing: efficient and low latency JDK for Linux os,
• Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,
• IBM J9 JDK: for AIX, Linux, Windows, and many other OS,
• Amazon Corretto: the newest option with the no-cost build of OpenJDK and
long-term support.
16 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
The Java Virtual Machine (JVM) is a crucial component of the Java Runtime
Environment (JRE) and the Java Development Kit (JDK).
17 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
2. Run time data area: This is the memory resource used by JVM and it is divided
into five parts —
a) Method area: Method area stores class code and method code.
b) Heap: The objects are created on heap.
c) Java stacks: Here the Java methods are executed. A Java stack contains
frames. On each frame, a separate method is executed.
d) Program counter registers: The program counter registers store memory
address of the instruction to be executed by the microprocessor.
e) Native method stacks: Here native methods (e.g. C/C++ programs) are
executed. Native method is a function, which is written in other languages.
18 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
2. Platform Independence: One of the key features of JVM is its ability to provide
platform independence. Since Java bytecode is executed by the JVM rather than
directly by the underlying operating system, Java programs can run on any device or
platform that has a compatible JVM implementation. This "write once, run
anywhere" capability is a major advantage of Java.
3. Memory Management: The JVM manages memory allocation and deallocation
dynamically. It includes a garbage collector that automatically identifies and
removes objects that are no longer needed, thus helping to prevent memory leaks and
improve overall memory efficiency.
6. Monitoring and Management: JVM offers tools and APIs for monitoring and
managing Java applications. Developers can use tools like JConsole, Visual VM, and
Java Mission Control to monitor JVM performance, analyze memory usage, and
troubleshoot issues in real-time.
JRE in Java
Java Runtime Environment (JRE) is an open-access software distribution that has a Java
class library, specific tools, and a separate JVM. In Java, JRE is one of the interrelated
components in the Java Development Kit (JDK).
It is the most common environment available on devices for running Java programs.
Java source code is compiled and converted to Java bytecode. If you want to run this
bytecode on any platform, you need JRE. The JRE loads classes check memory access
and get system resources. JRE acts as a software layer on top of the operating system.
Components of Java JRE
The components of JRE are mentioned below:
• Integration libraries include Java Database Connectivity (JDBC)
• Java Naming, Interface Definition Language (IDL)
• Directory Interface (JNDI)
• Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP)
• Remote Method Invocation (RMI)
• Scripting
20 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Working of JRE
Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact
with each other to create a sustainable runtime environment that enables Java-based
applications to run seamlessly on any operating system. The JRE runtime
architecture consists of the following elements as listed:
1. ClassLoader
2. ByteCode verifier
3. Interpreter
Now let us briefly about them as follows:
• ClassLoader: Java ClassLoader dynamically loads all the classes necessary to
run a Java program. Because classes are only loaded into memory whenever
they are needed, the JRE uses ClassLoader will automate this process when
needed. During the initialization of the JVM, three classLoaders are loaded:
• Bootstrap class loader
• Extensions class loader
• System class loader
21 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
• Bytecode Verifier: The bytecode checker ensures the format and precision of
Java code before passing it to the interpreter. If the code violates system
integrity or access rights, the class is considered corrupt and will not load.
• Interpreter: After loading the byte code successfully, the Java interpreter
creates an object of the Java virtual machine that allows the Java program to run
natively on the underlying machine.
How does JRE work with JVM?
JRE has an object of JVM with it, development tools, and library classes.
// Java class
class Jre {
// Main driver method
public static void main(String[] args) {
// Print statement
22 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
[Link]("Jre");
}
}
Once you write your Java program, we must save it with a file name with
a “.java” extension.
Then after we Compile our program. The output of the Java compiler is byte code which
is a platform-independent code. After compiling, the compiler generates a .class file that
contains the byte code. Bytecode is platform-independent that runs on all devices which
contain Java Runtime Environment (JRE)
• JVM: JVM stands for Java Virtual Machine. JVM is used for running Java
[Link] applications are called WORA (Write Once Run Anywhere). This
means a programmer can develop Java code on one system and can expect it to
run on any other Java-enabled system without any adjustment. This is all possible
because of JVM.
• JRE: JRE stands for Java Runtime Environment. JRE is made up of class
libraries.
• JDK: JDK stands for Java Development Kit. JDK contains the JRE with
compiler, interpreter, debugger, and other tools. It provides features to run as well
as develop Java Programs.
Java Environment
• Byte code files, which are very compact, are easily transported through a
distributed system like the Internet.
• The compiled Java code (resulting byte code) will be executed at run time.
Java programs can be written and executed in two ways —
• Stand-alone application (A general-purpose utility program)
• Applet which runs on a web browser (Example: Google Chrome or Mozilla
Firefox)
A Java program is a collection of one or more Java classes. A Java source file can contain
more than one class definition and has a .java extension.
Each class definition in a source file is compiled into a separate class file. The name of
this compiled file is comprised of the name of the class with .class as an extension.
To create our Java source code, you can use any editor (Notepad++) or we can use an
IDEs like Eclipse or NetBeans.
[Link]
24 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
A class is nothing but a blueprint or a template for creating different objects which
defines its properties and behaviours.
An object is an instance of a class created using a new operator. The new operator
returns a reference to a new instance of a class. This reference can be assigned to a
reference variable of the class. The process of creating objects from a class is
called instantiation. An object encapsulates state and behavior.
26 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
An object reference (or reference) provides a handle to an object that is created and
stored in memory. In Java, objects can only be manipulated via references, which can
be stored in variables.
Java class objects exhibit the properties and behaviors defined by its class. A class can
contain fields (i.e. variables) and methods (i.e. functions) to describe the behavior of an
object.
Methods are nothing but members of a class that provide a service for an object or
perform some business logic. Java fields and method names are case sensitive. Current
states of a class’s corresponding object are stored in the object’s instance fields. Methods
define the operations that can be performed in Java programming.
A class has the following general syntax:
<class modifiers> class <class name> <extends clause> <implements clause>
//extends or implements clause is optional
{
// Dealing with Classes (Class body)
<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}
Example 1
Below is an example of Objects and Classes related to the Rectangle class that
defines two fields namely length and breadth. The class also contains two methods
namely inputData() and computeArea().
[Link]
27 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
class Rectangle {
//fields
int length, breadth;
//method 1
void inputData(int l, int b) {
length = l;
breadth = b;
}
//method 2
int computeArea() {
return length * breadth;
}
}
public class AreaTest {
28 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Java Objects
When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class.
29 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
But the values of those attributes, i.e. the state are unique for each object. A single class
may have any number of instances.
Ways to Create an Object of a Class
1. Using new keyword
It is the most common and general way to create an object in Java.
Example:
// creating object of class Test
Test t = new Test();
2. Using [Link](String className) method
There is a pre-defined class in [Link] package with name Class. The forName(String
className) method returns the Class object associated with the class with the given
string name. We have to give a fully qualified name for a class. On calling the new
Instance() method on this Class object returns a new instance of the class with the given
string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)[Link]("[Link]").newInstance();
30 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
De-serialization is a technique of reading an object from the saved state in a file. Refer
to Serialization/De-Serialization in Java
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = [Link]();
Java Constructors
[Link]
public class Cube {
int length;
int breadth;
int height;
Cube() {
length = 10;
breadth = 10;
height = 10;
}
32 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Each time an object is created using a new() keyword, at least one constructor (it could
be the default constructor) is invoked to assign initial values to the data members of
the same class. Rules for writing constructors are as follows:
• The constructor(s) of a class must have the same name as the class name in which
it resides.
• A constructor in Java can not be abstract, final, static, or Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
Primarily there are three types of constructors in Java are mentioned below:
• Default Constructor((No-Argument Constructor)
• Parameterized Constructor
• Copy Constructor
boolean b;
public static void main(String[] args) {
// calls default constructor
Main obj = new Main();
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
34 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Then, we copy each field of the input object into the new instance:
public class Employee {
private int id;
private String name;
35 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed
in your application. In Java, there 4 types of access specifiers.
• public: It is accessible in all classes in your application.
36 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Advantage of Method
• Code Reusability
• Code Optimization
37 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Access Specifies
In Java, the access to classes, constructors, methods and fields are regulated
using access modifiers i.e. a class can control what information or data can be
accessible by other classes.
Actually there are three access modifiers in Java,
namely public, private and protected.
Java uses these access modifiers to help us set the level of access we want for classes as
well as the fields, methods and constructors in our classes.
A member has also package or default accessibility when no accessibility modifier is
specified. So, there are four access specifiers in
• public: It is accessible in all classes in your application.
• protected: It is accessible within the class in which it is defined and in its
subclass/es
• private: It is accessible only within the class in which it is defined.
• default: It is declared/defined without using any modifier. It is accessible within
the same class and package within which its class is defined.
39 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Visibility Specifiers
Static Members
The class basically contains two sections. One declares variable and other declare
methods.
These variable and methods are called instance variable and instance methods, this
because every time the class is instantiated, a new copy of each of them is created.
These are accessed using objects with dot operator.
But if we want to define a member that is common to all the objects and accessed
without using the particular object.
That is member belong to the class as a whole rather than the objects created from the
class. Such members can be created as follows:
static int count;
static int max(int x, int y);
The static keyword indicates that a variable belongs to the class itself rather than to any
particular instance of the class.
This means that there is only one copy of the variable, which is shared by all instances
of the class.
Since these members are associated with class itself rather than the individual objects,
these are also known as class variable and class methods.
40 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Static variable is used when we want to have a variable common to all instance of the
class.
Java creates only one copy for static variable which can be even if the class is never
actually instantiated.
Static methods can also be called without using the objects. They are also available for
use by other classes.
Methods that are of general utility but do not directly affect an instance of the class are
usually declared as class methods.
class Mathop
{
static float mul(float x, float y)
{
return x*y;
}
}
class Mathapp
{
public static void main(String args[])
{
float a = [Link](4.0,5.0);
[Link](“a=”+a);
}
}
Static methods has several restrictions:
1. It can only call other static methods.
2. It can only access static data.
3. It can not refer this and super in any way.
41 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Final Members
Making a method final ensures that the functionality defined in this method will never
be altered in any way. Similarly, the value of a final variable can never be changed. Final
variables behave like class variables and they do not take any space on individual objects
of the class.
Final Classes
Sometimes we may like to prevent a class being further subclasses for security reasons.
A class that cannot be subclassed is called a final class.
To disallow a method from being overridden, specify final as a modifier at the start of
its declaration. Methods declared as final cannot be overridden.
This can be used in java by using final as follows:
final class Aclass
{
}
final class Bclass extends Someclass
{
42 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
Any attempt to inherit these classes will cause an error and the compiler will not allow
it.
DATA TYPES
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 boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
• Integers This group includes byte, short, int, and long, which are for whole
valued signed numbers.
• Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
• Characters This group includes char, which represents symbols in a character
set, like letters and numbers.
43 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
• Boolean This group includes boolean, which is a special type for representing
true/false values.
Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers.
Many other Computer languages, including C/C++, support both signed and unsigned
integers.
Name Width(Bits) Range Default Value
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square
root, or transcendentals such as sine and cosine, result in a value whose precision
requires a floating-point type. Their width and ranges are shown here:
Name Width(Bits) Range Default Value
Characters:
The char data type is a single 16-bit Unicode character. Java uses the Unicode system
not the ASCII code System. Its value-range lies between '\u0000' (or 0) to '\uffff' (or
65,535 inclusive).The char data type is used to store characters.
The value of a char variable is a single character such as A, *, x, or a space character.
The value can also be a special character such a tab or a carriage return or one of the
many Unicode characters that come from different languages.
44 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Literals in Java
A name for a constant value is called a literal. A literal is what we have to type in a
program to represent a value.
// Here 100 is a constant/literal.
int x = 100;
Integer Literals
Integer literals are sequences of digits. There are four types of integer literals:
45 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
1. Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It
may have a positive (+) or negative (-) Note that between numbers commas and non-
digit characters are not permitted. For example, 5678, +657, -89, etc.
int decVal = 26;
2. Octal Integer: It is a combination of number have digits from 0 to 7 with a leading
0. For example, 045, 026,
int octVal = 067;
3. Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as
hexadecimal integers. It may also include a character from a to f or A to F that
represents numbers from 10 to 15, respectively. For example, 0xd, 0xf,
int hexVal = 0x1a;
4. Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can
create binary literals in Java SE 7 and later). Prefix 0b represents the Binary
system. For example, 0b11010.
Real Literals
The numbers that contain fractional parts are known as real literals. We can also
represent real literals in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals
Java supports some special backslash character literals known as backslash literals.
They are used in formatted output. For example:
\n: It is used for a new line
\t: It is used for horizontal tab
\b: It is used for blank space
\v: It is used for vertical tab
\a: It is used for a small beep
\r: It is used for carriage return
\': It is used for a single quote
\": It is used for double quotes
46 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.
String Literals
String literal is a sequence of characters that is enclosed between double quotes ("")
marks. It may be alphabet, numbers, special characters, blank space, etc. For example,
"Jack", "12345", "\n", etc.
Floating Point Literals
The vales that contain decimal are floating literals. In Java, float and double primitive
types fall into floating-point literals. Keep in mind while dealing with floating-point
literals.
o Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc.
It is a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to write D or
d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.
Floating:
1. float length = 155.4f;
Decimal:
1. double interest = 99658.445;
Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and
1. For example, true, 0, etc.
1. boolean isEven = true;
Null Literals
47 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Null literal is often used in programs as a marker to indicate that reference type object
is unavailable. The value null may be assigned to any variable, except variables of
primitive types.
1. String stuName = null;
2. Student age = null;
Variables in Java:
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java:
local, instance and static.
1. Local variables are declared in a method, constructor, or block. When a method
is entered, an area is pushed onto the call stack. This area contains slots for each
local variable and parameter. When the method is called, the parameter slots are
initialized to the parameter values. When the method exits, this area is popped off
the stack and the memory becomes available for the next called method.
Parameters are essentially local variables which are initialized from the actual
parameters. Local variables are not visible outside the method.
2. Instance variables are declared in a class, but outside a method. They are also
called member or field variables.
When an object is allocated in the heap, there is a slot in it for each instance
variable value. Therefore an instance variable is created when an object is created
and destroyed when the object is destroyed. Visible in all methods and
constructors of the defining class, should generally be declared private, but may
be given greater visibility.
3. Class / static variables are declared with the static keyword in a class, but outside
a method. There is only one copy per class, regardless of how many objects are
created from it. They are stored in static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
48 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
A variable can be used in a program only if it has first been declared. A variable
declaration statement is used to declare one or more variables and to give them names.
A simple variable declaration takes the form:
type-name variable-name-or-names;
Ex: double x, y;
Operators in Java
Java Operators
In Java programming, operators are used to perform operations on operands (i.e.
variables and values).
Java categorizes the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
49 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
3. Relational operators
4. Logical operators
5. Bit-wise operators
6. Conditional Operators
7. Instance of operators
1. Arithmetic Operators:
These operators are used with numeric values to perform common mathematical
operations.
Operator Meaning Example
+ Add two operands x+y
– Subtract right operand from the left x–y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into x/y
float)
% Modulus – remainder of the division of left operand by x%y
the right
++ Increment – Increases the value of a variable by 1 x++
50 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Relational Operators:
These operators are used to compare two values.
Logical Operators:
These operators are used to combine conditional statements.
Operator Meaning Example
&& Logical AND — True if both the operands are true x && y
|| Logical OR — True if either of the operands is true x || y
! Logical NOT — True if operand is false (complements the !x
operand)
Bit-wise Operators:
These operators are used to compare binary numbers.
For example, in the table below, let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
Operator Meaning Example
& Bit-wise AND x& y = 0 (0000 0000)
51 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Conditional Operators:
The Conditional operator is the only ternary operator (operator that takes three
arguments) in Java. The operator evaluates the first argument and, if true, evaluates the
second argument. If the first argument evaluates to false, then the third argument is
evaluated. The conditional operator is the expression equivalent of the if-else statement.
condition ? if true : if false
//[Link]
public class ConditionalOperatorsDemo {
public static void main(String[] args) {
int a = 10, b = 12;
boolean c = a > b ? true : false;
[Link]("c = " + c);
}
}
Output:
c = false
instance of operator
The instance of the operator is used for type checking. It can be used to test if an object
is an instance of a class, a subclass, or an interface. General format-
object instance of class/subclass/interface
52 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
1. if statement
We should use the if statement if we want to execute some code only if a specified
condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Example 1.
//[Link]
public class DecisionTest01 {
if(a > b) {
[Link](a + " is bigger than " + b);
53 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
}
}
Output:
20 is bigger than 10
2. if-else statement
If we want to execute some code if a condition is true and another code if the condition
is not true, use the if-else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example 2.
//[Link]
public class DecisionTest02 {
Output:
10 is an even number.
if(a > b) {
[Link]("a is bigger than b.");
}
else if(a < b) {
[Link]("a is smaller than b.");
55 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
else {
[Link]("a and b are equal.");
}
}
}
Output:
a and b are equal.
4. switch-case statement
We should use the switch-case statement if we want to select one of many blocks of
code to be executed.
Syntax
switch(choice)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
case 3:
execute code block 3
break;
default:
execute code if choice is different
break;
}
This is how it works: First we have a single expression choice (most
often int or char type variable is used), that is evaluated once. The value of the
expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. We
use break statement to prevent the code from running into the next case automatically.
56 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Example 4
//[Link]
public class DecisionTest04 {
switch(choice) {
case 1:
[Link]("hello");
break;
case 2:
[Link]("hi");
break;
case 3:
[Link]("welcome");
break;
default:
[Link]("bye");
break;
}
}
}
Output:
welcome
switch(choice) {
57 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
case "hello":
[Link]("hello");
break;
case "hi":
[Link]("hi");
break;
default:
[Link]("bye");
break;
}
Output:
bye
Java Loops are used to execute the same block of code a specified number of times or
while a specified condition is true.
Very often when we write code, we want the same block of code to run over and over
again in a row. Instead of adding several almost equal lines in a code we can use loops
to perform a repetitive task like this.
In Java there are mainly three different kinds of loops:
• while loop – loops through a block of code while a specified condition is true.
• do-while loop – a variant of the while loop which will always be executed at least
once, even if the condition is false, because the code is executed before the
condition is tested.
• for loop – loops through a block of code a specified number of times
Besides this, there are two other variations of for loop — labeled for
loop and enhanced for loop.
58 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
//code to be executed
Example 1.
[Link]
public class LoopTest01 {
The do…while loop is a variant of the while loop. This loop will always execute a block
of code at least once, and then it will repeat the loop as long as the specified condition
is true. This loop will always be executed at least once, even if the condition is false,
because the code is executed before the condition is tested. As the condition is checked
at the end of the loop, it is also called exit controlled loop.
Syntax
do {
//code to be executed
} while (condition);
Example 2.
See the program below.
[Link]
public class LoopTest02 {
60 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Example 3.
The example below defines a loop that starts with i=1. The loop will continue to run as
long as i is less than, or equal to 5. The value of i will increase by 1 each time the loop
runs.
[Link]
public class LoopTest03 {
61 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Here,
• array - an array or a collection
• item - each item of array/collection is assigned to this variable
• dataType - the data type of the array/collection
// print array elements
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
}
}
}
Example 2: Sum of Array Elements
// Calculate the sum of all elements of an array
class Main {
public static void main(String[] args) {
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
63 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Arrays
Types of Arrays
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. Obtaining an array
is a two-step process.
First, we must declare a variable of the desired array type.
64 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Second, we must allocate the memory to hold the array, using new, and assign it to the
array variable. Thus, in Java, all arrays are dynamically allocated.
To create an array, we first must create an array variable of the desired type.
The general form of a one dimensional array declaration is:
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element
type determines the data type of each element that comprises the array. Thus, the
element type for the array determines what type of data the array will hold.
Although this declaration establishes the fact that var_name is an array variable, no
array actually exists.
To link var_name with an actual, physical array of integers, we must allocate one using
new and assign it to var_name, new is a special operator that allocates memory.
The general form of new as it applies to one-dimensional arrays appears as follows:
Var_name = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and array-var is the array variable that is linked to the array.
That is, to use new to allocate an array, we must specify the type and number of elements
to allocate.
The elements in the array allocated by new will automatically be initialized to zero (for
numeric types), false (for boolean), or null (for reference types).
It is possible to combine the declaration of the array variable with the allocation of the
array itself, as shown here:
type var_name[] = new type[size];
65 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Array initialization:
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
66 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Java strictly checks to make sure we do not accidentally try to store or reference values
outside of the range of the array. The Java run-time system will check to be sure that all
array indexes are in the correct range.
If we try to access elements outside the range of the array (negative numbers or numbers
greater than the length of the array), we will cause a run-time error.
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if
length of the array in negative, equal to the array size or greater than the array size while
traversing the array.
Here is one more example that uses a one-dimensional array. It finds the average of a
set of numbers.
class Average
{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
[Link]("Average is " + result / 5);
}
}
67 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0
and not 1.
Initialize a 2d array in Java?
68 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
69 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Here, the square brackets follow the type specifier, and not the name of the array
variable. For example, the following two declarations are equivalent:
Java strings
70 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
71 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
72 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
StringBuffer class
StringBuffer class is a mutable class unlike the String class which is immutable. The
objects of StringBuffer class can be changed dynamically both in terms of its length and
content. StringBuffer objects are preferred when heavy modification of character strings
is involved (appending, inserting, deleting, modifying etc). Strings can be obtained from
StringBuffer objects. Since the StringBuffer class does not override the equals() method
from the Object class, contents of StringBuffer objects should be converted to String
objects for string comparison.
Class methods
Following is the list of built-in functions available in this class −
[Link]. Method & Description
1 StringBuffer append()
This method appends the given string argument to the sequence.
2 appendCodePoint()
This method appends the string representation of the codePoint argument to
this sequence.
3 capacity()
This method returns the current capacity.
4 charAt()
This method returns the char value in this sequence at the specified index.
5 chars()
The Java StringBuffer chars() method is used to map a StringBuffer to a
stream of int zero-extending char values.
6 codePointAt()
This method returns the character (Unicode code point) at the specified
index.
7 codePointBefore()
This method returns the character (Unicode code point) before the specified
index.
73 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
8 codePointCount()
This method returns the number of Unicode code points in the specified text
range of this sequence.
9 codePoints()
This method is used to return the Unicode values representing the current
object.
10 compareTo()
This method compares two StringBuffer instances in a lexicographical
manner.
11 delete()
This method removes the characters in a substring of this sequence.
12 deleteCharAt()
This method removes the char at the specified position in this sequence.
13 ensureCapacity( )
This method ensures that the capacity is at least equal to the specified
minimum.
14 getChars()
Characters are copied from this sequence into the destination character array
dst.
15 indexOf()
This method returns the index within this string of the first occurrence of
the specified substring.
16 insert()
This method inserts the string representation of the given argument into this
sequence.
17 lastIndexOf()
This method returns the index within this string of the rightmost occurrence
of the specified value.
18 length()
This method returns the length (character count).
19 offsetByCodePoints()
This method returns the index within this sequence that is offset from the
given index by codePointOffset code points.
74 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
20 replace()
This method replaces the characters in a substring of this sequence with
characters in the specified String.
21 reverse()
This method causes this character sequence to be replaced by the reverse of
the sequence.
22 setCharAt()
Character at the specified index is set to ch.
23 setLength()
This method sets the length of the character sequence.
24 subSequence()
This method returns a new character sequence that is a subsequence of this
sequence.
25 substring()
This method returns a new String that contains a subsequence of characters
currently contained in this character sequence.
26 toString()
This method returns a string representing the data in this sequence.
27 trimToSize()
This method attempts to reduce storage used for the character sequence.
[Link] :
75 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Inheritance
superclass: The class from which the subclass is derived is called a superclass (also a
base class or a parent class).
Constructors cannot be inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass.
In Java, inheritance is implemented by the process of extension.
76 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Types of inheritance:
The inheritance allows subclass to inherit all the variables and methods of their parent
classes. Inheritance may take different forms:
1. Single Inheritance (Only one super class)
2. Multiple Inheritance (Several super classes)
Java does not directly implement the multiple inheritance , this concept is
implemented by interfaces in java
3. Hierarchical Inheritance (One super class, many Sub class)
4. Multilevel Inheritance (Derived from derived class)
5. Hybrid Inheritance
77 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Defining a Subclass:
A subclass is defined as follows:
class subclassname extends superclassname
{
variable declaration;
method declaration;
}
The keyword extends signifies that the property of the superclassname are extended to
the subclassname.
The subclass will now contain its own variables and methods as well as those of the
superclass. This kind of situation occurs when we want to add some more properties to
existing class without actually modifying it.
1. Single Inheritance
When a subclass is derived from its parent class then this mechanism is known as single
inheritance. In case of single inheritance there is only a sub class and its parent class. It
is also called one level inheritance. The pictorial representation of single inheritance is
as follows:
int y;
int getValue(int p, int q)
{
x = p;
y = q;
return(0);
}
void Show()
{
[Link](x);
}
}
class B extends A // subclass B inheriting getValue A
{
public static void main(String args[ ])
{
A a = new A();
[Link](5,10);
[Link]();
}
void display() {
[Link]("I am in B");
}
}
79 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Multilevel Inheritance
When a subclass is derived from a derived class then this mechanism is known as the
multilevel inheritance. The derived class is called the subclass or child class for its
parent class and this parent class works as the child class for its just above ( parent )
class. Multilevel inheritance can go up to any number of level. The pictorial
representation of multilevel inheritance is as follows:
class A
{
int x;
int y;
int get(int p, int q)
{
x = p;
y = q;
return(0);
}
void show()
{
[Link](x);
80 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
}
class B extends A //subclass B inheriting from A
{
void Showb()
{
[Link]("I am in B ");
}
}
class C extends B //subclass C inheriting from B
{
void Display()
{
[Link]("I am in C");
}
public static void main(String args[])
{
A a = new A();
[Link](5,10);
[Link]();
}
}
81 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance.
Class A acts as the superclass for classes B, C, and D.
class A
{
public void methodA()
{
[Link]("method of Class A");
}
}
class B extends A
{
public void methodB()
{
[Link]("method of Class B");
}
82 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
class C extends A
{
public void methodC()
{
[Link]("method of Class C");
}
}
class D extends A
{
public void methodD()
{
[Link]("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
[Link]();
[Link]();
[Link]();
83 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
}
Hybrid Inheritance
Subclass Constructor:
The subclass constructor is used to construct the variable of both the subclass and the
superclass. The subclass constructor uses the keyword super invoke the constructor
method of the superclass.
The keyword super is used subject to the following conditions.
• super may only be used within the subclass constructor method.
• The call to the superclass constructor must appear as the first statement within
the subclass constructor.
• The parameter in the super call must match the order and type of the instance
variable declared in the super class.
84 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Methods Overriding:
Method defined in superclass is inherited by its subclass and is used by the objects
created by the subclass.
Method inheritance enables us to define and use methods repeatedly in subclasses
without having to define the methods again in subclass.
However, there may be occasions when we want an object to respond to the same
methods but have different behaviour when that method is called.
That means we should override the methods defined in the superclass. This is possible
by defining a method in subclass that has the same name, same arguments and same
return type as method in superclass. Then when method is called, the method defined
in the subclass is invoked and executed instead of the one in the superclass. This known
as overriding.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
Method overriding is used for runtime polymorphism
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display()
{
[Link](“Super x=”+x);
85 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void display()
{
[Link](“Super x=”+x);
[Link](“Sub y=”+y);
}
}
class OverrideTest
{
public static void main(String argss[])
{
Sub s1 = new Sub(100,200);
[Link]();
}
}
86 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Method Overloading
If a class has multiple methods having same name but parameters of the method should
be different is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Method overloading in java is based on the number and type of the parameters passed
as an argument to the methods.
We cannot define more than one method with the same name, Order, and type of the
arguments. It would be a compiler error.
The compiler does not consider the return type while differentiating the overloaded
method.
But we cannot declare two methods with the same signature and different return
types. It will throw a compile-time error. If both methods have the same parameter
types, but different return types, then it is not possible.
Java can distinguish the methods with different method signatures. i.e. the methods
can have the same name but with different parameters list (i.e. the number of the
parameters, the order of the parameters, and data types of the parameters) within the
same class.
It is used when object is required to perform similar tasks but using different input
parameters. Java matches up the method and then then the number and type of
parameters to decide which one of the definitions to execute. This Process is known as
polymorphism.
Different number of arguments:
public class Multiplier
{
87 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
{
return a * b;
}
As by making a method final we ensure that the method is not redefined in a subclass.
That is, the method can never be subclassed.
Java allows us to do something that is exactly opposite to this. That is, we can indicate
that a method must always be redefined in a subclass, thus making overriding
compulsory.
This is done using the modifier keyword abstract in the method definition.
Sometimes we will want to create a superclass that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
Such a class determines the nature of the methods that the subclasses must implement.
89 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
In this case, we want some way to ensure that a subclass does, indeed, override all
necessary methods. Java’s solution to this problem is the abstract method.
We can require that certain methods be overridden by subclasses by specifying the
abstract type modifier.
These methods are sometimes referred to as subclasser responsibility because they have
no implementation specified in the superclass.
Thus, a subclass must override them—it cannot simply use the version defined in the
superclass.
To declare an abstract method, use this general form:
Any class that contains one or more abstract methods must also be declared
abstract.
To declare a class abstract, we simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with the new operator.
Such objects would be useless, because an abstract class is not fully defined. Also, we
cannot declare abstract constructors, or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be declared abstract itself.
abstract class Shape
{
..........
..........
abstract void draw( );
..........
..........
}
90 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
91 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Note:
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of
the method.
Example
abstract class
{
}
Abstract Method
A method which is declared as abstract and does not have implementation is known as
an abstract method.
Example
abstract void display(); //no method body and abstract
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run()
92 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
{
[Link]("running safely");
}
}
class Car
{
public static void main(String args[])
{
Bike obj = new Honda();
[Link]();
}
}
running safely
93 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Interface in Java
Java does not support multiple inheritance. That is, classes in Java cannot have more
than one superclass. For instance, a definition like:
class A extends B extends C
{
.........
.........
}
is not permitted in Java. However, it could not overlook the importance of multiple
inheritance. A large number of real-life applications require the use of multiple
inheritance whereby we inherit methods and properties from several, distinct classes.
Since C++ like implementation of multiple inheritance proves difficult and adds
complexity to the language, Java provides an alternate approach known as interfaces to
support the concept of multiple inheritance.
Although a Java class cannot be a subclass of more than one superclass, it can
implement more than one interface, thereby enabling us to create classes that build
upon other classes without the problems created by multiple inheritance.
Using the keyword interface, we can fully abstract a class’ interface from its
implementation.
That is, using interface, we can specify what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and, as a
general rule, their methods are declared without any body.
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
94 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, we can say that interfaces can have abstract methods and variables.
It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Interfaces are designed to support dynamic method resolution at run time.
There are mainly three reasons to use interface. They are given below.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
Declaring an interface
An interface is basically a kind of class. Like classes, interfaces contain methods and
variables but with a major difference. The difference is that interfaces define only
abstract methods and final fields. This means that interfaces do not specify any code to
implement these methods and data fields contain only constants. Therefore, it is the
responsibility of the class that implements an interface to define the code for
implementation of these methods.
Syntax:
The syntax for defining an interface is very similar to that for defining a class.
The general form of an interface definition is:
interface InterfaceName
{
variables declaration;
methods declaration;
}
95 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Note that all variables are declared as constants. Methods declaration will contain only
a list of methods without any body statements.
Implementing Interfaces:
To implement an interface, a class must provide the complete set of methods required
by the interface.
However, each class is free to determine the details of its own implementation. By
providing the interface keyword, Java allows us to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and then
create the methods required by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.
Note : Prior to JDK 8, an interface could define only “what,” but not “how.”
JDK 8 changes this. Beginning with JDK 8, it is possible to add a default
implementation to an interface method.
Thus, it is now possible for interface to specify some behaviour.
Java 8 has introduced the concept of default methods which allow the interfaces to have
methods with implementation without affecting the classes that implement the interface.
96 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
// default method
default void show()
{
[Link](“Default Method Executed”);
}
}
Static Methods:
The interfaces can have static methods as well which is similar to static method of
classes.
// A simple Java program to TestClassnstrate static
// methods in java
interface TestInterface
{
// abstract method
public void square (int a);
// static method
static void show()
{
[Link]("Static Method Executed");
}
}
99 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Example
interface A
{
void display();
}
class B implements A
{
public void display()
{
[Link]("Hello");
}
}
class MB
{
100 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Interface Example:
In this example, the interface A has only one method. Its implementation is provided by
B and C classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used
by someone else. The implementation part is hidden by the user who uses the interface.
interface A
{
void display();
}
class B implements A
{
public void display()
{
[Link]("Display method in B class");
}
}
class C implements B
{
void display();
}
interface B
{
void show();
}
class C implements A,B
{
public void display()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}
}
class MainClass
{
public static void main(String args[])
{
C obj = new C();
[Link]();
[Link]();
}
}
103 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
Output:
Hello
Welcome
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface A
{
void display();
}
interface B extends A
{
void show();
}
class C implements B
{
public void display()
{
[Link]("Hello");
104 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
}
public void show()
{
[Link]("Welcome");
}
}
Class MainClass
{
public static void main(String args[])
{
C obj = new C();
[Link]();
[Link]();
}
}
Output:
Hello
Welcome
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given
below.
JAVA - PACKAGES:
Packages are used in Java, in-order to avoid name conflicts and to control access of
class, interface and enumeration etc.
A package can be defined as a group of similar types of classes, interface, enumeration
or sub-package. Using package, it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other files.
Benefits of using package in java:
1. Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2. Java package provides access protection.
3. Java package removes naming collision.
4. This package can be provide reusability of code.
5. We can create our own package or extend already available package.
Java Packages: Types:
• Built-in Package: Existing Java package
For example [Link], [Link] ,[Link] etc.
• User-defined-package: Java package created by user to categorize their project's
classes and interface.
We must first declare the name of the package using the package keyword followed by
a package name.
This must be the first statement in a Java source file (except for comments and white
spaces). Then we define a class, just as we normally define a class.
package firstPackage; // package declaration
public class FirstClass // class definition
{
........
........ (body of class)
........
}
Here the package name is firstPackage. The class FirstClass is now considered a part
of this package. This listing would be saved as a file called [Link], and located
in a directory named firstPackage. When the source file is compiled, Java will create a
.class file and store it in the same directory.
Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form:
package packagename;
2. Define the class that is to be put in the package and declare it public.
108 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the [Link] file in the subdirectory created.
5. Compile the file. This creates a .class file in the subdirectory.
Simply include a package command followed by name of the package as the first
statement in java source file.
package mypackage;
public class student
{
Statement;
}
The above statement will create a package name mypackage in the project directory.
Java uses file system directories to store packages. For example the .java file for any
class we define to be part of mypackage package must be stored in a directory called
mypackage.
Important points about package:
A package is always defined as a separate folder having the same name as the package
name.
• Store all the classes in that package folder.
• All classes of the package which we wish to access outside the package must be
declared public.
• All classes within the package must have the package statement as its first line.
• All classes of the package must be compiled before use (So that they are error free)
Example of Java packages:
package mypack;
public class Simple
{
109 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
This is just like compiling a normal java program. If we are not using any IDE, we
need to follow the steps given below to successfully compile your packages:
1. java -d directory javafilename
For example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. We can
use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. If we want to keep the package within the same directory, we can use . (dot).
we need to use fully qualified name e.g. [Link] etc to run the class.
To Compile: javac -d . [Link]
To Run: java [Link]
Output: Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
In Eclipse IDE, there are the following steps to create a package in java. They are as
follows:
1. Right-click on the ‘src’ folder as shown in the below screenshot.
Using a Package
We will create some simple programs that will use classes from other packages.
The listing below shows a package named package1 containing a single class ClassA.
package package1;
public class ClassA
{
public void displayA()
{
[Link]("Class A");
}
}
This source file should be named [Link] and stored in the subdirectory package1
as stated earlier. Now compile this java file. The resultant [Link] will be stored
in the same subdirectory.
111 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
import [Link];
class PackageTest1
{
public static void main(String args[ ])
{
ClassA objectA = new ClassA();
[Link]();
}
}
During the compilation of [Link] the compiler checks for the file
[Link] in the package1 directory for information it needs, but it does not actually
include the code from [Link] in the file [Link]. When the
PackageTest1 program is run, Java looks for the file [Link] and loads it
using something called class loader. Now the interpreter knows that it also needs the
code in the file [Link] and loads it as well.
Consider another package named package2
package package2;
public class ClassB
{
protected int m = 10;
public void displayB()
{
[Link]("Class B");
[Link]("m = " + m);
}
}
import [Link];
import package2.*;
class PackageTest2
{
public static void main(String args[ ])
{
ClassA objectA = new ClassA();
ClassB objectB = new ClassB();
[Link]();
[Link]();
}
}
Output:
Class A
Class B
m = 10
When we import multiple packages it is likely that two or more packages contain classes
with identical names. Example:
package pack1;
public class Teacher
{..........}
public class Student
{..........}
package pack2;
113 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
import pack1.*;
import pack2.*;
Student student1; // create a student object
Since both the packages contain the class Student, compiler cannot understand which
one to use and therefore generates an error. In such instance, we have to be more explicit
about which one we intend to use.
import pack1.*;
import pack2.*;
[Link] student1; // OK
[Link] student2; // OK
Teacher teacher1; // No problem
Courses course1; // No problem
package p1;
public class A
{
// body of A
}
The package p1 contains one public class by name A. Suppose we want to add another
class B to this package. This can be done as follows:
Steps to Add Class B to Package p1:
1. Define the class and make it public.
2. Place the package statement:
package p1; before the class definition as follows:
package p1;
public class B
{
// body of B
}
3. Store this as [Link] file under the directory p1.
4. Compile [Link]. This will create a [Link] file and place it in the directory p1.
Since a Java source file can have only one class declared as public, we cannot put two
or more public classes together in a .java file. This is because of the restriction that the
file name should be the same as the name of the public class with .java extension.
If we want to create a package with multiple public classes in it, we may follow the
following steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source
files are stored.
3. Create classes that are to be placed in the package in separate source files and
declare the package statement
package packagename;
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When
completed, the package would contain .class files of all the source files.
Hiding Classes
When we import a package using asterisk (*), all public classes are imported. However,
we may prefer to “not import” certain classes. That is, we may like to hide these classes
from accessing from outside of the package. Such classes should be declared “not
public”. Example:
package p1;
public class X // public class, available outside
{
// body of X
}
import p1.*;
X objectX; // OK: class X is available here
Y objectY; // Not OK: Y is not available
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1. Using packagename.*:
If we use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
117 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
package pack;
public class A
{
public void msg()
{
[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output: Hello
3. Using fully qualified name:
If we use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But we need to use fully qualified name every time
when we are accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.
Example of package by import fully qualified name:
119 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");}
}
//save by [Link]
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
[Link]();
}
}
Output: Hello
Note: If we import a package, subpackages will not be imported.
If we import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, we need to import the
subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize
the package further.
Let's take an example, Sun Microsystem has defined a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized
the java package into subpackages such as lang, net, io etc. and put the Input/Output
related classes in io package, Server and ServerSocket classes in net packages and so
on.
package [Link];
class Simple
{
public static void main(String args[])
{
[Link]("Hello subpackage");
}
}
To Compile: javac -d . [Link]
To Run: java [Link]
Output: Hello subpackage
Naming Conventions :
In order to avoid packages with the same name, we follow some naming conventions:
• we define our package names in all lower case.
• package names are period-delimited.
• names are also determined by the company or organization that creates them.
Companies use their reversed Internet domain name to begin their package names— if
the domain name of IBM is [Link]. We can declare the package by reversing
the domain like this:
package [Link];
With programmers worldwide writing classes and interfaces using the Java
programming language, it is likely that many programmers will use the same name for
different types.
The fully qualified name of each Rectangle class includes the package name.
That is, the fully qualified name of the Rectangle class in the graphics package
is [Link], and the fully qualified name of the Rectangle class in
the [Link] package is [Link].
There are situations where we need frequent access to static final fields (constants) and
static methods from one or two classes. Prefixing the name of these classes over and
over can result in cluttered code. The static import statement gives us a way to import
the constants and static methods that we want to use so that we do not need to prefix the
name of their class.
The [Link] class defines the PI constant and many static methods, including
methods for calculating sines, cosines, tangents, square roots, maxima, minima,
exponents, and many more. For example,
public static final double PI
= 3.141592653589793;
public static double cos(double a)
{
...
}
Ordinarily, to use these objects from another class, we prefix the class name, as follows.
double r = [Link]([Link] * theta);
we can use the static import statement to import the static members of [Link]
so that we don't need to prefix the class name, Math. The static members of Math can
be imported either individually:
import static [Link];
or as a group:
import static [Link].*;
Once they have been imported, the static members can be used without qualification.
For example, the previous code snippet would become:
double r = cos(PI * theta);
Obviously, we can write our own classes that contain constants and static methods that
we use frequently, and then use the static import statement. For example,
import static [Link].*;
In Java, JAR stands for Java ARchive, whose format is based on the zip format.
A JAR file is essentially a compressed archive that contains the compiled Java class
files, associated metadata, and resources required by a Java application or library. It
124 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department
simplifies the process of distributing Java programs by providing a single file that
encapsulates all the necessary components.
How to Create a JAR File in Java
To create a JAR file in Java, you can use the jar command-line tool that comes bundled
with the Java Development Kit (JDK). Let's take a look at an example of creating a JAR
file:
• Create a directory named "myproject" and navigate to it.
• Compile the Java source files: javac com/example/*.java
• Create a manifest file named "[Link]" with the following content:
The basic format of the command for creating a JAR file is:
jar cf jar-file input-file(s)
The options and arguments used in this command are:
• The c option indicates that you want to create a JAR file.
• The f option indicates that we want the output to go to a file rather than to stdout.
• jar-file is the name that we want the resulting JAR file to have. we can use any
filename for a JAR file. By convention, JAR filenames are given a .jar extension,
though this is not required.
• The input-file(s) argument is a space-separated list of one or more files that we
want to include in our JAR file. The input-file(s) argument can contain the
wildcard * symbol. If any of the "input-files" are directories, the contents of those
directories are added to the JAR archive recursively.
The c and f options can appear in either order, but there must not be any space between
them.
This command will generate a compressed JAR file and place it in the current directory.
The command will also generate a default manifest file for the JAR archive.
The [Link] file will be compressed using the code above and stored in
[Link].
If the command prompt is open in the current directory, we can specify the file name
directly; otherwise, we must provide an absolute path.
View a JAR File in Java
Java offers a mechanism to view the contents of a JAR file, much like how a file system
displays the contents of a folder.
The JAR file's contents are displayed when the following command is run.
jar tf jar-filename
Here’s an example:
jar tf [Link]
Extracting a JAR File
To extract the contents of a JAR file in Java, you can use the jar command or any file
archiving tool. Here's an example of extracting a JAR file using the jar command:
jar xf jar-filename
The files we want to extract can be specified explicitly.
jar xf [Link] [Link]
Only the [Link] will be extracted from the [Link] by the
aforementioned command.
We could also extract the entire JAR file.
jar xf [Link]
The -cp in the aforementioned command indicates the classpath, which will run the
designated class file. The jar tool will not raise a main manifest attribute error without
the -cp parameter.
Consider that SampleJavaClass is the main class in our scenario and that the command
to run our jar file is
java -cp [Link] SampleJavaClass
The [Link] file will be run using the aforementioned command.
2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing
the following command:
3. > SET CLASSPATH=.;c:\myProject\classes;d:\tomcat\lib\[Link]
Instead of using the CLASSPATH environment variable, you can also use the
command-line option -classpath (or -cp) of the javac and java commands, for example,
> java –classpath c:\myProject\classes [Link].project1.subproject2.MyClass3