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

Chapter 6 Inner Classes Package

The document provides an overview of nested classes in Java, explaining their types, properties, and usage, including static nested classes, inner classes, member inner classes, local inner classes, and anonymous inner classes. It also discusses the 'this' keyword, its purpose, and how it can be used to refer to the current object, access methods, and invoke constructors. Additionally, the document covers interfaces in Java, their characteristics, differences from classes, and examples of implementing multiple interfaces.
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 views62 pages

Chapter 6 Inner Classes Package

The document provides an overview of nested classes in Java, explaining their types, properties, and usage, including static nested classes, inner classes, member inner classes, local inner classes, and anonymous inner classes. It also discusses the 'this' keyword, its purpose, and how it can be used to refer to the current object, access methods, and invoke constructors. Additionally, the document covers interfaces in Java, their characteristics, differences from classes, and examples of implementing multiple interfaces.
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

Topic:1

Nested classes:
Writing a class within another is allowed in Java.
The class written within is called the nested class, and the class that holds
the inner class is called the outer class.
Nested classes are divided into two categories: static and non-static.
Nested classes that are declared static are simply called static nested
classes.
Non-static nested classes are called inner classes.

Properties of Nested classes in Java:

In Java, a nested class is a class that is defined inside some other class.
Nested classes are used to group certain classes to improve the readability
of the code.
The scope of a nested class is the same as its outer class.
Nested classes can access any member of the outer class, even if the outer
class is private.

Types of Nested Classes:

A nested class can either be defined as a static type or a non-static type.

Static Nested Classes


Non-static Nested Classes (or Inner Classes) We can further divide the
Non-static Classes into -

 Member Inner Classes


 Local Inner Classes
 Anonymous Inner Classes
Static Nested Classes:

A static class is a class that is created inside a class.


A static variable is common to all the instances of that particular class.
Similarly, a static class can access all the instance functions of the outer
class.
we will have to make objects of child classes and refer to them.
We can access all the static functions of the outer class without object
creation.

Syntax:
class parent_class
{
static class static_child_class
{
// code
}
}

static_child_class obj = new static_child_class();


Example:
class parent_class
{
static String s = "Parul University @";
static class static_child_class // child class
{
void print (String x) // child class method
{
[Link](s + " " + x);
}
}
public static void main(String args[])
{
static_child_class obj = new static_child_class(); // child class object
String y = "Vadodara";
[Link](y);
}
}
Output:
Parul University @ Vadodara

Non-static Nested Classes (Inner Classes):

A non-static nested class or inner class is a class within a class.


We do not define it as static so that it can directly use all the functions
and variables of the outer class.

From the inner class, if we want to access any static method of the outer class,
we do not need any object; we can call it directly.

1. Member Inner Classes


2. Local Inner Classes
3. Anonymous Inner Classes
Type Description

Member Inner A class created within class and outside method.


Class

Anonymous Inner A class created for implementing an interface or extending


Class class. The java compiler decides its name.

Local Inner Class A class was created within the method.

Static Nested A static class was created within the class.


Class

Nested Interface An interface created within class or interface.

Member Inner Classes:


A non-static class that is declared inside a class but outside the method
is known as member inner class in Java.
It is also known as regular inner class.
It can be declared with access modifiers like public, default, private and
protected.

Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example:
class parent_class
{
String s = "Parul University:-";
class child_class // child class
{
void print(String x)
{
[Link](s + " " + x);
}
}
public static void main(String args[])
{
parent_class parentObj = new parent_class();// parent class object
child_class childObj = [Link] child_class (); // child class object
using parent class object
String y = "Vadodara @ Gujarat";
[Link](y); // calling methods of child class
}
}

Output:
Parul University:- Vadodara @ Gujarat
Local Inner Classes:
A Local Inner class is a class that is defined inside any
block, i.e., for block, if block, methods, etc. Similar to local variables, the
scope of the Local Inner Class is restricted to the block where it is defined.
Syntax:
class class_name
{
void method_name()
{
// code
if(conditions)
{
// or any other block like while, for, etc.
class localInnerClass
{
void localInnerMethod()
{
// code
}
}
}
// code
}
}
Example:
class parent_class
{
public static void main(String args[])
{
String p = "Parul University";
if ([Link](0) = = 'P')
{
class child_class // child class
{
void print(String x)
{
[Link](p + " " + x);
}
}
child_class childObj = new child_class(); // child class object
String y = "Vadodara @ Gujarat";
[Link](y); // calling child class method
// child_class is accessible till here only
}
// child_class is not accessible here
}
}
Output:
Parul University Vadodara @ Gujarat
Anonymous Inner Classes:

