Java Unit-2
Java Unit-2
Prepared
Study NotesBy :by-
Bansari
RonakRupareliya
Goda
2
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).
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
Prepared
Study NotesByby-
: Bansari
Ronak Rupareliya
Goda
3
➢ 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]?
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
Prepared
Study NotesBy by-
: Bansari
Ronak Rupareliya
Goda
5
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
4. Constructors in inheritance
Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
7
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.
➢ 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
➢ 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
Study Notes
Prepared Byby- Ronak
: Bansari Goda
Rupareliya
10
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
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
Study Notes
Prepared By by- Ronak
: Bansari Goda
Rupareliya
13
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
Study Notes
Prepared By by- Ronak
: Bansari Goda
Rupareliya
15
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
Prepared By :by- Ronak
Bansari Goda
Rupareliya
17
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
Study Notes
Prepared By :by- Ronak
Bansari Goda
Rupareliya
20
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
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
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.
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
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
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
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.
➢ 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
Note :
What is thread?
A thread is a thread of execution in a java program. The
29
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.
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
Hello Everyone!
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
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.
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
Method Description
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
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
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
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: