0% found this document useful (0 votes)
4 views128 pages

Java Unit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, detailing key principles such as classes, objects, methods, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism. It also introduces Java as a programming language, its features, types of applications, and the Java platforms available. Additionally, it highlights the reasons for learning Java, emphasizing its platform independence, strong community support, and robust standard library.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views128 pages

Java Unit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, detailing key principles such as classes, objects, methods, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism. It also introduces Java as a programming language, its features, types of applications, and the Java platforms available. Additionally, it highlights the reasons for learning Java, emphasizing its platform independence, strong community support, and robust standard library.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Ajay Kumar Garg Engineering College, Ghaziabad

Information Technology Department

Introduction

Object Oriented Programming (OOPs) Concept in Java


As the name suggests, Object-Oriented Programming or OOPs refers to languages that
use objects in programming, they use objects as a primary source to implement what is
to happen in the code.
Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism etc. in programming. The main aim of OOP is to bind together
the data and the functions that operate on them so that no other part of the code can
access this data except that function.
OOPS concepts are as follows:
1. Class
2. Object
3. Method and method passing
4. Pillars of OOPs
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Compile-time polymorphism
• Runtime polymorphism

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

1.` Compile-time Polymorphism (Method Overloading):


• Achieved by defining multiple methods with the same name but different
parameter lists within the same class.
• The method to be executed is determined at compile time.
2. Runtime Polymorphism (Method Overriding):
• Achieved when a subclass provides a specific implementation of a method
already defined in its superclass.
• The method to be executed is determined at runtime, based on the object's actual
type

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;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](2, 3)); // Output: 5
[Link]([Link](2.5, 3.5)); // Output: 6.0
[Link]([Link](1, 2, 3)); // Output: 6
}
}

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");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


void sound() {
[Link]("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal a; // Reference of superclass

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.

Types of Java Applications

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

Java as an object-oriented programming language has several interesting features. They


are listed below.

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

5. Several dangerous features of C and C++ eliminated


• No memory pointers
• No preprocessor
• Array index limit checking

6. Automatic Memory Management


Automatic garbage collection – memory management handled by JVM.

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

3. Object-Oriented Programming (OOP): Java is an object-oriented


programming language, which encourages modular, reusable, and maintainable
code. This makes it suitable for building large-scale, complex applications.
4. Robust Standard Library: Java comes with a rich standard library that provides
functionalities for various tasks, such as networking, I/O operations, database
connectivity, and more. This reduces the need for developers to write code from
scratch for common tasks.
5. Security: Java has built-in security features, such as bytecode verification, class
loader architecture, and runtime security checks, which help in creating secure
applications. Additionally, Java's sandboxing mechanism enables running
untrusted code securely.
6. Scalability: Java is known for its scalability, making it suitable for both small
projects and large enterprise applications. Its ability to handle a high volume of
users and transactions makes it a popular choice for mission-critical systems.
7. Performance: While Java may not be as fast as lower-level languages like C or
C++, it offers good performance through Just-In-Time (JIT) compilation and
optimization techniques. Additionally, the JVM's garbage collection mechanism
manages memory efficiently, reducing the risk of memory leaks.
8. Backward Compatibility: Java maintains backward compatibility, ensuring
that code written in older versions of Java remains compatible with newer
versions. This reduces the effort required to migrate applications to newer Java
releases.

JDK in Java

The Java Development Kit (JDK) is a cross-platformed software development


environment that offers a collection of tools and libraries necessary for developing Java-
based software applications and applets. It is a core package used in Java, along with
the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment).
Note: If you are only interested in running Java programs on our machine then we can
easily do it using Java Runtime Environment. However, if we would like to develop a
Java-based software application then along with JRE we may need some additional
necessary tools, which is called JDK.

14 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

JDK=JRE+ Development Tools

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.

Most Popular JDKs:


• Oracle JDK: the most popular JDK and the main distributor of Java11,

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.

Important Components of JDK


Below there is a comprehensive list of mostly used components of Jdk which are very
useful during the development of a java application.
Component Use
javac Java compiler converts source code into Java bytecode
java The loader of the java apps.
javap Class file disassembler,
javadoc Documentation generator,
jar Java Archiver helps manage JAR files.
appletviewer Debugging of Java applets without a web browser,
xjc Accepts an XML schema and generates Java classes,
apt Annotation-processing tool,
jdb Debugger,
jmc Java Mission Control,
JConsole Monitoring and Management Console,
pack200 JAR compression tool,
extcheck Utility tool to detects JAR file conflicts,
idlj IDL-to-Java compiler,
keytool The keystore manipulating tool,

16 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

jstatd jstat daemon (experimental)


jstat JVM statistics monitoring tool
jshell jshell introduced in java 9.
jstack Prints Java stack traces(experimental)
jrunscript Java command-line script shell.
jhat Java Heap Analysis Tool (experimental)
jpackage Generate self-contained application bundles.
javaws Web Start launcher for JNLP applications,
javah C header and stub generator,
jarsigner jar signing and verification tool
jinfo configuration information(experimental)
javafxpackager Package and sign JavaFX applications

Java Virtual Machine (JVM):

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

What JVM is and why it's important:

The different components of JVM are described below.


1. Class loader sub system: This class loader sub system of JVM performs three tasks

a) It loads the .class file into memory.
b) It verifies the byte code instructions.
c) It allots memory required for the program.

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

3. Native method interface: Native method interface is a program that connects


native methods libraries (C/C++ header files) with JVM for executing native methods.
4. Native method library: It holds the native libraries information.
5. Execution engine: Execution engine contains interpreter and Just-in-time (JIT)
compiler, which covert byte code into machine code. JVM uses optimization technique
to decide which part of the code to be interpreted and which part of the code to be used
with JIT compiler. The HotSpot represents the block of code to be executed by the JIT
compiler.

Java Virtual machine perform following functions:


1. Execution Environment: The JVM provides an execution environment for Java
bytecode. When we compile Java source code, it gets translated into bytecode, which
is a platform-independent intermediate representation of the program. The JVM then
executes this bytecode on various operating systems and hardware platforms.

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.

4. Optimization: JVM includes various optimization techniques to improve the


performance of Java applications. One of the most significant optimizations is Just-
In-Time (JIT) compilation, where frequently executed bytecode is compiled into
native machine code for faster execution.

5. Security: JVM provides a secure execution environment for Java applications. It


includes features such as bytecode verification, class loading restrictions, and
runtime access controls, which help prevent unauthorized access and malicious code
execution.
19 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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.

7. Integration with Native Code: Although Java is primarily a high-level, platform-


independent language, JVM allows integration with native code written in languages
like C and C++. This enables developers to leverage existing native libraries and take
advantage of platform-specific features when necessary.

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)

Difference between JVM, JRE, and JDK.

• 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

Java environment is composed of a number of system components. We use these


components at compile time to create the Java program and at run time to execute the
program. Java achieves its independence by creating programs designed to run on the
Java Virtual Machine (JVM) rather than any specific computer system —
• After we write a Java program, we use a compiler that reads the statements in the
program and translates them into a machine independent format called bytecode.
23 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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

Java Source Code

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

public class HelloWorld {

public static void main(String[] args) {


[Link](”Hello World”);
} //End of main()
} //End of HelloWorld Class

Java Program Structure and the main() method:


A class named “HelloWorld” containing a simple main() method within it. The keyword
class specifies that we are defining a class. The name of a public class is spelled exactly
as the name of the file (Case Sensitive).
All Java programs begin execution with the method named main(). The main() method
that gets executed by the JVM has the following signature:
public static void main(String args[])
Declaring this method as public means that it is accessible from outside the class so that
the JVM can find it when it looks for the program to start executing it.
The keyword ‘static‘ denotes that the main() method is a direct member of the class to
which it belongs (here the class name is HelloWorld). It is necessary that the method is
declared with return type ‘void‘ (i.e. no value is returned from the method).
The main() method contains a String argument array that can contain the command line
arguments. The brackets ‘{‘ and ‘}’ mark the beginning and ending of the class.
The program contains a line “[Link](”Hello World”);” that tells the
computer to print out on one line of text namely “Hello World“. The semi-colon ‘;’ ends
the line of code. The double slashes ‘//’ are used for comments that can be used to
describe what a source code is doing. Everything to the right of the slashes on the same
line does not get compiled, as they are simply the comments in a program.
Java main() method declarations :—

class MainExample1 {public static void main(String[] args) {}}


class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}
All the three valid main methods shown above accept a single String array argument.
25 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Compiling and Running an Application


To compile and run the program we need the JDK distributed by Oracle Corporation.
The JDK contains documentation, examples, installation instructions, class libraries and
packages, and tools.
We must save our source code with a .java extension. The name of the file must be the
name of the public class contained in the file.

Steps for saving, compiling and running a Java program:-

Step 1: Save the program with .java Extension.


Step 2: Compile the file from command prompt by typing: javac <filename>.
Step 3: Successful compilation, results in creation of .class containing byte code
Step 4: Execute the file by typing: java <filename without extension>

Steps to run a Java Program

Programming Structures in Java

Defining Classes in Java:

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 {

public static void main(String[] args) {


Rectangle rect; //object reference of Rectangle class
rect = new Rectangle(); //creating object of Rectangle class
[Link](20, 10); //calling method 1 using object reference
int area = [Link](); //calling method 2 using object reference
[Link]("AREA = " + area);
}
}

28 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Components of Java Classes

In general, class declarations can include these components, in order:


1. Modifiers: A class can be public or has default access Class keyword: class
keyword is used to create a class.
2. Class name: The name should begin with an initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
5. Body: The class body is surrounded by braces, { }.

Java Objects

An object in Java is a basic unit of Object-Oriented Programming and represents real-


life entities. Objects are the instances of a class that are created to use the attributes and
methods of a class. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State: It is represented by 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 with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Note: When we create an object which is a non primitive data type, it’s always
allocated on the heap memory.

Declaring Objects (Also called instantiating a class)

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();

3. Using clone() method


clone() method is present in the Object class. It creates and returns a copy of the
object.
// creating object of class Test
Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)[Link]();
4. Deserialization

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

A constructor in Java is basically used to perform automatic initialization of an object.


It has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type (not even void), since constructors
never return a value.
A Java constructor cannot be abstract, static, final, and synchronized.
Constructors may include parameters of different types. When the constructor is
invoked using the new operator, the types must match those that are specified in the
constructor definition.
Java provides a default constructor which takes no parameter and performs no special
action or initialization, when no explicit constructors are provided.
Constructor parameters provide us with a way to provide parameters for the
initialization of an object.

[Link]
public class Cube {
int length;
int breadth;
int height;

public int getVolume() {


return (length * breadth * height);
31 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Cube() {
length = 10;
breadth = 10;
height = 10;
}

Cube(int l, int b, int h) {


length = l;
breadth = b;
height = h;
}

public static void main(String[] args) {


Cube cube1, cube2;
cube1 = new Cube();
cube2 = new Cube(10, 20, 30);
[Link]("Volume of Cube1 is : " + [Link]()
+ " square units.");
[Link]("Volume of Cube2 is : " + [Link]()
+ " square units.");
}

32 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Note: If a class defines an explicit constructor, it no longer has a default constructor to


set the state of the objects. If such a class requires a default constructor, its
implementation must be provided. Any attempt to call the default constructor will be a
compile time error if an explicit default constructor is not provided in such a case.

When Java Constructor is called?

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.

Types of Constructors in Java

Primarily there are three types of constructors in Java are mentioned below:
• Default Constructor((No-Argument Constructor)
• Parameterized Constructor
• Copy Constructor

1. Default Constructor in Java


A constructor that has no parameters is known as default the constructor. A default
constructor is invisible.
And if we write a constructor with no arguments, the compiler does not create a default
constructor. It is taken out. It is being overloaded and called a parameterized constructor.
The default constructor changed into the parameterized constructor. But Parameterized
constructor can’t change the default constructor.
class Main {
int a;
33 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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);
}
}

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
A Java constructor can also accept one or more parameters. Such constructors are known
as parameterized constructors (constructors with parameters).
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}

public static void main(String[] args)


{
// call constructor by passing a single value

34 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Main obj1 = new Main("Java");


Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

4. Copy Constructor in Java


A copy constructor is used to create an exact copy of an object. It takes an object of
the same class as a parameter and copies its attributes.
Unlike other constructors copy constructor is passed with another object which copies
the data available from the passed object to the newly created object.
How to Create a Copy Constructor
To create a copy constructor, we can first declare a constructor that takes an object
of the same type as a parameter:
public class Employee {
private int id;
private String name;

public Employee(Employee employee) {


}
}

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

public Employee(Employee employee) {


[Link] = [Link];
[Link] = [Link];
}
}

What is Method in Java?

A method in Java is a block of code or a collection of statements to perform specific


actions or operations and return the result to the caller. It allows code reusability.
So, WE need to write code only once and use it multiple times without re-writing it
again and again. Moreover, Java methods allow easy modification and improve code
readability by simply adding or removing a section or chunk of code.
In Java methods, you can add parameters to a method, and it will be executed only when
called or invoked. Each method in Java must be a part of a specific class which is
different from other languages, such as C++, C programming, and Python
programming.

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

• 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.
2. The return type: The data type of the value returned by the method or void if does
not return a value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded
by their data type, within the enclosed parenthesis. If there are no parameters, you must
use empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations. It is Optional in syntax.

Advantage of Method
• Code Reusability
• Code Optimization

37 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Types of Methods in Java

There are two types of methods in Java:


1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library method
or built-in method. We can directly use these methods just by calling them in the
program at any point.
2. User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement

There are 2 Ways to Create Method in Java


There are two ways to create a method in Java:
1. Instance Method(Non Static Method): Instance methods are the members of a class
object. Access the instance data using the object name. Declared inside a class.
Syntax:
// Instance Method
void method_name(){
body // instance area
}
2. Class Method (Static Method): While, the class methods are the members of the
class only. Access the static data using class name. Declared inside class
with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area
38 |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

Java Non-Access Modifiers


There are some non-access modifiers in Java. They are
namely, native, final, abstract, static, volatile, transient, strictfp, synchronized
etc. We can modify a class declaration using the keyword final, abstract, or strictfp.
These modifiers are in addition to whatever access control is on the class, so we could;
for example, declaring a class as both public and final. But we can’t always mix non-
access modifiers. We are free to use strictfp in combination with final, for example, but
we must never, ever, mark a class as both final and abstract.

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

Final Variables and Methods

All methods and variables can be overridden by default in subclasses. If we wish to


prevent the subclasses from overriding the members of the superclass, we can declare
them as final using the keyword final as a modifier. Example:

final int SIZE = 100;


final void showstatus() { .......... }

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

byte 8 –128 to 127 0


short 16 –32,768 to 32,767 0
int 32 –2,147,483,648 to 2,147,483,647 0
long 64 –9,223,372,036,854,775,808 to 0L
9,223,372,036,854,775,807

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

float 32 Upto 7 decimal digits 0.0f


double 64 Upto 16 decimal digits 0.0d

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

When a character is typed into a program, it must be surrounded by single quotes.


for example: ’A’, ’*’, or ’x’

Boolean Data Type:


Boolean data type represents only one bit of information either true or false which is
intended to represent the two truth values of logic and Boolean algebra, but the size of
the boolean data type is virtual machine-dependent.
Values of type boolean are not converted implicitly or explicitly (with casts) to any other
type.

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;

Types of Literals in Java


There are the majorly four types of literals in Java:
1. Integral Literals
2. Floating-Point Literals
3. Char Literals
4. String Literals
5. Boolean Literals
6. Null Literals

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

–– Decrement – Decreases the value of a variable by 1 x––

Java Assignment Operators


Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a
variable called x:
int x = 10;
In many cases, the assignment operator can be combined with other operators to build
a shorter version of the statement called a Compound Statement. For example, instead
of a = a+5, we can write a += 5.

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.

Operator Meaning Example


> Greater that – True if left operand is greater than the right x>y
< Less that – True if left operand is less than the right x<y
== Equal to – True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to – True if left operand is greater than x >= y
or equal to the right
<= Less than or equal to – True if left operand is less than or x <= y
equal to the right

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

| Bit-wise OR x | y = 14 (0000 1110)


~ Bit-wise NOT ~x = -11 (1111 0101)
^ Bit-wise XOR x ^ y = 14 (0000 1110)
>> Bit-wise right shift x>> 2 = 2 (0000 0010)
<< Bit-wise left shift x<< 2 = 40 (0010 1000)

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

Decision Control Statements


In Java programming, decision control statements perform different computations or
actions depending on whether a specific condition holds true or false. Based on it,
certain decisions are to be made. They are also called conditional statements.
We have the following decision control statements in Java:
• if statement – we use this statement if we want to execute some code only if a
specified condition is true
• if-else statement – we use this statement if we want to execute some code if the
condition is true and another code if the condition is false
• if-else nesting statement – we use this statement if we want to select one of many
blocks of code to be executed
• switch-case statement – we use this statement if we want to select one of many
blocks of code to be executed

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 {

public static void main(String[] args) {


int a = 20, b = 10;

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 {

public static void main(String[] args) {


int n = 10;

// Testing for even or odd number


if(n%2==0) {
[Link](n + " is an even number.");
}
else {
54 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

[Link](n + " is an odd number.");


}
}
}

Output:
10 is an even number.

3. if-else nesting statement


We should use the if-else nesting if we want to select one of many sets of lines to
execute.
Syntax
if (condition1) {
code to be executed if condition1 is true
}
else if (condition2) {
code to be executed if condition2 is true
}
else {
code to be executed if condition1 and condition2 are not true
}
Example 3.
//[Link]
public class DecisionTest03 {

public static void main(String[] args) {


int a = 30, b = 30;

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 {

public static void main(String[] args) {


int choice = 3;

switch(choice) {
case 1:
[Link]("hello");
break;

case 2:
[Link]("hi");
break;

case 3:
[Link]("welcome");
break;

default:
[Link]("bye");
break;
}
}
}
Output:
welcome

The switch-case statement with String


Java SE 7 has modified the “switch-case” statement to support String also.
String choice = "test";

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

Loop Control Statements

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

1) The while loop


The while loop is used when we want the loop to execute and continue executing while
the specified condition is true. As the condition is checked at the beginning of the loop,
it is also called entry controlled loop.
Syntax
while (condition) {

//code to be executed

Example 1.
[Link]
public class LoopTest01 {

public static void main(String[] args) {


int i = 1;
while (i <= 5) { //while loop
[Link]("The number is " + i);
i = i + 1;
}
}
}
Output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

2) The do..while Loop


59 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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 {

public static void main(String[] args) {


int i = 1;
do { //do-while loop
[Link]("The number is " + i);
i = i + 1;
} while (i <= 5);
}
}
Output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

60 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

3) The for Loop


The for loop is used when we know in advance how many times the code should run.
Syntax
for (initialization part; condition part; re-initialization part)
{
//code to be executed
}

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 {

public static void main(String[] args) {


//for loop
for (int i = 1; i <= 5; i++) {
[Link]("The number is " + i);
}
}
}
Output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

61 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

For-each loop in Java

In Java, the for-each loop is used to iterate through elements


of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
for-each Loop Syntax
The syntax of the Java for-each loop is:
for(dataType item : array)
{
...
}

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};

// for each loop


for (int number: numbers) {
[Link](number);
62 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

}
}
}
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;

// iterating through each element of the array


for (int number: numbers) {
sum += number;
}

[Link]("Sum = " + sum);


}
}

63 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Arrays

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


Arrays of any type can be created and may have one or more dimensions. A specific
element in an array is accessed by its index. Arrays offer a convenient means of grouping
related information.
Arrays of any type can be created and may have one or more dimensions.

There are three main features of an array:


1. Dynamic allocation: In arrays, the memory is created dynamically, which reduces
the amount of storage required for the code.
2. Elements stored under a single name: All the elements are stored under one name.
This name is used any time we use an array.
3. Occupies contiguous location: The elements in the arrays are stored at adjacent
positions. This makes it easy for the user to find the locations of its elements.

Types of Arrays

There are two types of array.


o One- Dimensional Array
o Multidimensional Array

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.

Define an Array in Java

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:

Arrays can be initialized when they are declared.


An array initializer is a list of comma-separated expressions surrounded by curly braces.
The commas separate the values of the array elements. The array will automatically be
created large enough to hold the number of elements we specify in the array initializer.
There is no need to use new.
For example, to store the number of days in each month, the following code creates an
initialized array of integers:
class AutoArray
{
public static void main(String args[])
{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
[Link]("April has " + month_days[3] + " days.");
}
}
We can also initialize arrays in Java, using the index number. For example,
// declare an array
int[] age = new int[5];

// 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);
}
}

Declaration, Instantiation and Initialization of Java Array


class Testarray1
{

67 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

public static void main(String args[])


{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}
}
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.
To declare a multidimensional array variable, specify each additional index using
another set of square brackets.
For example, the following declares a two dimensional array.
int[][] a = new int[3][4];

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

Here is how we can initialize a 2-dimensional array in Java.


int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
class MultidimensionalArray {
public static void main(String[] args) {

// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

// calculate the length of each row


[Link]("Length of row 1: " + a[0].length);
[Link]("Length of row 2: " + a[1].length);
[Link]("Length of row 3: " + a[2].length);
}
}
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;

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

In java String, is not a primitive type. Nor is it simply an array of characters.


Rather, String defines an object.
The String type is used to declare string variables. We can also declare arrays of strings.
A quoted string constant can be assigned to a String variable. A variable of type String
can be assigned to another variable of type String.
Strings in Java are class objects and implemented using three classes,
namely, String, StringBuffer, and StringBuilder. A Java string is an instantiated
object of the above classes.
Unlike C, a Java string is not a character array and is not NULL terminated.
String class
String class is immutable, i.e., once created and initialized, cannot be changed on the
same reference. A [Link] class is final which implies no class can extend it.
This class differs from other classes, one difference being that the String objects can be
used with the “+=“ and “+” operators for concatenation.
Two useful methods for String objects are equals( ) and substring( ). The equals( )
method is used for testing whether two Strings contain the same value. The substring( )
method is used to obtain a selected portion of a String.
1.1 String object creation
String objects may be declared and created using “new” operator as follows:
String str = new String("Sample String"); // Option 1: using "new" operator
A string object can also be created using a string literal enclosed inside double quotes
as shown:
String str = "Sample String"; // Option 2: using string literal
Since a string literal is a reference, it can be manipulated like any other String reference.
The reference value of a string literal can be assigned to another String reference.

70 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

No. Method Description


1 char charAt(int index) It returns char value for the
particular index
2 int length() It returns string length
3 static String format(String format, Object... It returns a formatted string.
args)
4 static String format(Locale l, String format, It returns formatted string with
Object... args) given locale.
5 String substring(int beginIndex) It returns substring for given
begin index.
6 String substring(int beginIndex, int It returns substring for given
endIndex) begin index and end index.
7 boolean contains(CharSequence s) It returns true or false after
matching the sequence of char
value.
8 static String join(CharSequence delimiter, It returns a joined string.
CharSequence... elements)
9 static String join(CharSequence delimiter, It returns a joined string.
Iterable<? extends CharSequence>
elements)
10 boolean equals(Object another) It checks the equality of string
with the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified
string.
13 String replace(char old, char new) It replaces all occurrences of
the specified char value.

71 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

14 String replace(CharSequence old, It replaces all occurrences of


CharSequence new) the specified CharSequence.
15 static String equalsIgnoreCase(String It compares another string. It
another) doesn't check case.
16 String[] split(String regex) It returns a split string
matching regex.
17 String[] split(String regex, int limit) It returns a split string
matching regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char
value index.
20 int indexOf(int ch, int fromIndex) It returns the specified char
value index starting with given
index.
21 int indexOf(String substring) It returns the specified
substring index.
22 int indexOf(String substring, int fromIndex) It returns the specified
substring index starting with
given index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase
using specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase
using specified locale.
27 String trim() It removes beginning and
ending spaces of this string.
28 static String valueOf(int value) It converts given type into
string. It is an overloaded
method.

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

The [Link] class is mutable sequence of characters. This provides an


API compatible with StringBuffer, but with no guarantee of synchronization.

75 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Object Oriented Programming

Inheritance

Reusability is one of the important features of object-oriented programming and it can


be achieved through inheritance.
Java supports the concepts of inheritance. Inheritance can be defined as the process
where one object acquires the properties of another. 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
the new class from the existing class.
In doing this, we can reuse the fields and methods of the existing class without rewriting
them again.
subclass: A class that is derived from another class is called a subclass (also a derived
class, extended class, or child class).
A subclass inherits all the members (fields, methods, and nested classes) from its
superclass.

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

Importance of Java inheritance

Implementation of inheritance in Java provides the following benefits:


• Inheritance minimizes the complexity of a code by minimizing duplicate code. If
the same code has to be used by another class, it can simply be inherited from
that class to its sub-class. Hence, the code is better organized.
• The efficiency of execution of a code increases as the code is organized in a
simpler form.
• The concept of polymorphism can be used along with inheritance.

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:

class A // super class A


{
int x;
78 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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

In simple terms we can say that Hybrid inheritance is a combination


of Single and Multiple inheritance. A hybrid inheritance can be achieved in the java
in a same way as multiple inheritance can be!! Using interfaces.

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
{

public int multiply(int a, int b)

87 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

{
return a * b;
}

public int multiply(int a, int b, int c)


{
return a * b * c;
}
}

Different Types of arguments:

public class Multiplier {

public int multiply(int a, int b) {


return a * b;
}

public double multiply(double a, double b) {


return a * b;
}
}

Both types of method overloading:


public class Multiplier {
88 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

public int multiply(int a, int b) {


return a * b;
}

public int multiply(int a, int b, int c) {


return a * b * c;
}

public double multiply(double a, double b) {


return a * b;
}
}

Abstract classes and Methods in Java

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:

abstract type name(parameter-list);

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

A Simple demonstration of abstract.


abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
[Link]("This is a concrete method.");
}
}
class B extends A {
void callme()
{
[Link]("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[]) {
B b = new B();
[Link]();
[Link]();
}
}

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.

Uses of Java interface

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.

static final type VariableName = Value;


return-type methodName1(parameter-list);

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

// A simple program to Test Interface default


// methods in java
interface TestInterface
{
// abstract method
public void square(int a);

// default method
default void show()
{
[Link](“Default Method Executed”);
}
}

class TestClass implements TestInterface


{
// implementation of square abstract method
public void square(int a)
{
[Link](a*a);
}

public static void main(String args[])


{
TestClass d = new TestClass();
[Link](4);
97 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

// default method executed


[Link]();
}
}
Default methods are also known as defender methods or virtual extension methods.

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");
}
}

class TestClass implements TestInterface


{
98 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

// Implementation of square abstract method


public void square (int a)
{
[Link](a*a);
}

public static void main(String args[])


{
TestClass d = new TestClass();
[Link](4);

// Static method executed


[Link]();
}
}

99 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Relationship between classes and interfaces

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

public static void main(String args[])


{
B obj = new B();
[Link]();
}
}
Output:
Hello

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
{

101 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

public void display()


{
[Link]("display method in C class");
}
}
class MainClass
{
public static void main(String args[])
{
D obj=new D();
[Link]();
}
}
Multiple inheritance by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it


is known as multiple inheritance.
interface A
{
102 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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.

105 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

106 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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.

107 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

How to Create a package

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

public static void main(String args[])


{
[Link]("Welcome to package");
}
}

How to compile Java packages:

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

How to run java package program:

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.

How to Create Package in Eclipse IDE?

110 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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.

2. Go to New option and then click on package.


3. A window dialog box will appear where you have to enter the package name
according to the naming convention and click on Finish button. Once the package
is created, a package folder will be created in your file system where you can
create classes and interfaces.

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);
}
}

112 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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

public class Courses


{..........}
public class Student
{..........}

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

Adding a Class to a Package

package p1;
public class A
{
// body of A
}

114 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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.

Now, the package p1 will contain both the classes A and B.


Note: that we can also add a non-public class to a package using the same procedure.

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

115 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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
}

class Y // not public, hidden


{
// body of Y
}
Here, the class Y which is not declared public is hidden from outside of the package p1.
This class can be seen and used only by other classes in the same package. Note that a
Java source file should contain only one public class and may include any number of
non-public classes. We may also add a single non-public class using the procedure
suggested in the previous section.
116 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

import p1.*;
X objectX; // OK: class X is available here
Y objectY; // Not OK: Y is not available

How to access package from another package:

Packages are organised in a hierarchical structure for Example:

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

Example of package that import the packagename.*:


//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello java");}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output: Hello java
2. Using [Link]:
If we import [Link] then only declared class of this package will be
accessible.
Example of package by import [Link]:
//save by [Link]
118 |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.

120 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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

How to send the class file to another directory or drive:


There is a scenario, I want to put the class file of [Link] source file in classes folder
of c: drive.
For example:
//save as [Link]
package mypack;
public class Simple
{

121 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

public static void main(String args[])


{
[Link]("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes [Link]
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java [Link]
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, we can use -classpath switch of java
that tells where to look for class file. For example:
e:\sources> java -classpath c:\classes [Link]
Output: Welcome to package

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.

122 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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

Packages in the Java language itself begin with java. or javax.

The Static Import Statement

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.

123 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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].*;

Creating a JAR File

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.

JAR File in Java Example


jar cvf [Link] [Link]
125 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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]

Running a JAR File in Java


To run a Java application packaged in a JAR file, you can use the Java command
followed by the JAR file name.
Here's an example of running a JAR file:
java -cp jar-filename MainClassName

126 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)


Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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.

CLASSPATH Setting for java Packages:

CLASSPATH: CLASSPATH is an environment variable which is used by Application


ClassLoader to locate and load the .class files. The CLASSPATH defines the path, to
find third-party and user-defined classes that are not extensions or part of Java platform.
Include all the directories which contain .class files and JAR files when setting the
CLASSPATH.
Setting the CLASSPATH in Java is necessary when we want to specify the location of
Java classes that our application needs to run. This is particularly important when our
project consists of multiple packages or external libraries.
Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the
required files.
Here's how we can set the CLASSPATH:

1. CLASSPATH can be set permanently in the environment: In Windows, choose


control panel ⇒ System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System
Variables" (for all the users) or "User Variables" (only the currently login user) ⇒
choose "Edit" (if CLASSPATH already exists) or "New" ⇒ Enter "CLASSPATH" as
the variable name ⇒ Enter the required directories and JAR files (separated by
semicolons) as the value (e.g., ".;c:\myProject\classes;d:\tomcat\lib\[Link]").
Take note that you need to include the current working directory (denoted by '.') in
the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
> SET CLASSPATH
127 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

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

128 |SUDHAKAR DWIVEDI(AP-AKGEC-IT)

You might also like