Anonymous Inner class is an inner class but without a name. It has only a
single object. It is used to override a method. It is only accessible in the block
where it is defined.

We can use an abstract class to define the anonymous inner class.


It has access to all the members of the parent class.
It is useful to shorten over code.
Basically, it merges the step of creating an object and defining the class.

Abstract is a keyword, its non-accessing modifier, its used for classes and
Methods.
Abstract Class: Abstract class is a restricted class that can’t be used to
create Object, it must be inherited from another class.
Abstract Methods: abstract method is used only in abstract class, it does
not have any body

Syntax:
abstractClass obj = new abstractClass()
{
void methods()
{
// code
}
};
Example:
abstract class Printer
{
abstract void print (String x);
}
class parent_class // Parent Class
{
public static void main(String args[])
{
Printer obj = new Printer() // Anonymous Inner Class
{
void print(String x)
{
[Link]("Parul University, " + x);
}
};
String y = "Vadodara @ Gujarat";
[Link](y);
}
}

Output:
Parul University, Vadodara @ Gujarat

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Topic:2
this keyword in Java:

In Java, this is a keyword which is used to refer current object of a class. we


can it to refer any member of the class. It means we can access any instance
variable and method by using this keyword.

The main purpose of using this keyword is to solve the confusion when we have
same variable name for instance and local variables.

We can use this keyword for the following purpose.

this keyword is used to refer to current object.


this is always a reference to the object on which method was invoked.
this can be used to invoke current class constructor.
this can be passed as an argument to another method.
Lets first understand the most general use of this keyword. As we said, it can be
used to differentiate local and instance variables in the class.

Example:
class ThisKeyWord
{
Double width, height, depth;
ThisKeyWord (double w, double h, double d)
{
[Link] = w;
[Link] = h;
[Link] = d;
}
public static void main(String[] args)
{
ThisKeyWord Obj = new ThisKeyWord(100,200,300);
[Link]("width = "+ [Link]);
[Link]("height = "+ [Link]);
[Link]("depth = "+ [Link]);
}
}
Output:
width = 100.0
height = 200.0
depth = 300.0
Calling Constructor using this keyword:
We can call a constructor from inside the another function by using this
keyword

Example:
In this example, we are calling a parameterized constructor from the non-
parameterized constructor using the this keyword along with argument.

Example:

class ThisKeyWordConstructor
{
ThisKeyWordConstructor ()
{
this("CSE Dept @ Parul University "); // Calling constructor
}
ThisKeyWordConstructor(String str)
{
[Link](str);
}
public static void main(String[] args)
{
ThisKeyWordConstructor This = new ThisKeyWordConstructor();
}
}

Output:

CSE Dept @ Parul University


Accessing Method using this keyword:
This is another use of this keyword that allows to access method. We can access
method using object reference too but if we want to use implicit object
provided by Java then use this keyword.

Example:

In this example, we are accessing getName () method using this and it works
fine as works with object reference.

Example Program:

class ThisMethod
{
public void getName()
{
[Link]("Department of CSE @ Parul");
}
public void display()
{
[Link]();
}
public static void main(String[] args)
{
ThisMethod Obj = new ThisMethod ();
[Link]();
}
}

Output:

Department of CSE @ Parul

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Topic:3

What is Interface in Java?


Interface is basically a kind of a class.
Interface contains methods and variables.
Interface is a collection of abstract method and constants (Static and
Final)
Very interface in java is abstract by default.
So, no need to abstract key with an interface.
An Interface in Java programming language is defined as an abstract type
used to specify the behaviour of a class.
A class can implement multiple interfaces.
In Java, interfaces are declared using the interface keyword.
All methods in the interface are implicitly public and abstract.
Difference between Class and Interface:
Class Interface
In class, you can instantiate variable In an interface, you can’t instantiate
and create an object. variable and create an object.
Class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods

