BCA-2 Java Unit-1 & Unit-2 Notes
BCA-2 Java Unit-1 & Unit-2 Notes
UNIT – I
CHAPTER – I
INTRODUCTION TO JAVA
1. History of Java
Java is a purely object oriented programming language developed from Sun
Microsystems in 1991 by team headed by James Gosling.
Java was initially developed for the electrical home appliances like remote control,
washing machines refrigerators etc.
In 1990, Sun Microsystems got a project called Green project to develop embedded
software for home appliances. Sun Microsystems formed a team headed by James Gosling.
The team concluded that existing programming languages were in adequate for this project
due to their machine dependence.
In 1991, the team developed a platform independent language by extending and
modifying C++ language and named as “Oak”. Later this programming language was
renamed as “Java” due to copy right problems.
Here's a more detailed timeline:
1991: The Green Project at Sun Microsystems, led by James Gosling, begins with the
goal of creating a language for consumer electronics.
1992: The initial prototype, named Oak, is developed.
1994: The team shifts focus to the internet and the language is renamed Java.
1995: Java is officially launched by Sun Microsystems.
1996: The first Java Development Kit (JDK 1.0) is released.
2009: Oracle acquired Sun Microsystems, taking ownership of Java.
2. Java Features
Java provides various features. The main features are as follows.
Simple: Java is a simple language. Java was designed to be easy for the professional
programmer to learn and effectively.
Object Oriented: Java is purely object oriented language. Everything in Java are defined
inside of a class and accessed through object. Main () method is defined inside of a class.
Both compiled and interpreter: Java combines both compiler and interpreter. Java
compiler translates source code into byte code instructions. Java interpreter generates a
machine code that can be directly executable by the machine.
Platform independence and portable: Java programs can be easily moved from one
computer system to another computer, anywhere and anytime. Changes and upgrades
in operating system, processer and system recourses not force any changes in Java
program. Java ensures portability because Java compiler generates byte code
instructions that can be run on any machine.
Distributed: Java is designed as distributed environment of internet. It has the ability to
share both data and programs. This enables multiple programs at multiple remote
locations to work together.
B.Sc - V SEM - Computer Science 1
Programming in Java Prepared by S. Nagesh MCA NET
Secure: Java provides security from viruses and unknown program by providing
firewall between a networked applications and user local computer.
Robust: Java provides strict compile time and runtime checking and eliminates
situations that are error prone.
RMI: Remote Method Invocation allows application to call object located at remote site
and communicate with them.
Memory Management: Java uses Garbage collector to destroy memory of unused
objects.
Multithreaded: Multithreaded means handling multiple tasks simultaneously. Java
supports the multithreaded programming which allows writing a program that does
many things simultaneously.
appletviewer: It is used to run Java applet program without using web browser
jdb (Java debugger): Java debugger helps in finding and the fixing of bugs in Java
language programs.
javadoc: This tool is used to generate API documentation into HTML format from
Java source code. It is interesting to know that Javadoc is the industry standard for
documenting Java classes.
javap: It is used to display the content of the predefined packages of java.
Java Runtime Environment (JRE):
The JRE is a software package that provides the essential components
required to run compiled Java applications. It is intended for end-users who only
need to execute Java programs, not develop them. The JRE includes:
Java Virtual Machine (JVM): JVM is responsible for executing Java bytecode. The
JVM acts as an abstract machine that interprets the bytecode and translates it into
platform-specific machine instructions.
Java Class Libraries: A rich set of pre-written classes and APIs (Application
Programming Interface) that provide fundamental functionalities like
input/output, networking, data structures, and graphical user interface (GUI)
components.
5. Java Primitive Types
Data types specify type of values assigned to a variable. Data types also specify
storage area allocated to a variable. In Java, data types are classified as follows.
Data type
Primitive Non-Primitive
Integer Type:
Integer type represents whole numbers. There are four integer types as given below.
Type size min max
byte 1 byte -27 27-1
short 2 bytes -2 15 215-1
int 4 bytes -231 231-1
long 8 bytes -263 263-1
Floating Type:
Floating point types are used to represent real numbers. There are two floating types
as given below.
Type size min max
float 4 bytes -3.4e-38 3.4e+38
double 8 bytes -1.7e-308 1.7e+308
In Java, the default floating type is double.
Character Type:
Character type represents a single character values enclosed in single quotes. Java
supports a data type char to represent character type. It reserves two bytes of memory. Java
supports Universal code.
Boolean:
Java supports this data type to represent two possible values true or false.
6. CREATING AND EXECUTION OF JAVA PROGRAM
A Java program is a collection of classes, each class consist fields and methods. Every
Java program consists at least one class which defines one method known as main()
method.
Let us create a simple example Java program.
class Example
{
public static void main( String ar[ ])
{
System.out.println(“Hello World”);
}
}
Creating a Java Program:
A Java source program can be created using any text editor.
Open any text editor such as Notepad
Enter the source code
Save the source code with the name of main class name with java extension. The above
program has to be saved with file name “Example.java”
Logical Operators: The logical operators are used to combine two or more Boolean expressions.
In C-Language there are three logical operators. They are as follows.
Operator meaning Description
&& logical AND True when all conditions are true
|| logical OR True when any one of conditions is true
! logical NOT It gives negation of a condition
Assignment Operators: Assignment operators are used to assign the result of right side
expression to the left side variable. Assignment operators are +=, -=, *=, /=, %= and =.
Ex: if b= 11, b+=2 means b=b+2 b= 13
If c=11 , c %=3 means c=c%3 c=2
Increment and Decrement Operator: Increment and decrement operators are used to
increase or decrease the value of an operand by one. These are unary operators since there is a
single operand.
Operator meaning Description
++ Increment Increases value of an operand by one
If a=15, a++; then the value of a is 16
-- Decrement Decreases value of an operand by one true
If a=15, a- -; then the value of a is 14
Increment and decrement operators can be used before variable and after variable.
Pre Increment ++a, if a=10 and b=++a, now a=11 and b=11
Post Increment a++, if a=10 and b=a++, now a=11 and b=10
Pre Decrement --a, if a=21 and b= --a, now a=20 and b=20
Post Decrement a--, if a=21 and b=a--, now a=20 and b=21
Conditional Operator (Ternary operator): The character pair ? and : is called the
Conditional operator or ternary operator. The conditional operator is used to select particular block
depending on the condition.
Syn: variable = (condition) ? value_if_true : value _ if _ false
Ex: if a=10 and b=20
c = (a<b) ? b : a;
If a value is less than b, b is assigned to c or a assigned to c. Now c =20
Bitwise Operators: Bitwise operators are used to perform the operations on binary bits. The
Bitwise Operators are as follows:
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift
Syntax: if (condition)
{
Statements if_true;
}
else
{
Statements if_false;
}
First test condition is evaluated. If it is true, then the statements in if block will be
executed and else-block will be skipped. If test condition is false, then the statements in if-
block will be skipped and else-block statements will be executed.
if – else ladder: It is a multiple selection statement. The general form of simple if
statement is as follows:
Syntax: if (condition1)
{
Statements if_condition1_true;
}
else if (condition2)
{
Statements if_condition2_true;
}
else if (condition3)
{
Statements if_condition3_true;
}
else
{
----
}
First, the condition 1 is evaluated. If it is true, the statements in that if block are
executed and all are skipped. If the condition1 is false, then condition2 is evaluated and
so on. If all conditions are false, then final else statement will be executed.
Switch case:
Switch case is multiple selection statement. The general form of switch case is as
follows:
Syntax: switch (expression)
{
case label1:
statements;
break;
case label2:
statements;
break;
------
default:
statements
}
First the result of expression is evaluated and matched to case values. If the
match is found that case is executed. If no match case found, then the statements in the
default will be executed. Here break keyword is used to jump the control out of switch
block after execution of particular case.
In switch –case, the result of expression must either character or integer type.
Syntax:
while(condition)
{
Statements
Loop counter alteration;
}
Ex:
int i=1;
while (i<=5)
{
System.out.println(“Odd Number:”+i);
i=i+2;
}
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
do-while loop statement:
The do-while loop is also used to execute a block of statement repeatedly based on a
condition. The condition will be evaluated at the end of the loop. It is known as exit
controlled loop. The statements in the loop will executed at least once.
Syntax: do
{
Statements
Loop counter alteration;
} while(condition);
Ex:
int i=1;
do
{
System.out.println(“Odd Number:”+i);
i=i+2;
}while (i<=5);
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
System.out.println(“Odd Number:”+i);
}
Output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
for-each loop statement:
Java 5.0 introduced advanced for loop called as for-each loop. This loop is used to
access each value successively in an array.
Syntax:
for(type var:array)
{
Statements; 10) 453(45
- 450
}
-------
Write a Java program to find reverse of a number 3 –r
class Reverse S=s*10+r =0*10+3=3
{ n=n/10n=45
public static void main(String ar[ ])
10) 45 (4
{
-40
int n=453;
-----
int s=0;
5 -r
System.out.println(“Given number=”+n);
s=s*10+r
while(n!=0) =3*10+5=35
{ n=n/10n=4
int r=n%10;
10) 4 ( 0
s=s*10+r;
-0
n=n/10;
-------
}
4–r
System.out.println(“Reverse number=”+s);
s=s*10+r
}
=35*10+4=354
} // End of the program
n=n/10 n=0;
Compile: javac Reverse.java
here n!=0 condition
Run: java Reverse
false.
Output: Loop terminates.
Given Number=453
Reverse Number=354
if(c==2)
System.out.println(n+“ is Prime”);
else
System.out.println(n+“ is Not Prime”);
}
} // End of the program
CHAPTER-2
DEFINIG CLASSES
10. Class & Object
In object oriented programming, the problem domain is divided into number of
objects. Each object consist data and operations on data. Some objects may share same
properties.
“Collection of objects that have common properties is called as a Class”.
In OOPs a class is defined as a user defined data type that can be used to define
objects as variables. A class definition consist data and operations on data.
Class Declaration: In Java a class can be defined by using a keyword class.
Syntax:
[modifier] class classname [ extends superclass] [ implement interface]
{
Field declarations;
Method definition;
}
Here the keywords inside [ ] brackets are optional. So a basic class definition is as
follows:
class classname
{
Field declarations;
Method definition;
}
Note:
The classname is any valid identifier
Field Declaration: The variables used in a program are declared. Instance variables and
class variables are declared in field declaration part. Variables declared inside class are
called member variables. These variables can be declared as follows:
Syntax:
[modifier] datatype variablename;
Here modifier is any visibility control such as private, public, protected. It is optional.
The default visibility is up to the same package.
Ex:
class Rectangle
{
int length;
int breadth;
}
Method Definition: A method is block of programming code that performs a specific task.
In Java operations on data is defined as method like functions in c++. In Java methods has
to define inside of the class definition.
Syntax:
[modifier] returntype methodname(parameters list)
{
Statements;
}
Return type is a type of value a method can return. It can be void if no value return. The
method name must be a valid identifier.
Eg: void getdata(int x,int y)
{
length=x;
breadth=y;
}
11. Object Creation
Object is an instance of a class. Object is a variable of a class type. Creation of an
object involves two tasks, declaring and initializing object.
Declaration of Object: Object declarations are same as variable declaration.
Syntax: classname objectname1, objectname2;
Ex: Rectangle r1,r2;
The above declaration would not create an object but it creates a variable.
Initializing an object: After declaring an object a physical copy of an object must be
acquired and assigned to that variable. This can be achieved by new operator. The new
operator creates an object reference by dynamically allocating memory for an object of the
class.
Syntax: objectname = new classname( );
Ex: r1=new Rectangle();
r2=new Rectangle();
Now object r1 & r2 consist its own length and breadth variables.
Declaration and initialization of an object can be done in a single statement as
follows:
Rectangle r1=new Rectangle();
Method Invocation:
Method of a class can’t run on their own. They need to be invoked. Instance methods
will be invoked by the objects of that class.
Syntax:
Objectname.methodname(values);
When an object invokes a method, it can pass certain values to the method and the
method can also return values.
Ex: Rectangle r1=new Rectangle();
r1.getdata(30,20);
B.Sc - V SEM - Computer Science 13
Programming in Java Prepared by S. Nagesh MCA NET
13. Constructor
Constructor is a special member method that will be invoked automatically when
object of that class is created. Constructor is used to initialize the instance variables of a
class.
Constructor name is same as class name.
The constructors don’t have any return type even void.
The constructors can’t be private or protected
Constructors can’t be abstract, final
Constructors can’t be overridden
Constructors can be overloaded
In Java there are two types of constructors. They are
1. Default Constructors
2. Parameterized Constructors
Default constructor: A constructor that does not take any parameters is known as default
constructors.
class Abc
{
Abc( )
{
System.out.println(“this is default constructor”);
}
}
Parameterized Constructor: A constructor that takes parameters is called parameterized
constructors. During object creation, the required parameters must be passed to
constructor.
class Abc
{ int x,y;
Abc(int p,int q)
{
x=p;
y=q;
}
}
Here object creation statement must pass arguments to the constructor.
Abc obj=Abc(15,16);
Write a program to demonstrate constructors
class Rectangle
{
int l,b;
Rectangle()
{
l=15,
b=30;
}
Rectangle(int x,int y)
{
l=x;
b=y;
}
void area()
{
int a=l*b;
System.out.println(“Area=”+a);
}
}
class Room
{
public static void main(String ar[])
{
Rectangle r1=new Rectangle(); // Default constructor
Rectangle r2=new Rectangle(20,50); // Parameterized constructor
r1.area();
r2.area();
}
}
Constructor Overloading:
The mechanism of defining two or more constructors in class definition with
different type of arguments or different number of arguments is called Constructor
Overloading.
class Room
{
int l,b;
Room(int x)
{
l=b=x;
}
Room(int x,int y)
{
l=x;
b=y;
}
}
Class / static variables: Class /static variables declaration is preceded with the keyword
static. They are also declared inside a class, but outside a method. There exists only one
copy of static variables per class. All objects of the class share this variable. Static variables
are normally used for constants.
Syntax:
static int var=0;
Static methods: Like static variables, we can also defined methods as static. Such methods
are called static methods. Static methods can be invoked without creation object. Static
methods can be invoked with its class name. Static methods can only access static variables
directly.
Syntax:
static void getdata(parameters);
The Scanner class provides various methods to read specific data types. commonly used
method in Scanner Class are as follows:
nextByte(): This method reads byte type of data
nextShort(): This method reads short type of data
nextInt(): This method read int type of data
nextLong(): This method read long type of data
nextFloat(): This method read float type of data
nextDouble(): This method read double type of data
nextLine(): This method reads a line of text.
nextBoolean(): This method read a Boolean type of data
The following steps are used to read input from the keyboard using the Scanner class.
UNIT – II
CHAPTER-3
ARRAYS, STRINGS IN JAVA
1. Defining Arrays & Creating Arrays
An array is a collection of similar type of elements. Arrays are used to store multiple
values in a single variable.
An array is a memory space that can store multiple values of same data type in
continuous memory locations. Individual elements of an array can be accessed using
subscript or index used inside the brackets. The index will starts from 0 (zero) and ends
with size-1. There are two types of arrays.
One dimensional Array
Multi dimensional Array
One Dimensional Arrays
In one – dimensional array single row of values are stored in single variable.
A single subscript or index is required to access individual array elements.
Creation of One-Dimensional Array:
Creating an array is similar object creation and involves following steps.
Declaring an array
Creating memory location
Declaring an Array:
A One – dimensional array can be declared as follows:
Syntax:
datatype variable[ ]; OR datatype[ ] variable.
Eg:
int m[];
Creating memory location:
In Java memory location for an array can be created using new operator.
Syntax:
Arrayname = new type[size];
Eg:
m=new int[5];
Array variable declaration and memory creation can be done in a single
statement as given below.
int m[]=new int[10];
Initialization of one dimensional array:
An array variable can be initialized as follows.
Syntax: type array[]={list of values};
int m[ ]={10,15,32,14,2};
Two Dimensional Array
Two-dimensional array is used to represent a table of values which are
organized in rows and columns. Two indices are used to access individual values
of an array. One index for row, another index for column.
Creating 2-D array:
int compareTo(String): This is used to compare two strings. It returns integer value.
The value is negative if calling string is less than argument string, positive if calling
string is greater than argument string and zero if both are same.
Ex:
String s1=new String(“Nalgonda”);
String s2=new String(“MGU”);
int x=s1.compareTo(s2);
Here s1 is calling String object
s2 is argument string object
Calling string S1 is greater than Argument string s2
hence the value of x is positive value.
String toUppercase(): It converts all characters in its calling string to upper case and
new string returns.
Ex:
String s1=new String(“Nalgonda”);
String s2=s1.toUppercase();
Now s2=”NALGONDA”;
String toLowercase(): It converts all characters in its calling string to lower case
letters and return a new string.
Ex:
String s1=new String(“Nalgonda”);
String s2=s1.toLowercase();
Now s2=”nalgonda”;
String subString(int x, int y): It returns a substring from calling string starts with x
and ends with y.
Ex:
String s1=new String(“Nalgonda”);
String s2=s1.subString(2,5);
Now value of s2 is “lgon”
4. String Buffer Class
StringBuffer is a subclass of String class. StringBuffer class creates a variable length
strings that can be modified. We can insert characters or strings in middle of a sting and
also appended one string at the end of other string.
A StringBuffer object can be created as follows:
StringBuffer city=new StringBuffer(“Nalgonda”); OR
StringBuffer city=”Nalgodnda”;
String Buffer class methods
StringBuffer class definition includes following methods.
insert(int,string):It inserts a parameter string at the nth position of calling string.
Ex:
StringBuffer s1=new StringBuffer(“Mahtma University”);
s1.insert(6,” Ghandhi ”);
Now the s1 value is Mahatma Gandhi University
B.Sc - V SEM - Computer Science 23
Programming in Java Prepared by S. Nagesh MCA NET
6. Wrapper Classes
Wrapper classes are used to convert primitive data types into object types. Java API
defines wrapper classes for all its primitive types in java.lang package. The wrapper classes
and their primitive types are as follows:
Byte byte
Short short
Integer int
Long long
Float float
Double double
Character char
Boolean boolean
These wrapper classes define constructors and other methods to convert primitive data
values into objects and objects into their primitive types.
Primitive numbers can be converted into object number using respective constructor
method.
Ex:
int x=10;
Integer obj=new Integer(x);
Now 10 is an object.
Object format numbers can be converted into primitive number using typeValue()
method. Here type is based data type.
int x=obj.intValue();
float y=obj.floatValue();
Numeric String objects can be converted into primitive numbers by using parser
method.
parseInt() defined in Integer class
parseLong() defined in Long class
Ex:
String s1=”245”;
Now the number 245 is in string format. This string format can be converted into
integer type using parseInt() method of Integer class.
int x=Integer.parseInt(s1);
Now the number 245 is an integer.
UNIT-II
Chapter – 4
INHERITANCE, INTERFACES AND PACKAGES IN JAVA
7. Inheritance
The process of acquiring object properties of another object is known as inheritance.
Defining a new class from already existing class is known as inheritance. The new class is
known as sub class or derived or child class. The existing class is known as super class, base
class or parent class. The sub class gets all properties and methods of its super class and can
have additional variables and methods. The mechanism of inheritance enables reusability
of existing code.
Defining sub class:
In Java, classes are inherited from another class by using extends keyword.
Syntax;
class subclassname extends superclassname
{
Field declaration;
Method definition;
}
Ex:
class Base
{
int x;
}
class Derived extends Base
{
int y;
}
Types of inheritance
There are 5 types of inheritances. They are as follows:
Single inheritance
Multilevel inheritance
Multiple inheritance
Hierarchical inheritance
Hybrid Inheritance
Single Inheritance:
Deriving one class from a single Base class is known as Single inheritance.
A Base Class
class A
{
int x;
}
class B extends A B Derived class
{
int y;
}
B.Sc - V SEM - Computer Science 26
Programming in Java Prepared by S. Nagesh MCA NET
Multilevel Inheritance:
Defining a class from already derived class is known as multilevel inheritance.
A Base Class
C Derived class
class A
{
int x;
}
class B extends A
{
int y;
}
class C extends B
{
int z;
}
Multiple Inheritance
Deriving a single class from more than one base class is known multiple inheritance.
Java does not support multiple inheritance because the keyword extends can inherit
properties of only one class. But multiple inheritance can achieved with concept of
interface.
C Derived class
Hierarchical inheritance
Deriving multiple classes from single base class is called hierarchical inheritance.
A Base Class
class A
{
int x;
}
class B extends A
{
int y;
}
class C extends A
{
int z;
}
Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
C D
class Single
{
public static void main(String ar[])
{
Rect r=new Rect();
r.getdata(30,15);
r.readdata(16);
r.area();
r.volume();
}
}
8. Method Overriding
The mechanism of defining a method in sub class with the same name and same
signature as in super class method is known as method overriding. The subclass method
override super class method that means the super class method is hidden.
class A
{
void show()
{
System.out.println(“Super class”);
}
}
class B extends A
{
void show()
{
System.out.println(“Sub class”);
}
}
class override
{
public static void main(String ar[])
{
B obj=new B();
B.show();
}
}
9. Final Keyword
The keyword final is used for the following purposes
To declare a symbolic constants. The final keyword is used to define a variable that
does not change
final int a=10;
The final keyword is used to define a method that prevents not overriding in
subclass.
final void display()
{
statements
}
The final keyword is used with class declaration to disallow a class to be inherit.
final class Abc
{
Body of the class
}
10. Abstract Class
A method declaration without definition is known as abstract method. Abstract
methods are defined using a keyword abstract.
abstract void display(); // It is abstract method
A class definition with one or more abstract methods along with normal methods is
known as abstract class.
Abstract classes must be inherited to provide definition for their abstract methods by
overriding them. If its subclass doesn’t implement all the abstract methods then that sub
class also becomes abstract class.
The abstract class can’t be instantiated but can have reference variables. Abstract
class can have constructors, variables and non-abstract methods.
abstract class Abc
{
int x;
void getdata(int p);
{
x=p;
}
abstract void display();
}
class Xyz extends Abc
{
void display()
{
System.out.println(“X=”+x);
}
}
11. Interface
An interface is like a class with all abstract methods and final variables. An interface
doesn’t specify any code to implement. Therefore it is responsibility of the class that
implements an interface to define the code for these abstract methods.
Defining an interface:
The keyword interface is used to define an interface.
Syntax:
interface interface_name
{
Variable declaration;
Method declaration;
}
Eg:
interface Abc
{
int a=10;
void display();
}
Implementing interface:
Interfaces are inherited to classes to provide the implementation code for abstract
methods. The keyword implements is used to implement an interface.
Syntax:
class class_name implements interface_name
{
Body of class
}
A class can implement more than one interface and an interface can be implemented
by more than one class.
The implementing class must provide the definition for all the methods of interface
otherwise that class becomes abstract.
class Xyz implements Abc
{
void display()
{
System.out.println(a);
}
}
12. Package
Package is a group of classes, interfaces and sub packages. The grouping is usually
done according to functionality. Package is a container for classes.
Packages provide a way to hide classes, thus preventing other program to access.
The concept of package increases the reusability of existing code. Java packages are
classified into two types.
Java API packages (System defined, predefined)
User Defined Packages
Java API Packages: Java Application Programming Interface (API) provides a large
number of classes grouped into different packages according to their functionality. The
frequently used API packages are as follows:
java.lang: It includes language support classes. These classes are automatically
imported.
java.io: It includes input / output supporting classes.
B.Sc - V SEM - Computer Science 31
Programming in Java Prepared by S. Nagesh MCA NET
Eg:
import pack.Abc;
class Demopack
{
public static void main(String ar[])
{
int a=10,b=20;
Abc obj=new Abc();
int c=obj.sum(a,b);
System.out.println(“sum=”+c);
}
}
13. Access Specifiers
Access Specifiers defines, how much an element (class, method, variable) is exposed
to other classes and packages. There are four types of access specifiers in Java. They are
Public, Private, Protected and Default
The following table shows the access protection of element.
Same Sub Class Non-Sub class Sub Class Non-Sub Class &
Class Same Package Same Package Other Package Other Package
public Yes Yes Yes Yes Yes
private Yes No No No No
protected Yes Yes No Yes No
default Yes Yes Yes No No
14. Inner Classes
In Java, an inner class is a class defined within another class or interface. It groups
logically related classes, enhancing encapsulation and making code more readable and
aligned with real-world object-oriented design.
Types of Inner Classes:There are basically four types of inner classes in java.
a. Nested Inner Class
b. Method Local Inner Classes
c. Static Nested Classes
d. Anonymous Inner Classes
a. Nested Inner Class: It can access any private instance variable of the outer class. Like
any other instance variable, we can have access modifier private, protected, public and
default modifier.
Eg: class Outer {
class Inner {
public void show()
{
System.out.println("In a nested class method");
}
}
}
b. Method Local Inner Class: Inner class can be declared within a method of an outer
class
class Outer {
void outerMethod()
{
System.out.println("inside outerMethod");
class Inner {
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
}
}
c. Static Inner Class: A static class defined inside another class. It cannot access non-static
members of the outer class directly.
class Outer
{
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
static class Inner {
public static void display()
{
System.out.println("inside inner class Method");
}
}
}
d. Anonymous Inner Class: An anonymous class in Java is an inner class which is declared
without any class name at all. In other words, a nameless inner class in Java is called an
anonymous inner class. Since it does not have a name, it cannot have a constructor.
Anonymous inner classes are used when you want to create a simple class that is needed
for one time only for a specific purpose.
Eg:
Test t=new Test()
{
public void inner_method()
{
System.out.println(“This is anonymous class”);
}
};