0% found this document useful (0 votes)
9 views42 pages

Java Unit-2

The document provides an overview of Java programming concepts, focusing on inheritance, Java packages, access specifiers, constructors, method overriding, interfaces, object cloning, inner classes, final classes, and abstract classes. It explains how to create and compile Java packages, the significance of the Object class, and the use of access modifiers. Additionally, it covers the purpose and declaration of interfaces, the cloning process, and the structure of nested classes in Java.

Uploaded by

shailymakhyavya
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)
9 views42 pages

Java Unit-2

The document provides an overview of Java programming concepts, focusing on inheritance, Java packages, access specifiers, constructors, method overriding, interfaces, object cloning, inner classes, final classes, and abstract classes. It explains how to create and compile Java packages, the significance of the Object class, and the use of access modifiers. Additionally, it covers the purpose and declaration of interfaces, the cloning process, and the structure of nested classes in Java.

Uploaded by

shailymakhyavya
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

1

CS - 19 Programming with JAVA

Unit - 2 Inheritance, Java Packages


1. What is Java Packages?

➢ A java package is a group of similar` types of classes,


interfaces and sub-packages.
➢ Package in java can be categorized in two form, built-in
package and user-defined package.
➢ There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
➢ Here, we will have the detailed learning of creating and
using user-defined packages.

Advantages of Java Package

➢ Java package is used to categorize the classes and interfaces so


that they can be easily maintained.
➢ Java package provides access protection.
➢ Java package removes naming collision.

Prepared
Study NotesBy :by-
Bansari
RonakRupareliya
Goda
2

CS - 19 Programming with JAVA

How to create java package


package mypack;
public class J1_createpackage
{
public static void main(String args[]) {
[Link]("Welcome to package”);
}
}
How to compile java package

If you are not using any IDE, you need to follow the syntax
given below:
javac -d directory javafilename
Example : javac —d . J1_createpackage
The -d switch specifies the destination where to put the generated class
file. You can use any directory name like /home (in case of Linux), d:/abc
(in case of windows) etc. If you want to keep the package within the
same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.J 1_createpackage etc to
run the class.
To Compile: javac -d .
J1_createpackage.java To Run: java
mypack. J1_createpackage

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.

Prepared
Study NotesByby-
: Bansari
Ronak Rupareliya
Goda
3

CS - 19 Programming with JAVA

2. Universal Class (Object Class)

➢ The Object class is the parent class of all the classes in java by
default. In other words, it is the topmost class of java.
➢ Every class in Java is directly or indirectly subclass of
the Object class.
➢ Object class is present in [Link] package.
➢ [Link] package is a default package in Java therefore, there is
no need to import it explicitly. i.e. without importing you can access
the classes of this package.
• Note : What is [Link]?

➢ [Link] is one of the built-in packages provided by Java that


contains classes and interfaces fundamental to the design of the
Java programming language. The lang packages contain classes
such as Boolean, Integer, Math, etc., that are considered the
building blocks of a Java program.
➢ [Link] package is a default package in Java therefore, there is
no need to import it explicitly.
➢ i.e. without importing you can access the classes of this package.
➢ Let's take an example, there is getclass() method which returns
name of class of particular object.

Methods of Object class


The 0bject class provides many methods. They are as follows:

Method Description
public final Class getClass() returns the Class class object of this
object. The Class class
can further be used to get the metadata of
this class.

Study Notes
Prepared By by- Ronak
: Bansari Goda
Rupareliya
4

CS - 19 Programming with JAVA

public int hashCode() returns the hashcode number for this


object.
public boolean equals(Object compares the given object to this object.
obj)
protected Object clone() creates and returns the exact copy (clone)
throws of this object.
CloneNotSupportedException
public String tostring() returns the string representation of this
object.
public final void notify() wakes up single thread, waiting on this
object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this
object's monitor.
public final void wait(long causes the current thread to wait
timeout)throws for the specified
InterruptedException milliseconds, until another thread notifies
(invokes notify() or notifyAll() method).
public void wait(long causes the current thread to wait
timeout,int for the specified
nanos)throws milliseconds and nanoseconds,
InterruptedException until another thread notifies
(invokes notify() or notifyAll() method).
public final void causes the current thread to wait, until
wait()throws another thread
InterruptedException notifies (invokes notify() or notifyAll()
method).
protected void finalize()throws is invoked by the garbage collector
Throwable before object is being
garbage collected.

Prepared
Study NotesBy by-
: Bansari
Ronak Rupareliya
Goda
5

CS - 19 Programming with JAVA

3. Access Specifiers
There are two types of specifiers in Java: access modifiers and
non-access modifiers. The access modifiers in Java specifies the
accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
- The private access modifier is specified using the
keyword private.
- For example, we have created two classes A and Simple. A class
contains private data member and private method. We are
accessing these private members from outside the class, so there
is a compile-time error.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do
not specify any access level, it will be the default.
-It provides more accessibility than private. But, it is more restrictive
than protected, and public.
For example, we have created two packages pack and mypack. We
are accessing the A class from outside its package, since A class is
not public, so it cannot be accessed from outside the package.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the
package.
-The protected access modifier is specified using the keyword
protected.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the

Study Notes
Prepared By by- Ronak
: Bansari Goda
Rupareliya
6

CS - 19 Programming with JAVA

package and outside the package.


There are many non-access modifiers, such as static, abstract,
synchronized, native, volatile, transient, etc. Here, we are going to
learn the access modifiers only.
- The public access modifier is specified using the keyword
public.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.
Access within within outside package by outside
Modifier class package subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

4. Constructors in inheritance

➢ It is very important to understand how the constructors get executed in the


inheritance.
➢ In inheritance constructor never get inherited to any child class.
➢ Inheritance means having parent and child class.
➢ Constructor of parent class can not be inherited to child class.
➢ In java, default constructor of parent class will be automatically called
when object of child class is created.
➢ But parameterised constructor will not be called in child class.
➢ Parameterised constructor of parent class will be called in child class by
using super keyword.
➢ In java, default constructor of a parent class called automatically by the
constructor of its child class. That means when we create an object of the
child class, the parent class constructor executed with child class
constructor.

Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
7

CS - 19 Programming with JAVA

5. Method Overriding in Java


➢ If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
➢ In other words, If a subclass provides the specific implementation n of
the method that has been declared by one of its parent class, it is
known as method overriding.
Usage of Java Method Overriding
➢ Method overriding is used to provide the specific implementation n of
a method which is already provided by its superclass.
➢ Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
➢ The method must have the same name as in the parent class
➢ The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).

6. Interface in Java
➢ An interface in Java is a blueprint of a class. It has static constants and
abstract
➢ methods.
➢ The interface in Java is mechanism to achieve abstraction. There
can be onIy abstract methods in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritance in lava.
➢ In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.

Why use Java interface?

➢ There are mainly three reasons to use interface. They are given
below.
o It is used to achieve abstraction.

Study Notes
Prepared By : by- Ronak
Bansari Goda
Rupareliya
8

CS - 19 Programming with JAVA

oBy interface, we can support the functionality of multiple


inheritance.
How to declare an interface?

➢ An interface is declared by using the interface keyword. It provides


total abstraction; means all the methods in an interface are declared
with empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the
methods declared in the interface.

7. Object Cloning in Java

➢ The object cloning is a way to create exact copy of an object. The


clone() method of Object class is used to clone an object.
➢ The [Link] interface must be implemented by the
class whose object clone we want to create. If we don't implement
Cloneable interface, clone() method generates
CloneNotSupportedException.
➢ The clone() method is defined in the Object class. Syntax of the
clone() method is as follows:
➢ protected Object clone() throws CloneNot SupportedException

Why use clone() method ?

➢ The clone() method saves the extra processing task for creating the
exact copy of an object. If we perform it by using the new keyword,
it will take a lot of processing time to be performed that is why we
use object cloning.

Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
9

CS - 19 Programming with JAVA

8. Java Inner Classes (Nested Classes)


➢ Java inner class or nested class is a class that is declared inside the
class or interface.
➢ We use inner classes to logically group classes and interfaces
in one place to be more readable and maintainable.
➢ Additionally, it can access all the members of the outer class, including
private data
members and methods.
Syntax of inner class
class Java_Outer_cIas
{
//code
class Java_lnner_class
{
//code
}
}
Use of Java Inner class

➢ Nested classes represent a particular type of relationship that is


it can access all the members (data members and methods) of
the outer class, including private.
➢ Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
➢ Code Optimization: It requires less code to write.
➢ Sometimes users need to program a class in such a way so that
no other class can access it. Therefore, it would be better if you
include it within other classes.
➢ If all the class objects are a part of the outer object then it is
easier to nest that class inside the outer class. That way all the

Study Notes
Prepared Byby- Ronak
: Bansari Goda
Rupareliya
10

CS - 19 Programming with JAVA

outer class can access all the objects of the inner class.
Types of Nested class:
1) Private Inner Classe
Unlike a "regular" class, an inner class can be private or
protected. If you don't want outside objects to access the inner
class, declare the class as private with private keyword.
Syntax:
Class classname
{
private class classname
{
//code
}
}
2) Static Inner Class
An inner class can also be static, which means that you can
access it without creating an object of the outer class. Declare
class as static with static keyword.
Class classname
{
static class classname
{
//code
}
}
Access Outer Class From Inner Class
One advantage of inner classes, is that they can access
attributes and methods of the outer class:

Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
11

CS - 19 Programming with JAVA

9. Final Class
➢ Final is keyword is a non access modifier.
➢ Final keyword can be applied to class, method and variable.
➢ A class which is declared with the “Final” keyword is known as the final
class.
➢ The final keyword is used to finalize the implementations of the classes,
the methods and the variables used in this class.
➢ When class is declared final then inheritance is not possible for that class
➢ When a method is declared final, method overriding is not possible for
that method.
➢ When a variable is declared final it is converted to constant and and its
value can not be changed.
Syntax:
final class classname
{
//code
}
10. Abstract Class:
➢ A class that is declared using the “abstract” keyword is known as an
abstract class. The main idea behind an abstract class is to
implement the concept of Abstraction. An abstract class can have
both abstract methods(methods without body) as well as the
concrete methods(regular methods with the body). However, a
normal class(non-abstract class) cannot have abstract methods.
11. Normal import and static import
1) Normal import:
➢ Import is a keyword.
➢ Import is used to import packages, classes and interfaces in java.
➢ With import statement we can use class and its members.
➢ Syntax:
import [Link];

Study Notes
Prepared by- Ronak
By : Bansari Goda
Rupareliya
12

CS - 19 Programming with JAVA

or, import package1.package2.*;


➢ An import statement tells the compiler the path of a class or the
entire package.
➢ Class or package is imported with the keyword import.
➢ Import statement tells the compiler that we want to use a class (or
classes) that is defined under a package.
Example: import [Link].*; this will import whole util package and
import [Link]; will import scanner class of util package.
➢ The [Link] package is automatically imported into our code
by Java.
2) Static Import Statement
➢ Static imports will import all static data so that can use without a class name.
➢ A static import declaration has two forms, one that imports a
particular static member which is known as single static import and
one that imports all static members of a class which is known as
a static import on demand.
➢ Static imports introduced in Java5 version.
➢ One of the advantages of using static imports is reducing keystrokes and
re-usability.
➢ For Example: we always use sqrt() method of Math class by using Math
class i.e. [Link](), but by using static import we can access sqrt()
method directly.
➢ Syntax: import static [Link].*;

12. Introduction to Java API packages and IMP classes


What is java API?
➢ A package in Java is used to group related classes. Think of it as a
folder in a file directory. We use packages to avoid name
conflicts, and to write a better maintainable code.
➢ Packages are divided into two categories:
• Built-in Packages (packages from the Java API)

Study Notes
Prepared By by- Ronak
: Bansari Goda
Rupareliya
13

CS - 19 Programming with JAVA

• User-defined Packages (create your own packages)

Built-in Packages
➢ The Java API (Application Programming Interface) is a library of
prewritten classes, that are free to use, included in the Java
Development Environment.
➢ The library contains components for managing input, database
programming, and much more.
➢ The library is divided into packages and classes. Meaning you can
either import a single class (along with its methods and attributes),
or a whole package that contain all the classes that belong to the
specified package.
➢ To use a class or a package from the library, you need to use the import
keyword:
Syntax
Import [Link]; //import a single class
Import package name.*; //import the whole package
User-defined Packages
➢ To create your own package, you need to understand that Java
uses a file system directory to store them. Just like folders on
your computer:
➢ To create a package, use the package keyword.
[Link]
➢ [Link] is one of the built-in packages provided by Java that
contains classes and interfaces fundamental to the design of the
Java programming language.
➢ The lang packages contain classes such as Boolean, Integer,
Math,etc., that are considered the building blocks of a Java
program.
➢ lang package is a default package in Java therefore, there is no

Prepared
Study NotesByby-
: Bansari
Ronak Rupareliya
Goda
14

CS - 19 Programming with JAVA

need to import it explicitly.


➢ i.e. without importing you can access the classes of this package.
[Link]
➢ The [Link] package in Java is a built-in package that contains
various utility classes and interfaces. It provides basic
functionality for commonly occurring use cases.
➢ It contains Java's collections framework, date and time utilities,
string-tokenizer, event-
➢ model utilities, etc.
Java.l/O
➢ Java.l/O (Input and Output) is used to process the input and
produce the output.
➢ Java uses the concept of a stream to make I/O operation fast. The
[Link] package contains all the classes required for input and
output operations.
[Link]
➢ Java programs are built specially to be run on a network. For the
practice of these network applications, a set of classes is provided
under this package.
[Link]
➢ The Abstract Window Toolkit ( AWT ) package in java enables
programmers to create graphical user interface applications.
➢ It contains a number of classes that help to implement common
windows-based tasks,
➢ such as manipulating windows, adding scroll bars, buttons, list
items, text boxes, etc. All the classes are contained in the [Link]
package
➢ All these classes are hierarchically arranged inside the AWT
package in such a manner that each successive level in the

Study Notes
Prepared By by- Ronak
: Bansari Goda
Rupareliya
15

CS - 19 Programming with JAVA

hierarchy adds certain attributes to the GUI application.

i) Components
➢ Component class is the Parent class to all the other classes from
which various GUI elements are realized. It is primary responsible
for affecting the display of a graphic object on the screen. It also
handles the various keyboard and mouse events of the GUI
application.
ii) Container
➢ The Container object contains the other AU components. It
manages the layout and placement of the various AST
components within the container.
➢ The Container provides very important Methods to add or Remove
the Components from the Applet or from any other Window.
iii) Panel
➢ It is a subclass of container and it is the super class of Applet. It
represents a window space on the application's output is displayed.
It is just like a normal window having no border, title

Study Notes by- Ronak Goda


16

CS - 19 Programming with JAVA

bar, menu bar, etc.


➢ A Panel is used for displaying Multiple Windows in a Single Window
and a Panel may have any Layout.
iv) Window
➢ The Window is the layout of the window .Window is also a Sub
Class of a Container and window class creates a top level window.
➢ These are not directly created, for this the subclass of window
name frame is used and dialog are used. This is used for
displaying a Sub Windows from a Main Window.
v) Frame
➢ Frame Class is also a Sub Class of Window Class and frame class
allows to Create a pop- Menus. And Frame Class Provides a
Special Type of Window which has a title bar, menu bar , border.
➢ It supports common window-related events such as close, open,
activate, deactivate, etc.
vii) Button
➢ The Button is one of the most used components in AWT. It is a
component primarily for interaction with the user and a user can
click on a button to achieve an action which is associated with it.
viii) Label
➢ Label is a component used for placing text in a container and is the
easiest component to use. As a label usually shows only a static
String, it doesn't support any way to interaction with the user.

Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
17

CS - 19 Programming with JAVA

ix) Check Boxes


➢ Check Boxes are components that are used to allow user to select
data from a specific set of options only. When a checkbox is
checked, we say that its state is turned ON, otherwise it is termed
as turned OFF.
x) Menu Bars and Menus:
➢ A menu comes with a pull-down list of menu items from which
user can select one at a time.
➢ When a lot of options in different categories exist to be opted by
the user, menus are the
➢ best choice as they take less space on the frame.
➢ A click on the Menultem generates ActionEvent and is handel by
actionlistener.
[Link]
➢ Changing the state of an object is known as an event. For example,
click on button, dragging mouse etc. The [Link] package
provides event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and M ouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
18

CS - 19 Programming with JAVA

ContainerEvent ContainerListener
FocusEvent FocusListener

[Link]
➢ Applet is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and
works at client side.
➢ The [Link] package is a small but important package that
defines the Applet class-- the superclass of all applets. It also
defines the AppletContext and AppletStub interfaces, which are
implemented by web browsers and other applet viewers.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browser on many platforms including Linux,
Windows, Mac os.
Drawback of Applet
➢ Plugin is required at client browser to execute applet.

[Link]
➢ Swing has about four times the number of User Interface [UI]
components as AWT and is part of the standard Java distribution.
➢ By today's application GUI requirements, AWT is a limited
implementation, not quite capable of providing the components
required for developing complex GUI's required in modern
commercial applications.
➢ The AWT component set has quite a few bugs and really does
take up a lot of system resources when compared to equivalent
Swing resources.
➢ Netscape introduced its Internet Foundation Classes [IFC] library
for use with Java.

Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
19

CS - 19 Programming with JAVA

➢ Its classes became very popular with programmers creating GUI's


for commercial applications.
o Swing is a Set Of API ( API- Set Of Classes and Interfaces )
o Swing is Provided to Design Graphical User Interfaces
o Swing is an Extension library to the AWT (Abstract Window Toolkit)
o Swing can be used to build(Develop) The Standalone swing GUI
Apps Also as Servlets And Applets
o It Employs model/view design architecture
o Swing is Entirely written in Java
o Java Swing Components are Platform-independent And The
Swing Components are lightweight
o Swing Supports a Pluggable look and feels And Swing provides
more powerful components such as tables, lists, Scrollpanes,
Colourchooser, tabbedpane, etc
o Further Swing Follows MVC.

13. [Link] Package Classes


13.1. Math Class
➢ Math Class methods helps to perform the numeric operations like
square, square root, cube, cube root, exponential and
trigonometric operations
➢ Java Math class provides several methods to work on math
calculations like min(), max(), avg(), sin(), cos(), tan(), round(),
ceil(), floor(), abs() etc.
➢ If the size is int or long and the results overflow the range of
value, the methods addExact(), subtractExact(), multiplyExact(),
and tolntExact() throw an ArithmeticException.
➢ For other arithmetic operations like increment, decrement, divide,
absolute value, and negation overflow occur only with a specific
or value.
Math Methods:

Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
20

➢ The [Link] class contains various methods for


performing basic numeric operations such as the logarithm, cube
root, and trigonometric functions etc. The various java math
methods are as follows:
Basic Math methods

Method Description
[Link]() It will return the Absolute value of the given
value.
[Link]() It returns the Largest of two values.
[Link]() It is used to return the Smallest of two values.
[Link]() It is used to round of the decimal numbers to the
nearest value.
[Link]() It is used to return the square root of a number.
[Link]() It is used to return the cube root of a number.
[Link]() It returns the value of first argument raised to the
power to second argument.
[Link]() It is used to find the sign of a given value.
[Link]() It is used to find the smallest integer value that
is greater than or
equal to the argument or mathematical integer.
[Link]() It is used to find the Absolute value of first
argument along with sign
specified in second argument.
[Link]() It is used to return the floating-point number
adjacent to the first
argument in the direction of the second
argument.
[Link]() It returns the floating-point value adjacent to d in
the direction of
positive infinity.
21

[Link]() It returns the floating-point value adjacent to d in


the direction of
negative infinity.
[Link]() It is used to find the largest integer value which
is less than or equal
to the argument and is equal to the mathematical
integer of a double value.
[Link]() It is used to find the largest integer value that is
less than or equal to
the algebraic quotient.
[Link]() It returns a double value with a positive sign,
greater than or equal
to 0.0 and less than 1.0.
[Link]() It returns the double value that is closest to the
given argument and
equal to mathematical integer.
[Link]() It returns sqrt(x2 +y2) without intermediate
overflow or underflow.
[Link]() It returns the size of an ulp of the argument.
[Link] It is used to return the unbiased exponent used in
Exponent() the representation
of a value.
[Link] It is used to calculate the remainder operation on
nder() two arguments as
prescribed by the IEEE 754 standard and returns
value.
[Link]() It is used to return the sum of its arguments,
throwing an exception
if the result overflows an int or long.
22

[Link] It returns the difference of the arguments,


act() throwing an exception if
the result overflows an int.
[Link] It is used to return the product of the
ct() arguments, throwing an exception if the result
overflows an int or long.
[Link] It returns the argument incremented by one,
xact() throwing an exception if the result overflows an
int.
[Link] It is used to return the argument decremented by
Exact() one, throwing an exception if the result overflows
an int or long.
[Link] It is used to return the negation
ct() of the argument, throwing an exception if the
result overflows an int or long.
[Link] It returns the value of the long argument,
ntExact() throwing an exception if the value overflows an
int.

Logarithmic Math Methods

Method Description
[Link]() It returns the natural logarith m of a do uble value.
Math.Iog10() It is used to return the base 10 logarithm of a double
value.
Math.Iog1p() It returns the natural logarithm of the sum of the
argument and 1.
[Link]() It returns E raised to the power of a double value,
where E is Euler's number and it is approximately
equal to 2.71828.
23

Math.expm1( It is used to calculate the power of E and subtract one


) from it.

Trigonometric Math Methods

Method Description
[Link]() It is used to return the trigonometric Sine value of a
Given double value.
[Link]() It is used to return the trigonometric Cosine value of a
Given double value.
[Link]() It is used to return the trigonometric Tangent value of
a Given double value.
[Link]() It is used to return the trigonometric Arc Sine value of
a Given double value
[Link]() It is used to return the trigonometric Arc Cosine value
of a Given double value.
[Link]() It is used to return the trigonometric Arc Tangent value
of a Given double value.

Hyperbolic Math Methods

Method/ Description
[Link]() It is used to return the trigonometric Hyperbolic Cosine
value of a Given double
value.
[Link]( It is used to return the trigonometric Hyperbolic Sine
) value of a Given double
value.
24

[Link]() It is used to return the trigonometric Hyperbolic Tangent


value of a Given double
value.

Angular Math Methods

Method Description
[Link] It is used to convert the specified Radians angle to
Degrees equivalent angle measured
in Degrees.
[Link] It is used to convert the specified Degrees angle to
Radians equivalent angle measured
in Radians.
13.2. Wrapper Classes
➢ The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
➢ Since J2SE 5.0, autoboxing and unboxing feature convert
primitives into objects and
➢ objects into primitives automatically. The automatic conversion of
primitive into an object is known as autoboxing and vice-versa
unboxing.
Use of Wrapper classes in Java
➢ Java is an object-oriented programming language, so we need to
deal with objects many times like in Collections, Serialization,
Synchronization, etc. Let us see the different scenarios, where we
need to use the wrapper classes.
➢ Change the value in Method: Java supports only call by value.
So, if we pass a primitive value, it will not change the original value.
But, if we convert the primitive value in an object, it will change the
original value.
➢ Serialization: We need to convert the objects into streams to
perform the serialization. If we have a primitive value, we can
25

convert it in objects through the wrapper classes.


➢ Synchronization: Java synchronization works with objects in
Multithreading.
➢ [Link] package: The [Link] package provides the utility
classes to deal with objects.
➢ The eight classes of [Link] package are known as wrapper
classes in Java. The list of eight wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Note:

Autoboxing
The automatic conversion of primitive data type into its
corresponding wrapper class is known as autoboxing, for
example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and
short to Short.
Unboxing
The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing.
26

13.3. String Class


➢ String class belongs to language package.
➢ [Link]; implements strings from string class
➢ Strings are a sequence of characters.
➢ For example, "hello" is a string containing a sequence of
characters 'h', 'e', 'l', 'l', and 'o'.
➢ We use double quotes to represent a string in Java.
➢ Strings are constants their value can not be changed after
created.
➢ Java String provides various methods to perform different
operations on strings.
➢ The [Link] class implements Serializable, Comparable
and CharSequence interfaces.
➢ Java String class provides a lot of methods to perform operations
on strings such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
➢ There are two ways to create String.
➢ By string literal
➢ By new keyword
1) String Literal
➢ Java String literal is created by using double quotes. For
Example:
➢ String s="welcome";
2) By new keyword
➢ String s=new String("Welcome");
String constructors:
➢ String class supports several types of constructors in Java APIs.
The most commonly used constructors of the String class are as
follows:
➢ String(): To create an empty String, we will call the default
constructor.
➢ String(String str): It will create a string object and stores the given
27

value in it.
➢ String(char chars[ ]): This constructor creates a string object and
stores the array of characters in it.
Methods of String class:
➢ CharAt() - Returns the character at the specified index (position).
➢ CompareTo() - Compares two strings.
➢ Concat() - Appends a string to the end of another string.
➢ Contains() - Checks whether a string contains a sequence of
characters.
➢ ContentEquals() - Checks whether a string contains the exact
same sequence of characters of the specified CharSequence
➢ getBytes() - Encodes this String into a sequence of bytes.
➢ indexOf() - Returns the position of the first found occurrence of
specified characters in a string.
➢ Length() - Returns the length of the string.

13.4. String Buffer class

➢ The StringBuffer class is the force behind the scene for most
complex string manipulations.
➢ String Buffer class belongs to language package.
➢ Java StringBuffer class is used to create mutable (modifiable)
String objects. The StringBuffer class in Java is the same as String
class except it is mutable i.e. it can be changed.
➢ Java StringBuffer class is thread-safe i.e. multiple threads cannot
access it simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer Class
➢ StringBuffer() - It creates an empty String buffer with the initial
capacity of 16.
➢ StringBuffer(String str) - It creates a String buffer with the
specified string
➢ StringBuffer(int capacity) - It creates an empty String buffer with
the specified capacity as length.
28

Method of String Buffer class


➢ Append() - concatenates the given argument with this String.
➢ Insert() - inserts the given String with this string at the given
position.
➢ replace() - replaces the given String from the specified beginIndex
and endIndex.
➢ delete() - deletes the String from the specified beginIndex to
endIndex.
➢ reverse() - reverses the current String.
➢ capacity() - returns the current capacity of the buffer. The default
capacity of the buffer is 16.
14. [Link] Package Classes
14.1. Random Class
➢ Random class is part of [Link] package.
➢ An instance of java Random class is used to generate random
numbers.
➢ This class provides several methods to generate random
numbers of type integer, double, long, float etc.
➢ Random number generation algorithm works on the seed value. If
not provided, seed value is created from system.
➢ If two Random instances have same seed value, then they will
generate same sequence of random numbers.
➢ Java Random class is thread-safe, however in multithreaded
e n v i r o n m e n t i t ' s a d v i s e d t o u s e
[Link] class.
➢ Random class instances are not suitable for security sensitive
applications, better to use [Link],SecureRandom in those
cases.

Note :
What is thread?
A thread is a thread of execution in a java program. The
29

Virtual Machine allows an application to have multiple threads


of execution running concurrently.
Constructors:
o Random(): Creates a new random number generator
o Random(long seed): Creates a new random number
generator using a single long seed
Note :
➢ What is Seed? The seed is the initial value of the internal state of
the random number generator which is maintained by method
next(int) . The invocation new Random(seed) is equivalent to:
Random rnd = new Random();
Declaration:
➢ public class Random extends Object implements Serializable

14.2. Date Class

➢ The [Link] class represents date and time in java. It


provides constructors and methods to deal with date and time in
java.
➢ The java. [Link] class implements Serializable, Cloneable
and ComparabIe<Date> interface. It is inherited by [Link]. Date,
[Link] and [Link] interfaces.

Constructors
N Constructor Description
o.
1) Date() Creates a date object representing current
date and time.
2) Date(long Creates a date object for the given
milliseconds) milliseconds since January 1,
1970, 00:00:00 GMT.
30

[Link] Methods
No. Method Description
1) boolean after(Date tests if current date is after the given
date) date.
2) boolean before(Date tests if current date is before the given
date) date.
3) Obiect clone() returns the clone object of current date.
4) int compareTo(Date compares current date with given date.
date)
5) boolean equals(Date compares current date with given date
date) for equality.
6) static Date from(Instantreturns an instance of Date object from
instant) Instant date.
7) long getTime() returns the time represented by this date
object.
8) int hashCode() returns the hash code value for this date
object.
9) void setTime(long time) changes the current date and time to
given time.
10) Instant toInstant() converts current date into Instant object.
11) String tostring() converts this date into Instant object.

14.3. Gregorian Calendar


➢ GregorianCalendar is a concrete subclass of Calendar and
provides the standard calendar system used by most of the world.
➢ The major difference between GregorianCalendar and Calendar
classes are that the Calendar Class being an abstract class cannot
be instantiated. So an object of the Calendar Class is initialized
as:
Calendar cal = [Link] nstance();
31

➢ Here, an object named cal of Calendar Class is initialized with the


current date and time in the default locale and timezone. Whereas,
GregorianCalendar Class being a concrete class, can be
instantiated. So an object of the GregorianCalendar Class is
initialized as:
➢ GregorianCalender cal = (GregorianCalender) [Link]();
Constructors :
GregorianCalendar()
➢ In order to initialize the object with the current time in the default
time zone with the default locale, GrexgorainCalendar() is used.

GregorianCalendar(int year, int month, int day)


➢ In order to initialize the object with the date-set defined in the
default locale and time zone, GregorianCaIendar(int year, int
month, int day) is used.

GregorianCalendar(int year, int month, int day, int hours, int min)
➢ It initializes the object with the date and time-set defined in the
default locale and time zone.
GregorianCalendar(int year, int month, int day int hours, int minutes, int
seconds)
➢ It initializes the object with the date and more specific time-set
defined in the default locale and time zone.
GregorianCalendar(Locale locale)
➢ It initializes the object with a defined date, time, and locale.
GregorianCalendar(TimeZone timezone)
➢ It initializes the object with the defined date, time-set, and
TimeZone.
GregorianCalendar(TimeZone timezone, Locale locale)
➢ It initializes the object with the defined Locale and TimeZone.
32

14.4. String Tokenizer

➢ The [Link] class allows you to break a String into


tokens. It is simple way to break a String. It is a legacy class of
Java.
➢ It doesn't provide the facility to differentiate numbers, quoted
strings, identifiers etc. like StreamTokenizer class.
Example of String Tokenizer class in Java

Hello Everyone!

Hello Everyone! Good Morning

Constructors of the StringTokenizer Class


There are 3 constructors defined in the StringTokenizer class.

Constructor Description
StringTokenizer(String str) It creates StringTokenizer with specified
string.
StringTokenizer(String str, It creates StringTokenizer with specified
String delim) string and delimiter.
33

StringTokenizer(String str, It creates StringTokenizer with specified


String delim, boolean string, delimiter and
returnValue) returnValue. If return value is true,
delimiter characters are
considered to be to kens. If it is false,
delimiter characters serve
to separate tokens.

Methods of the StringTokenizer Class


Methods Description
boolean hasMoreTokens() It checks if there is more tokens
available.
String nextToken() It returns the next token from the
StringTokenizer object.
String nextToken(String It returns the next token based on the
delim) delimiter.
boolean It is the same as hasMoreTokens()
hasMoreElements() method.
Object nextElement() It is the same as nextToken() but its
return type is Object.
int countTokens() It returns the total number of tokens.

14.5. Collection in java


14.5.1. Vector class
➢ Vector is like the dynamic array which can grow or shrink its size.
Umike array, we can store n-number of elements in it as there is
no size limit. It is a part of Java Collection framework since Java
1.2.
➢ It is found in the [Link] package and implements the List
interface, so we can use all the methods of List interface here.
➢ It is recommended to use the Vector class in the thread-safe
34

implementation only. If you don't need to use the thread-safe


implementation, you should use the ArrayList, the ArrayList will
perform better in such case.
➢ The Iterators returned by the Vector class are fail-fast. In case of
c o n c u r r e n tm o d i f i c a t i o n ,i t f a i l s a n d t h r o w s t h e
ConcurrentModificationException.
➢ It is similar to the ArrayList, but with two differences
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the
part of a collections framework.
Syntax:
public class Vector<E> extends AbstractList<E> implements
List<E>, RandomAccess, Clo neable, Serializable
➢ Here, E is the type of element.
➢ It extends AbstractList and implements List interfaces.
➢ I t implements Serializable, Cloneable, I terab Ie<E>,
CoIIection<E>, List<E>, RandomAccess interfaces.
➢ The directly known subclass is Stack.
Constructors
1. Vector(): Creates a default vector of the initial capacity is 10.
Vecto r<E> v = new Vector<E>();
2. Vector(int size): Creates a vector whose initial capacity
is specified by size. Vecto r<E> v = new Vector<E>(int
size)
3. Vector(int size, int incr): Creates a vector whose initial capacity is
specified by size and increment is specified by incr. It specifies the
number of elements to allocate each time a vector is resized upward.
Vecto r<E> v = new Vector<E>(int size, int incr);
4. Vector(Collection c): Creates a vector that contains the
elements of collection c.
Vecto r<E> v = new Vector<E>(Collection c);
35

14.5.2. HashTable,
➢ Java Hashtable class implements a hashtable, which maps keys to
values. It inherits Dictionary class and implements the Map
interface.
Points to remember
➢ A Hashtable is an array of a list. Each list is known as a bucket.
The position of the bucket is identified by calling the hashcode()
method. A Hashtable contains values based on the key.
➢ Java Hashtable class contains unique elements. Java Hashtable
class doesn't allow null key or value. Java Hashtable class is
synchronized.
➢ The initial default capacity of Hashtable class is 11 whereas
IoadFactor is 0.75.

Hashtable class declaration


➢ Let's see the declaration for [Link]. Hashtable class.
public class HashtabIe<K,V> extends Dictionary<K,V> implements M
ap<K,V>, Cloneable, Serializable
Hashtable class Parameters
Let's see the Parameters for [Link] class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.

Constructors of Java Hashtable class


Constructor Description
Hashtable() It creates an empty hashtable having the
initial default capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter and
creates a hash table that
contains a specified initial capacity.
36

Hashtable(int It is used to create a hash table having


capacity, float the specified initial capacity and
IoadFactor) IoadFactor.
Hashtable(M ap<? It creates a new hash table with the
extends K,? same mappings as the given Map.
extends V> t)

14.5.3. LinkedList
➢ Java LinkedList class uses a doubly linked list to store the
elements. It provides a linked- list data structure. It inherits the
AbstractList class and implements List and Deque interfaces.
➢ The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no
shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

Note :
ArrayList vs. LinkedList
➢ The LinkedList class is a collection which can contain many
objects of the same type, just like the ArrayList.
➢ The LinkedList class has all of the same methods as the ArrayList
class because they both implement the List interface. This means
that you can add items, change items, remove items and clear the
list in the same way.
➢ However, while the ArrayList class and the LinkedList class can
be used in the same way, they are built very differently.
➢ LinkedList Methods
➢ For many cases, the ArrayList is more efficient as it is common to
need access to random items in the list, but the LinLedList
37

provides several methods to do certain operations more


efficiently:

Method Description

addF irst() Adds an item to the beginning of the list.


addLast() Add an item to the end of the list
removeFirst() Remove an item from the beginning of the list.
removeLast() Remove an item from the end of the list

getFirst() Get the item at the beginning of the list


getLast() Get the item at the end of the list

14.5.4. SortedSet,
➢ A set is used to provide a particular ordering on its element. The
elements are ordered either by using a natural ordering or by using
a Comparator. All the elements which are inserted into a sorted set
must implement the Comparable interface.
➢ The set's iterator will traverse the set in an ascending order.
Several other operations are provided in order to make best use of
ordering. All the elements must be mutually comparable.

Methods

Comparator() Returns the comparator which is used to order the


elements in the given set.
Also returns null if the given set uses the natural ordering
of the element.
First() Returns the first element from the current set.
38

headSet(E Returns a view of the portion of the given set whose


toElement) elements are strictly less than the toElement.
last() Returns the Last element from the current set.
spliterator() Splits or divides set into parts.
subSet(E Returns a key-value mapping which is associated with
fromElement, the greatest key which is less than or equal to the given
E toElement) key. Also, returns null if the map is empty.
taiISet(E Returns a view of the map whose keys are strict Iy less
fromElement) than the toKey.

14.5.5. Stack
➢ Stack is a subclass of Vector that implements a standard last-in,
first-out stack.
➢ Stack only defines the default constructor, which creates an
empty stack. Stack includes all the methods defined by Vector,
and adds several of its own.
➢ Stack() a part from the methods inherited from its parent class
Vector, Stack defines the following methods.
Sr.N Method & Description
o.
boolean empty() : Tests if this stack is empty. Returns true if
1 the stack is empty, and returns false if the stack contains
elements.
2 Object peek( ): Returns the element on the top of the stack,
but does not remove it.
3 Object pop( ): Returns the element on the top of the stack,
removing it in the process.
4 Object push(Object element) : Pushes the element onto
the stack. Element is also returned.
39
40

5 int search(Object element) : Searches for element in the


stack. If found, its offset from the top of the stack is returned.
Otherwise, -1 is returned.

14.5.6. Queue
➢ The queue interface is provided in [Link] package
➢ It implements the Collection interface.
➢ The queue implements FIFO i.e. First In First Out. This means
that the elements entered first are the ones that are deleted first.
Creating Queue Objects: As queue is interface we can not write
constructor of queue interface.
➢ So that we need to use the classes that implements queue
interface.
➢ Queue<Obj> queue = new LinkedList<Obj> ();
Methods of queue:
➢ add(element): Adds an element to the Last of the queue. If the
queue is full, it throws an exception.
➢ remove(): Removes and returns the element at the front of the
queue.
➢ poll(): Removes and returns the element at the front of the
queue.
➢ peek(): Returns the element at the front of the queue without
removing it.
➢ The Queue interface is implemented by several classes in Java,
including LinkedList, ArrayDeque, and PriorityQueue.

14.5.7. Map
➢ The Map interface of the Java collections framework provides the
functionality of the map data structure.
Working of Map
➢ In Java, elements of Map are stored in key/value pairs. Keys are
unique values associated with individual Values.
41

➢ A map cannot contain duplicate keys. And, each key is associated


with a single value.

Classes that implement Map


➢ Since Map is an interface, we cannot create objects from it.
➢ In order to use functionalities of the Map interface, we can use
these classes:
➢ HashMap
➢ EnumMap
➢ Linked HashMap
➢ WeakHash Map
➢ Tree Map
➢ These classes are defined in the collections framework and
implement the Map interface.
Interfaces that extend Map
➢ The Map interface is also extended by these sub interfaces:
➢ SortedMap
➢ Navigable Map
➢ Concurrent Map

Methods of Map
➢ The Map interface includes all the methods of the Collection
interface. It is because Collection is a super interface of Map.
➢ Besides methods available in the Collection interface, the Map
interface also includes the
➢ following methods:

➢ put(K, V) - Inserts the association of a key K and a value V into


the map. If the key is already present, the new value replaces the
old value.
➢ putAll() - Inserts all the entries from the specified map to this
map.
42

➢ putIfAbsent(K, V) - Inserts the association if the key K is not


already associated with the value V.
➢ get(K) - Returns the value associated with the specified key K. If
the key is not found, it returns null.
➢ getOrDefault(K, defaultValue) - Returns the value associated
with the specified key K. If the key is not found, it returns the
defaultValue.
➢ containsKey(K) - Checks if the specified key K is present in the
map or not.
➢ containsValue(V) - Checks if the specified value V is present in
the map or not. O replace(K, V) - Replace the value of the key K
with the new specified value V.
➢ replace(K, oldValue, newValue) - Replaces the value of the key
K with the new value newValue only if the key K is associated with
the value oIdVaIue.
➢ remove(K) - Removes the entry from the map represented by the
key K.
➢ remove(K, V) - Removes the entry from the map that has key K
associated with value V.
➢ keyset() - Returns a set of all the keys present in a map. O
values() - Returns a set of all the values present in a map.
➢ Entryset() - Returns a set of all the key/value mapping present in
a map.

You might also like