The access specifiers used with classes In Interface only one specifier is used-
are private, protected and public. Public.
Constructors can be included in a class but not an inheritance.
A method body can exist in a class. but it cannot exist in an interface.
Classes do not support multiple but it is supported by inheritance.
inheritance.

A Java class can implement multiple Java Interfaces.


It is necessary that the class must implement all the methods declared in
the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning
which classes it belongs.
Class needs to provide functionality for the methods declared in the
interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend only
one class but implement any number of interfaces
An interface cannot implement another Interface. It has to extend another
interface if needed.
An interface which is declared inside another interface is referred as nested
interface
At the time of declaration, interface variable must be initialized. Otherwise,
the compiler will throw an error.
The class cannot implement two interfaces in java that have methods with
same name but different return type.

Example

Interface and Class:

interface Pet
{
public void test();
}
class Dog implements Pet
{
public void test()
{
[Link]("Interface Method Implemented");
}
public static void main(String args[])
{
Pet p = new Dog();
[Link]();
}
}
Output:

Interface Method Implemented


Interface and Multiple Classes Bank

interface Bank
{
float rateOfInterest(); SBI ICICI
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 7.15f;
}
}
class ICICI implements Bank
{
public float rateOfInterest()
{
return 8.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new ICICI ();
[Link]("ROI: "+[Link]());
}
}

Output:
ROI: 8.7
Multiple inheritance in Java by interface:
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface int1
{ int1 int2
int i=20;
void print();
}
Test
interface int2
{
void show();
}
class test implements int1, int2
{
public void print()
{
[Link]("Hello");
}
public void show()
{
[Link]("Welcome");
}
public static void main(String args[])
{
test obj=new test();
[Link]();
[Link]();
obj.i=30;
[Link](obj.i);
}
}

Output:

Hello

Welcome

20
interface A
{
void print();
}
interface B
{
void show();
}
class C implements A, B
{
A B
public void print()
Interface Interface
{
[Link]("Hello");
}
public void show() C
Class
{
[Link]("Welcome to CSE");
}
public static void main(String args[])
{
C obj = new C();
[Link]();
[Link]();
}
}

Output:

Hello

Welcome to CSE
Example : 2

/*
* Interface extends multiple interfaces java example
*/

interface A
{
void printa();
A B
}
interface B
{
void printb(); C
}
interface C extends A,B
{ XYZ
void printc();
}
class XYZ implements C
{
public void printa()
{
[Link]("im from interface A");
}
public void printb()
{
[Link]("im from interface B");
}
public void printc()
{
[Link]("im from interface C");
}
}
class Sample
{
public static void main(String[] args)
{
XYZ obj = new XYZ();
obj. printa();
obj. printb();
obj. printc();
}
}
Output:

im from interface A

im from interface B

im from interface C

*-*-*-**-*-*-*-*-*-*-*-*-*
Topic:4

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

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.

Adding a class to a Package:


We can add more classes to a created package by using package name at
the top of the program and saving it in the package directory.
We need a new java file to define a public class, otherwise we can add
the new class to an existing .java file and recompile it.
Packages avoid the name clashes.
The Package provides easier access control.
We can also have the hidden classes that are not visible outside and used
by the package.
It is easier to locate the related classes.
 Sub packages:
Packages that are inside another package are the subpackages.
These are not imported by default;
they have to imported explicitly.
Also, members of a sub-package have no access privileges, i.e., they are
considered as different package for protected and default access
specifiers.

 How to Create a package:


Creating a package in java is quite easy. 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 you define to be part of
mypackage package must be stored in a directory called mypackage.
 Additional 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)
The packages are classified into two types.

Built-in Packages
User-defined packages
[Link]-in Packages: (Pre-defined packages)
These packages consist of a large number of classes which
are a part of Java API. Some of the commonly used built-in packages are:

1) [Link]:
Contains language support classes (e.g classed which defines
primitive data types, math operations). This package is automatically imported
by default.
2)[Link]:
Contains classed for supporting input / output operations. It will
perform Read/Write operations.

3)[Link]:
Contains utility classes which implement data structures like
Linked List, Dictionary and support; for Date / Time operations.
Ex: [Link].*;
ex: [Link] class
4)[Link]:
Contains classes for creating Applets.

5)[Link]:
Contain classes for implementing the components for graphical
user interfaces (GUI) like button, menus etc..

6)[Link]:
Contain classes for supporting networking operations. Like Client
Server programs and networking operation in java

[Link]-defined packages:
These are the packages that are defined by the user.
first we create a directory myPackage (name should be same as the name of
the package). Then create the MyClass inside the directory with the first
statement being the package names.

package mypack;
public class Simple
{
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 you are not using any IDE, you 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.
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. [Link] etc to run the
class.
To Compile: javac -d . [Link]
To Run: java [Link]
Example
Program: Creating Package
package Robo;
public class Add
{
int x,y;
public Add() // Constructor //
{
x=100;
y=200;
}
public void sum() // Method //
{
[Link]("Addition of two numbers:="+(x + y));
}
}

import [Link]; // Main Program importing package //


class Sana
{
public static void main(String args[])
{
Add obj=new Add();
[Link]();
}
}
Output:
Addition of two numbers: 300
Topic:5

 How to access package from another package:


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

All the classes and interfaces of this package can be accessed (imported)
from outside the packages.
If you 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.

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.*; // it access all classes in a package //
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:
Hello java

2) Using [Link]:

If you import [Link], you can access the declared class


of this package.
If you import [Link] then only declared class of this package
will be accessible.

Example of package by import [Link]:


//save by [Link] //
package pack; // creating package 1 //
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link] //
package mypack; // creating package 2 //
import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:
Hello
Note:
pack.A it access only class A, if you use [Link].* it will access all
[Link], we can access all Linkedlist, date, Calendar and Hash table.

3) Using fully qualified name:

If you use fully qualified name then only declared class of this package
will be accessible.
Now there is no need to import. But you need to use fully qualified name
every time when you 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:


//save by [Link]
package pack; // creating package 1 //
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack; // creating package 2 //
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
[Link]();
}
}
Output:
Hello
Note:

If you use import a package, sub packages will not be imported.


If you import a package, all the classes and interface of that package will
be imported excluding the classes and interfaces of the sub packages.
Hence, you need to import the sub package as well.

 Subpackage in java:
Package inside the package is called the subpackage. It
should be created to categorize the package further.

Let's take an example, Sun Microsystem has defined a package named


java that contains many classes like System, String, Reader, Writer,
Socket etc.
These classes represent a particular group e.g. Reader and Writer classes
are for Input/Output operation, Socket and Server Socket classes are for
networking etc and so on.
So, Sun has subcategorized the java package into sub packages such as
lang, net, io etc. and put the Input/Output related classes in io package,
Server and Server Socket 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
{
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, you 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.
Topics:6

 IO Package:

The [Link] package is used to handle input and output operations.


Java IO has various classes that handle input and output sources.
A stream is a sequence of data.
Java input stream classes can be used to read data from input sources
such as keyboard or a file.
Similarly output stream classes can be used to write data on a display or
a file again.

I/O Streams in Java:

Before understanding IO streams, let us discuss streams.


A Stream is also a sequence of data.
It is neither a data structure nor it stores data.
Take an example of a river stream, where water flows from source to
destination. Similarly, these are data streams; data flows through one
point to another.

To handle these sequences, we introduce a term called IO streams.

The [Link] package helps the user to perform all types of input-output
operations.
Java IO package is primarily focused on input-output files, network
streams, internal memory buffers, etc.
Data is read and written from Java
IO's InputStream and OutputStream classes.
In other words, IO streams in java help to read the data from an input
stream such as a file and write the data into an output stream such as the
standard display or a file again.
It represents source as input and destination as output. It can handle all
types of data, from primitive values to advanced objects.

There are 3 categories of classes in [Link] package:

Input Streams.
Output Streams.
Error Streams.

Java supports three streams that are automatically attached with the console.

1. [Link]: Standard output stream


2. [Link]: Standard input stream
3. [Link]: Standard error stream

Input Streams:

As we know input source consists of data that needs to be read in order to


extract information from it.
Input Streams help us to read data from the input source.
It is an abstract class that provides a programming interface for all input
streams.
Input streams are opened implicitly as soon as it is created.
To close the input stream by using the close() method on the source
object.
Output Streams:

The output of the executed program has to be stored in a file for further
use.
Output streams help us to write data to a output source (may be file).
Similarly like input streams output streams are also abstract classes that
provides a programming interface for all output streams.
The output stream is opened as soon as it is created and explicitly closed
by using the close() method.

Error Streams:

Error streams are the same as output streams.


In some ide’s error is displayed in different colors (other than the color of
output color).
It gives output on the console the same as output streams.

Why We Need IO Streams in Java?

In day-to-day work, we do not enter the input into the programs


manually.
Also, the result of the program needs to be stored somewhere for further
use.
So, IO streams in Java provide us with input and output streams that help
us to extract data from the files and write the data into the files.
Normally, we can create, delete, and edit files using [Link].
In short, all the file manipulation is done using Java IO streams. Java IO
streams also handle user input functionality.

Useful methods of Input Stream:

1. public abstract int read() throws IOException:

The method above helps to return the data of the next byte in the input
stream.
The value returned is between 0 to 255.
If no byte is read, the code returns -1, which indicates the end of the file.

2. public int available() throws IOException:

The method above returns the number of bytes that can be read from
the input stream.

3. public void close() throws IOException:

The method above closes the current input stream and releases any
system resources associated with it.

4. public void mark(int readlimit):

It marks the current position in the input stream.


The readlimit argument tells the input stream to read that many bytes to
read before the mark position gets invalid.

5. public boolean markSupported():

It tells whether the mark() and reset() method is supported in a particular


input stream.
It returns true if the mark and reset methods are supported by the
particular input stream or else return false.

6. public int read(byte[ ] b) throws IOException;

The method above reads the bytes from the input stream and stores every
byte in the buffer array.
It returns the total number of bytes stored in the buffer array.
If there is no byte in the input stream, it returns -1 as the stream is at the
end of the file.
7. public int read(byte[ ] b , int off , len) throws IOException:

It reads up to len bytes of data from the input stream.


It returns the total number of bytes stored in the buffer.
Here the “off” is start offset in buffer array b where the data is written,
and the “len” represents the maximum number of bytes to read.

8. public void reset() throws IOException:

It repositions the stream to the last called mark position.


The reset method does nothing for input stream class except throwing an
exception.

9. public long skip(long n) throws IOException:

Output Stream:

It is an abstract superclass of the [Link] package and writes data to an


output resource.
In other words, writing the data into the files.
We can create an object of the output stream class using
the new keyword.
The output stream class has several types of constructors.

Useful methods of OutputStream:

1. public void close() throws IOException:

This method closes the current output stream and releases any system
resources associated with it.
The closed stream cannot be reopened and operations cannot be
performed within it.
2. public void flush() throws IOException:

It flushes the current output stream and forces any buffered output to be
written out.

3. Public void write(byte[ ] b) throws IOException:

This method writes the [Link] bytes from the specified byte array to the output
stream.

4. Public void write (byte[ ] b ,int off ,int len) throws IOException:

It writes upto len bytes of data to the output stream.


Here the “off” is the start offset in buffer array b, and the “len” represents
the maximum number of bytes to be written in the output stream.

5. Public abstract void write(int b) throws IOException.

The method above writes the specific bytes to the output stream. It
does not return a value.
Topics:7

[Link] package in Java

1. Boolean:
The Boolean class wraps a value of the primitive type
boolean in an object.

2. Byte:
The Byte class wraps a value of primitive type byte in an
object.
3. Character – Set 1, Set 2:
The Character class wraps a value of the
primitive type char in an object.

4. [Link]:
Instances of this class represent particular subsets
of the Unicode character set.

5. [Link]:
A family of character subsets
representing the character blocks in the Unicode specification.

6. Class – Set 1, Set 2 :


Instances of the class Class represent classes
and interfaces in a running Java application.

7. ClassLoader:
A class loader is an object that is responsible for
loading classes.

8. ClassValue:
Lazily associate a computed value with (potentially)
every type.

9. Compiler:
The Compiler class is provided to support Java-to-native-
code compilers and related services.

10. Double:
The Double class wraps a value of the primitive type double
in an object.
11. Enum:
This is the common base class of all Java language
enumeration types.

12. Float:
The Float class wraps a value of primitive type float in an
object.

13. InheritableThreadLocal:
This class extends ThreadLocal to provide
inheritance of values from parent thread to child thread: when a child
thread is created, the child receives initial values for all inheritable
thread-local variables for which the parent has values.

14. Integer :
The Integer class wraps a value of the primitive type int in
an object.

15. Long:
The Long class wraps a value of the primitive type long in an
object.
16. Math – Set 1, Set 2:
The class Math contains methods for performing
basic numeric operations such as the elementary exponential,
logarithm, square root, and trigonometric functions.

17. Number:
The abstract class Number is the superclass of classes
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and
Short.

18. Object:
Class Object is the root of the class hierarchy.

19. Package:
Package objects contain version information about the
implementation and specification of a Java package.

20. Process:
The [Link]() and [Link] methods
create a native process and return an instance of a subclass of
Process that can be used to control the process and obtain
information about it.
21. ProcessBuilder:
This class is used to create operating system
processes.

22. [Link]:
Represents a source of subprocess input or
a destination of subprocess output.

23. Runtime:
Every Java application has a single instance of class
Runtime that allows the application to interface with the
environment in which the application is running.

24. RuntimePermission:
This class is for runtime permissions.

25. SecurityManager:
The security manager is a class that allows
applications to implement a security policy.

26. Short:
The Short class wraps a value of primitive type short in an
object.

27. StackTraceElement:
An element in a stack trace, as returned by
[Link]().

28. StrictMath- Set1, Set2:


The class StrictMath contains methods for
performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.

29. String- Set1, Set2:


The String class represents character strings.
30. StringBuffer:
A thread-safe, mutable sequence of characters.
31. StringBuilder:
A mutable sequence of characters.
32. System:
The System class contains several useful class fields and
methods.

33. Thread:
A thread is a thread of execution in a program.

34. ThreadGroup:
A thread group represents a set of threads.

35. ThreadLocal:
This class provides thread-local variables.

36. Throwable:
The Throwable class is the superclass of all errors and
exceptions in the Java language.

37. Void:
The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the Java keyword void.
Example:
public class Main
{
public static void main(String[] args)
{
// Creating objects
Boolean bool = new Boolean("False");
Byte by = new Byte("0001");
Character character = new Character('a');
Double doub = new Double("1.25");
Float fl = new Float("1.1");
Integer integer = new Integer("10");
Long l = new Long("1000000");
//printing result
[Link]("Boolean: " + bool);
[Link]("Byte: " + by);
[Link]("Character: " + character);
[Link]("Double: " + doub);
[Link]("Float: " + fl);
[Link]("Integer: " + integer);
[Link]("Long: " + l);
}
}

Output:
Boolean: false
Byte: 1
Character: a
Double: 1.25
Float: 1.1
Integer: 10
Long: 1000000
Topics:8
[Link] Package:
1. AbstractCollection:
This class provides a skeletal implementation
of the Collection interface, to minimize the effort required to
implement this interface.

2. AbstractList:
This class provides a skeletal implementation of the
List interface to minimize the effort required to implement this
interface backed by a “random access” data store (such as an array).

3. AbstractMap<K,V>:
This class provides a skeletal implementation
of the Map interface, to minimize the effort required to implement
this interface.

4. [Link]<K,V>:
An Entry maintaining a key and
a value.

5. [Link]<K,V>:
An Entry
maintaining an immutable key and value.

6. AbstractQueue:
This class provides skeletal implementations of
some Queue operations.

7. AbstractSequentialList:
This class provides a skeletal
implementation of the List interface to minimize the effort required
to implement this interface backed by a “sequential access” data
store (such as a linked list).

8. AbstractSet:
This class provides a skeletal implementation of the
Set interface to minimize the effort required to implement this
interface.
9. ArrayDeque:
Resizable-array implementation of the Deque
interface.

10. ArrayList:
Resizable-array implementation of the List interface.

11. Arrays:
This class contains various methods for manipulating arrays
(such as sorting and searching).

12. BitSet:
This class implements a vector of bits that grows as needed.

13. Calendar:
The Calendar class is an abstract class that provides
methods for converting between a specific instant in time and a set
of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the calendar fields, such as
getting the date of the next week.

14. Collections:
This class consists exclusively of static methods that
operate on or return collections.
15. Currency:
Represents a currency.
16. Date:
The class Date represents a specific instant in time, with
millisecond precision.
17. Dictionary<K,V>:
The Dictionary class is the abstract parent of
any class, such as Hashtable, which maps keys to values.
18. EnumMap,V>:
A specialized Map implementation for use with
enum type keys.
19. EnumSet:
A specialized Set implementation for use with enum types.

20. EventListenerProxy:
An abstract wrapper class for an
EventListener class which associates a set of additional parameters
with the listener.
21. EventObject:
The root class from which all event state objects shall
be derived.
22. FormattableFlags:
FomattableFlags are passed to the
[Link]() method and modify the output format for
Formattables.
23. Formatter:
An interpreter for printf-style format strings.
24. GregorianCalendar:
GregorianCalendar is a concrete subclass of
Calendar and provides the standard calendar system used by most of
the world.
25. HashMap<K,V>:
Hash table based implementation of the Map
interface.
26. HashSet:
This class implements the Set interface, backed by a hash
table (actually a HashMap instance).
27. Hashtable<K,V>:
This class implements a hash table, which maps
keys to values.
28. IdentityHashMap<K,V>:
This class implements the Map interface
with a hash table, using reference-equality in place of object-equality
when comparing keys (and values).
29. LinkedHashMap<K,V>:
Hash table and linked list implementation
of the Map interface, with predictable iteration order.
30. LinkedHashSet:
Hash table and linked list implementation of the
Set interface, with predictable iteration order.
31. LinkedList:
Doubly-linked list implementation of the List and
Deque interfaces.
32. ListResourceBundle:
ListResourceBundle is an abstract subclass
of ResourceBundle that manages resources for a locale in a
convenient and easy to use list.
33. Locale – Set 1, Set 2:
A Locale object represents a specific
geographical, political, or cultural region.
34. [Link]:
Builder is used to build instances of Locale from
values configured by the setters.
35. Objects:
This class consists of static utility methods for operating
on objects.
36. Observable:
This class represents an observable object, or “data” in
the model-view paradigm.
37. PriorityQueue:
An unbounded priority queue based on a priority
heap.
38. Properties:
The Properties class represents a persistent set of
properties.
39. PropertyPermission:
This class is for property permissions.
40. PropertyResourceBundle:
PropertyResourceBundle is a concrete
subclass of ResourceBundle that manages resources for a locale
using a set of static strings from a property file.
41. Random:
An instance of this class is used to generate a stream of
pseudorandom numbers.
42. ResourceBundle:
Resource bundles contain locale-specific objects.
43. [Link]:
[Link] defines a set of
callback methods that are invoked by the [Link]
factory methods during the bundle loading process.
44. Scanner:
A simple text scanner which can parse primitive types and
strings using regular expressions.
45. ServiceLoader:
A simple service-provider loading facility.
46. SimpleTimeZone:
SimpleTimeZone is a concrete subclass of
TimeZone that represents a time zone for use with a Gregorian
calendar.
47. Stack:
The Stack class represents a last-in-first-out (LIFO) stack of
objects.
48. StringTokenizer:
The string tokenizer class allows an application
to break a string into tokens.
49. Timer:
A facility for threads to schedule tasks for future execution
in a background thread.
50. TimerTask:
A task that can be scheduled for one-time or repeated
execution by a Timer.
51. TimeZone:
TimeZone represents a time zone offset, and also figures
out daylight savings.
52. TreeMap<K,V>:
A Red-Black tree based NavigableMap
implementation.

53. TreeSet:
A NavigableSet implementation based on a TreeMap.
54. UUID:
A class that represents an immutable universally unique
identifier (UUID).
55. Vector:
The Vector class implements a growable array of objects.
56. WeakHashMap<K,V>:
Hash table based implementation of the
Map interface, with weak keys.

Topics:9

Wrapper classes in Java:

The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.

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.

The eight classes of the [Link] package are known as wrapper classes in
Java. The list of eight wrapper classes are given below:
Use of Wrapper classes in Java:

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

Collection Framework:

Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with
objects only.
Autoboxing:

The automatic conversion of primitive data type into its


corresponding wrapper class is known as autoboxing,

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.

Example:

class WrapperClass
{
public static void main(String args[])
{
//Converting int into Integer
int a=50;
Integer i=[Link](a); //converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write [Link](a) internal
ly
[Link](a +" "+ I +" "+ j );
}
}
Output:
50 50 50
Unboxing:

The automatic conversion of wrapper type into its corresponding primitive


type is known as unboxing.
It is the reverse process of autoboxing.
Since Java 5, we do not need to use the intValue () method of wrapper
classes to convert the wrapper type into primitives.

public class WrapperClass1


{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(100);
int i=[Link]();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write [Link]() internally
[Link](a +" " + i + " " + j );
}
}

Output:
100 100 100
Example:
public class WrapperExample3
{
public static void main(String args[])
{
byte b=100;
short s=1500;
int i=200;
long l=250;
float f=350.0F;
double d=400.0D;
char c='c';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
[Link]("***Printing object values***");
[Link]("Byte object: "+byteobj);
[Link]("Short object: "+shortobj);
[Link]("Integer object: "+intobj);
[Link]("Long object: "+longobj);
[Link]("Float object: "+floatobj);
[Link]("Double object: "+doubleobj);
[Link]("Character object: "+charobj);
[Link]("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
[Link]("*-*-*-*Printing primitive values-*-*-*");
[Link]("byte value: "+bytevalue);
[Link]("short value: "+shortvalue);
[Link]("int value: "+intvalue);
[Link]("long value: "+longvalue);
[Link]("float value: "+floatvalue);
[Link]("double value: "+doublevalue);
[Link]("char value: "+charvalue);
[Link]("boolean value: "+boolvalue);
}
}

Output:

***Printing object values***


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40Float object: 50.0
Double object: 60.0
Character object: b
Boolean object: true
*-*-*-*Printing primitive values-*-*-*
byte value: 10short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: b
boolean value: true

*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*
Topics:10

Enumerations in java:
An enumeration (enum for short) in Java is a special
data type which contains a set of predefined constants.

The Enum in Java is a data type which contains a fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY).

Directions (NORTH, SOUTH, EAST, and WEST).

colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.

Java Enums can be thought of as classes which have a fixed set of


constants (a variable that does not change).
The Java enum constants are static and final implicitly.
Enums are used to create our own data type like classes.
The enum data type (also known as Enumerated Data Type) is used to
define an enum in Java.
Example:
class EnumExample1
{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER }
//creating the main method
public static void main(String[] args)
{
//printing all enum
for (Season s : [Link]())
{
[Link](s);
}
[Link]("Value of WINTER is: "+[Link]("WINTER"));
[Link]("Index of WINTER is: "+[Link]("WINTER").
ordinal());
[Link]("Index of SUMMER is: "+[Link]("SUMMER").
ordinal());
}
}

Output:
WINTER
SPRING
SUMMER
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Example: 2
enum players
{
sachin, dravid, virat, dhoni;
}
public class A
{
public static void main(String[] args)
{
players a1 = [Link];

switch(a1)
{
case sachin:
[Link]("Sachin is best bastman ever");
break;

case dravid:
[Link]("Dravid is the best Test Batsman");
break;

case virat:
[Link]("Virat is a Stylish Batsmen");
break;

case dhoni:
[Link]("Dhoni is the best captain ever");
break;

}
}

Output:
Virat is a Stylish Batsmen
Example:3
enum players
{
sachin, virat, dhoni;
}
public class A
{
public static void main(String[] args)
{
players a1 = [Link];
if(a1 == [Link] || a1 == [Link])
{
[Link]("Sachin and Virat are greatest batsmen");
}
else
{
[Link]("Dhoni is the best Captain");
}
}
}
Output:
Dhoni is the best Captain
Example:4
enum games
{
ludo, Chess, Badminton, Cricket;
}
public class A
{
public static void main(String[] args)
{
[Link]("Using for each loop");
for (games index:[Link]())
{
[Link](index);
}
}
}
Output:
Using for each loop
ludo
Chess
Badminton
Cricket
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*
End of The Chapter

You might also like