Java UNIT-1
Java UNIT-1
Telangana.
COURSE FILE
OF
Regulation R22
Prepared by
Professor
UNIT - I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
coping with complexity, abstraction mechanisms. A way of viewing world – Agents,
responsibility, messages, methods, History of Java, Java buzzwords, data types, variables,
scope and lifetime of variables, arrays,operators, expressions, control statements, type
conversion and casting, simple java program, concepts of classes, objects, constructors,
methods, access control, this keyword, garbage collection, overloading methods and
constructors, method binding, inheritance, overriding and exceptions, parameter passing,
recursion, nested and inner classes, exploring string class.
UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass,
subtype, substitutability, forms of inheritance specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance. Member
access rules, super uses, using final with inheritance, polymorphism- method overriding,
abstract classes, the Object class.
Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing
packages, differences between classes and interfaces, defining an interface, implementing
interface, applying interfaces, variables in interface and extending interfaces. Exploring
java.io.
UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of
exception handling, Termination or resumptive models, exception hierarchy, usage of try,
catch, throw, throws and finally, built in exceptions, creating own exception subclasses.
String handling, Exploring java.util. Differences between multithreading and multitasking,
thread life cycle, creating threads, thread priorities, synchronizing threads, inter thread
communication, thread groups, daemon threads. Enumerations, autoboxing, annotations,
generics.
UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event
model, handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user
interface components- labels, button, canvas, scrollbars, text components, check box,
checkbox groups, choices,lists panels – scrollpane, dialogs, menubar, graphics, layout
manager – layout manager types – border,grid, flow, card and grid bag.
UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent,Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes,Tabbed Panes, Scroll Panes, Trees, and Tables.
TEXTBOOKS:
1. Java the complete reference, 7th edition, Herbert schildt, TMH.
2. Understanding OOP with Java, updated edition, T. Budd, Pearson education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J.Nino and F.A. Hosch, John
wiley
& sons.
2. An Introduction to OOP, third edition, T. Budd, Pearson education.
3. Introduction to Java programming, Y. Daniel Liang, Pearson education.
4. An introduction to Java programming and object-oriented application development, R.A.
Johnson- Thomson.
5. Core Java 2, Vol 1, Fundamentals, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education.
6. Core Java 2, Vol 2, Advanced Features, Cay.S. Horstmann and Gary Cornell, eighth
Edition,
Pearson Education
7. Object Oriented Programming with Java, R.Buyya, S.T.Selvi, X.Chu, TMH.
8. Java and Object Orientation, an introduction, John Hunt, second edition, Springer. 9.
Maurach’s
Beginning Java2 JDK 5, SPD.
UNIT - I
OBJECT-ORIENTED THINKING AND JAVA BASICS
As the name suggests, Object-Oriented Programming or OOP refers to languages that use
objects in programming. They use objects as a primary source to implement what is to
happen in the code. Objects are seen by the viewer or user, performing tasks assigned by
you. Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism etc. in programming. The main aim of OOP is to bind together the
data and the functions that operate on them so that no other part of the code can access this
data except that function.
Object-oriented programming paradigm methods enable us to create a set of objects that work
together to produce software that is better understandable and models their problem domains
than those produced using traditional techniques. The software produced using an object-
oriented programming paradigm is easier to adapt to the changing requirements, easier to
maintain, create modules of functionality, promote greater design, be more robust, and
perform desired work efficiently.
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code.
You should extract out the codes that are common for the application and place them at a
single place and reuse them instead of repeating it.
Although, Java has become a popular programming language for developing the web-
application, android apps, IoT applications, etc. Still, C has not lost its popularity because it is
used to develop firmware, operating system, and other system utilities.
APPLICATION
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords. A list of the most important features of the Java language
is given below.
1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.There
are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API (Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
4. Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
5. Robust
6. Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.In C programming, int data type occupies 2 bytes
of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
7. Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
8. High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
9. Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
10. Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
11. Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
A way of viewing the world is an idea to illustrate the object-oriented programming concept
with an example of a real-world situation.
Let us consider a situation: I am at my office and I wish to get food to my family members
who are at my home from a hotel. Because of the distance from my office to home, there is
no possibility of getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delivery community), tell them
the variety and quantity of food and the hotel name from which I wish to deliver the food to
my family members. Look at the following image.
Responsibilities
In object-oriented programming, behaviors of an object described in terms of responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered to
my family). The agent (zomato) free to use any technique that solves my problem. By
discussing a problem in terms of responsibilities increases the level of abstraction. This
enables more independence between the objects in solving complex problems.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes
(objects) of a community. This graphical representation shows classes listed in a hierarchical
tree-like structure. In this more abstract class listed near the top of the tree, and more specific
classes in the middle of the tree, and the individuals listed near the bottom.
In object-oriented programming, classes can be organized into a hierarchical
inheritance structure. A child class inherits properties from the parent class that higher
in the tree.
Method Binding, Overriding, and Exception
In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the child.
Or a class may provide multiple definitions to a single method to work with different
arguments (overloading).
The search for the method to invoke in response to a request (message) begins with the class
of this receiver. If no suitable method is found, the search is performed in the parent class of
it. The search continues up the parent class chain until either a suitable method is found or the
parent class chain is exhausted. If a suitable method is found, the method is executed.
Otherwise, an error message is issued.
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#,
Python, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit (object / class). In
OOP, every object is associated with its data and code. In programming, data is defined as
variables and code is defined as methods. The java programming language uses the class
concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another
object or one class to another class. In inheritance, we derive a new class from the existing
class. Here, the new class acquires the properties and behaviors from the existing class. In the
inheritance concept, the class which provides properties is called as parent class and the class
which recieves the properties is called as child class. The parent class is also known as base
class or supre class. The child class is also known as derived class or sub class.
In the inheritance, the properties and behaviors of base class extended to its derived class, but
the base class never receive properties or behaviors from its derived class.
Polymorphism
Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviours. The java uses method
overloading and method overriding to implement polymorphism.
Abstraction
Abstraction is hiding the internal details and showing only essential functionality. In the
abstraction concept, we do not show the actual implementation to the end user, instead we
provide only essential things. For example, if we want to drive a car, we do not need to know
about the internal functionality like how wheel system works? how brake system works? how
music system works? etc.
HISTORY OF JAVA
Java is a computer programming language. Java was created based on C and C++. Java uses
C syntax and many of the object-oriented features are taken from C++. Before Java was
invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc.
These languages had few disadvantages which were corrected in Java. Java also innovated
many new features to solve the fundamental problems which the previous languages could
not solve. Java was invented by a team of 13 employees of Sun Microsystems, Inc. which is
lead by James Gosling, in 1991. The team includes persons like Patrick Naughton, Chris
Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as a part of the Green project.
Initially, it was called Oak, later it was changed to Java in 1995.
Asymptotic Notations:
Asymptotic Notations are mathematical notations that allow you to analyze an algorithm’s
running time by identifying its behavior as its input size grows. This is also referred to as
an algorithm’s growth rate.Asymptotic notations are the mathematical notations used to
describe the running time of an algorithm when the input tends towards a particular value
or a limiting value.
Note - When we calculate time complexity of an algorithm, we consider only input data and
ignore the remaining things, as they are machine dependent. We check only, how our
program is behaving for the different input values to perform all the operations like
Arithmetic, Logical, Return value and Assignment etc.,
Calculating Time Complexity of an algorithm based on the system configuration is a very
difficult task because the configuration changes from one system to another system. To solve
this problem, we must assume a model machine with a specific configuration. So that, we can
able to calculate generalized time complexity according to that model machine.
To calculate the time complexity of an algorithm, we need to define a model machine. Let us
assume a machine with following configuration...
1. int i = 1;
2. do
3. {
4. i++;
5. }while(i<=n);
In above scenario, loop is executed 'n' times. Therefore, time complexity of this loop is O(n).
1. int i=1;
2. do
3. {
4. i = i*c;
5. }while(i<=n);
1. int i=0;
2. do{
3. do{
4. int j =0;
5. j++;
6. }while(j<=i);
7. i++;
8. }while(i<=n-1);
In this case, in each iteration of i, inner loop is executed 'n' times. The time complexity of a
loop is equal to the number of times the innermost statement is to be executed.
Infinite loop is executed "Infinite times". Therefore, there is no "algorithm time complexity"
for an infinite loop.
1. int i=1;
2. do{
3. i++;
4. }while(i<=m);
5.
6. int j=1;
7. do{
8. j++;
9. }while(j<=n);
Time complexity of different loops is equal to the sum of the complexities of individual loop.
Therefore,
Generally, when a program is under execution it uses the computer memory for THREE
reasons. They are as follows...
Note - When we want to perform analysis of an algorithm based on its Space complexity, we
consider only Data Space and ignore Instruction Space as well as Environmental Stack.
That means we calculate only the memory required to store Variables, Constants, Structures,
etc.,
DATA TYPES
Java programming language has a rich set of data types. The data type is a category of data
stored in variables. In java, data types are classified into two types and they are as follows.
The following table provides more description of each primitive data type.
These are built-in data types These are created by the users
JAVA VARIABLES
A variable is a named memory location used to store a data value. A variable can be defined
as a container that holds a data value.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;
• Local variables
• Instance variables or Member variables or Global variables
• Static variables or Class variables
• Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local
variable is visible within the method in which it is declared. The local variable is created
when execution control enters into the method or block and destroyed after the method or
block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Instance variables or member variables or global variables
The variables declared inside a class and outside any method, constructor or block are known
as instance variables or member variables. These variables are visible to all the methods of
the class. The changes made to these variables by method affects all the methods in the class.
These variables are created separate copy for every object of that class.
Let's look at the following example java program to illustrate instance variable in java.
Static variables or Class variables
A static variable is a variable that declared using static keyword. The instance variables can
be static variables but local variables can not. Static variables are initialized only once, at the
start of the program execution. The static variable only has one copy per class irrespective of
how many objects we create.
The static variable is access by using class name.
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college" refers to the common property
of all objects. If we make it static, this field will get the memory only once.
Output:
JAVA ARRAY
An array is a collection of similar data values with a single name. An array can also be
defined as, a special type of variable that holds multiple values of the same data type at a
time.
In java, arrays are objects and they are created dynamically using new operator. Every array
in java is organized using index values. The index value of an array starts with '0' and ends
with size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
• Single Dimensional Array
• Multi-Dimensional Array
SINGLE DIMENSIONAL ARRAY IN JAVA
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
Output:
10
20
70
40
50
MULTIDIMENSIONAL ARRAY IN JAVA
In such case, data is stored in row and column-based index (also known as matrix form).
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array
variable, specify each additional index using another set of square brackets. We use the
following syntax to create two-dimensional array.
Syntax
When we create a two-dimensional array, it created with a separate index for rows and
columns. The individual element is accessed using the respective row index followed by the
column index. A multidimensional array can be initialized while it has created using the
following syntax.
Syntax
When an array is initialized at the time of declaration, it need not specify the size of the array
and use of the new operator. Here, the size is automatically decided based on the number of
values that are initialized.
Example
The above statement creates a two-dimensional array of three rows and two columns.
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.
123
245
445
JAVA OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. Java provides a
• Arithmetic Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators
ARITHMETIC OPERATORS
In java, arithmetic operators are used to performing basic mathematical operations like
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
Operator Meaning Example
/ Division 10 / 5 = 2
++ Increment a++
-- Decrement a--
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two posible results either TRUE or FALSE. In simple words, the relational
operators are used to define conditions in a program. The following table provides
< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE
> Returns TRUE if the first value is larger than second value otherwise 10 > 5 is
returns FALSE TRUE
<= Returns TRUE if the first value is smaller than or equal to second 10 <= 5
value otherwise returns FALSE is
FALSE
>= Returns TRUE if the first value is larger than or equal to second 10 >= 5
value otherwise returns FALSE is TRUE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5
is TRUE
When we run the above example code, it produces the following output.
LOGICAL OPERATORS
The logical operators are the symbols that are used to combine multiple conditions into one
& Logical AND - Returns TRUE if all conditions are TRUE otherwise false &
returns FALSE true =>
false
^ Logical XOR - Returns FALSE if all conditions are same otherwise true ^
returns TRUE true =>
false
Operator Meaning Example
! Logical NOT - Returns TRUE if condition is FLASE and returns !false =>
FALSE if it is TRUE true
&& short-circuit AND - Similar to Logical AND (&), but once a false &
decision is finalized it does not evaluate remianing. true =>
false
ASSIGNMENT OPERATORS
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators in the java
programming language.
Operator Meaning Example
+= Add both left and right-hand side values and store the result into left- A += 10
hand side variable
-= Subtract right-hand side value from left-hand side variable value and A -= B
store the result into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and A *= B
store the result into left-hand side variable
|= Logical OR assignment -
When we run the above example code, it produces the following output.
BITWISE OPERATORS
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on binary
values. The following table describes all the bitwise operators in the java programming
language.
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A& B
⇒ 16
(10000)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is A^ B
1 ⇒ 13
(01101)
<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the right by the A >> 2
specified number of positions ⇒6
(00110)
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first, we verify a condition, then
we perform one operation out of the two operations based on the condition result. If the
condition is TRUE the first option is performed, if the condition is FALSE the second option
Syntax
JAVA EXPRESSIONS
In any programming language, if we want to perform any calculation or to frame any
condition etc., we use a set of symbols to perform the task. These set of symbols makes an
expression.In the java programming language, an expression is defined as follows.
In the above definition, an operator is a symbol that performs tasks like arithmetic
Operands are the values on which the operators perform the task. Here operand can be a
follows.
• Infix Expression
• Postfix Expression
• Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.The
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
Example
JAVA CONTROL STATEMENTS
In java, the default execution flow of a program is a sequential order. But the sequential order
of execution flow may not be suitable for all situations. Sometimes, we may want to jump
from line to another line, we may want to skip a part of the program, or sometimes we may
want to execute a part of the program again and again. To solve this problem, java provides
control statements.
In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of
execution according to our requirements. Java provides several control statements, and they
• Jump Statements
In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed
• if-else statement
• if-elif statement
• nested if statement
• switch statemen
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then
decides the execution of a block of statements. If the condition is True, then the block of
statements is executed and if it is False, then the block of statements is ignored. The syntax
Java Program
and the condition is evaluated to False. Then the if statement ignores the execution of its
output as follows.
In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the
given condition then decides which block of statements to be executed based on the condition
result. If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed. The syntax and execution flow of if-else
statement is as follows.
Let's look at the following example java code.
Writing an if statement inside another if-statement is called nested if statement. The general
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
Writing an if-statement inside else of an if statement is called if-else-if statement. The general
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Let's look at the following example java code.
Using the switch statement, one can select only one option from more number of options very
easily. In the switch statement, we provide a value that is to be compared with a value
associated with each option. Whenever the given value matches the value associated with an
option, the execution starts from that option. In the switch statement, every option is defined
as a case.The switch statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
In java, the iterative statements are also known as looping statements or repetitive statements.
The iterative statements are used to execute a part of the program repeatedly as long as the
given condition is True. Using iterative statements reduces the size of the code, reduces the
code complexity, makes it more efficient, and increases the execution speed. Java provides
• while statement
• do-while statement
• for statement
• for-each statement
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control
looping statement. The syntax and execution flow of while statement is as follows.
Let's look at the following example java code.
repeatedly as long as given the condition is TRUE. The do-while statement is also known as
the Exit control looping statement. The do-while statement has the following syntax.
Let's look at the following example java code.
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. The for statement has the following syntax and
In for-statement, the execution begins with the initialization statement. After the
initialization statement, it executes Condition. If the condition is evaluated to true, then the
block of statements executed otherwise it terminates the for-statement. After the block of
statements execution, the modification statement gets executed, followed by condition again.
Let's look at the following example java code.
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to
traverse through an array or collection in Java. The for-each statement also known
as enhanced for statement. The for-each statement executes the block of statements for each
The for-each statement has the following syntax and execution flow diagram.
In java, the jump statements are used to terminate a block or take the execution control to the
• break
• continue
• return
Example:
Continue Statement In Java
The continue statement is used to move the execution control to the beginning of the
looping statement. When the continue statement is encountered in a looping statement,
the execution control skips the rest of the statements in the looping block and directly
jumps to the beginning of the loop. The continue statement can be used with looping
statements like while, do-while, for, and for-each.
When we use continue statement with while and do-while statements, the execution
control directly jumps to the condition. When we use continue statement with for
statement the execution control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.
Example:
Java Continue Statement with Inner Loop
It continues inner loop only if you use the continue statement inside the inner loop.
ContinueExample2.java
Output:
11
12
13
21
23
31
32
33
In Java programming, the return statement is used for returning a value when the execution of
the block is completed. The return statement inside a loop will cause the loop to break and
further statements will be ignored by the compiler.
In Java, every method is declared with a return type such as int, float, double, string,
etc.These return types required a return statement at the end of the method. A return keyword
is used for returning the resulted value.The void return type doesn't require any return
statement. If we try to return a value from a void method, the compiler shows an error.
Following are the important points must remember while returning a value:
o The return type of the method and type of data returned at the end of the method
should be of the same type. For example, if a method is declared with the float return
type, the value returned should be of float type only.
o The variable that stores the returned value after the method is called should be a
similar data type otherwise, the data might get lost.
o If a method is declared with parameters, the sequence of the parameter must be the
same while declaration and method call.
Syntax:
The syntax of a return statement is the return keyword is followed by the value to be returned.
1. return returnvalue;
SampleReturn1.java
Output:
x=3
y=8
The greater number among x and y is: 8
In the above Java code, the method CompareNum is defined with the int return type. It
compares the x and y values and returns the greater number.
Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
target data type may be smaller than the source data type when converting the data type to
another data type, that’s why it is also called narrowing conversion.
Syntax/Declaration:-
target_datatype = (target_datatype)source_variable;
( ): is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
Type Casting example –
float x;
byte y;
y=(byte)x; //line 3
Example:
double x=9.78;
int y=(int)x;
int y= 9;
In Line 3: you can see that, we are converting float(source) data type into byte(target)
data type.
2. Type conversion : In type conversion, a data type is automatically converted into
another data type by a compiler at the compiler time. In type conversion, the target data
type cannot be smaller than the source data type, that’s why it is also called widening
conversion. One more important thing is that it can only be applied to compatible data
types.
Type Conversion example –
int x=30;// source datatype
float y;// target datatype
y=x; // y==30.000000.
Type casting takes place during the Whereas type conversion is done at the
5.
program design by programmer. compile time.
S.NO TYPE CASTING TYPE CONVERSION
Type casting is also called narrowing Whereas type conversion is also called
conversion because in this, the widening conversion because in this, the
6.
destination data type may be smaller destination data type can not be smaller
than the source data type. than the source data type.
Type casting is more efficient and Whereas type conversion is less efficient
8.
reliable. and less reliable.
CONCEPTS OF CLASSES
Java is an object-oriented programming language, so everything in java program must be
based on the object concept. In a java programming language, the class concept defines the
skeleton of an object.
The java class is a template of an object. The class defines the blueprint of an object. Every
class in java forms a new data type. Once a class got created, we can generate as many
objects as we want. Every class defines the properties and behaviors of an object. All the
objects of a class have the same properties and behaviors that were defined in the class.
Every class of java programming language has the following characteristics.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods. Following is the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
• The data, or variables, defined within a class are called instance variables.
• The code is contained within methods.
• The methods and variables defined within a class are called members of the class.
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is
said to be instantiated. All the objects that are created using a single class have the same
properties and methods. But the value of properties is different for every object. Following is
the syntax of class in the java.
Syntax
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.
Here, we are creating a main() method inside the class.
File: Student.java
Output:
0
null
In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main() method
in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.
File: TestStudent1.java
Output:
0
null
CONSTRUCTORS IN JAVA
Java constructors or constructors in Java is a terminology used to construct something in
our programs. A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial
values for object attributes.
// Driver class
class ABC {
// Default Constructor
ABC()
{
System.out.println("Default constructor");
}
// Driver function
public static void main(String[] args)
{
ABC obj = new ABC();
}
}
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.
Now the most important topic that comes into play is the strong incorporation of OOPS
with constructors known as constructor overloading. Just like methods, we can overload
constructors for creating objects in different ways. The compiler differentiates constructors
on the basis of the number of parameters, types of parameters, and order of the parameters.
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not
be same as the class name.
In Java, a copy constructor is a special type of constructor that creates an object using another
object of the same Java class. It returns a duplicate copy of an existing object of the class.
We can assign a value to the final field but the same cannot be done while using the clone()
method. It is used if we want to create a deep copy of an existing object. It is easier to
implement in comparison to the clone() method.
In this example, we are going to copy the values of one object into another using Java
constructor.
1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }
Output:
111 Karan
111 Karan
Copy Constructor Vs clone() Method
Both the copy constructor and the clone() method are used to create a copy of an existing
object of the class. But the use of copy constructor is easier and better in comparison to the
clone() method because of the reasons given below:
o If we are using the clone() method it is necessary to import the Cloneable The
method may throw the exception CloneNotSupportException. So, handling the
exception in a program is a complex task. While in copy constructor there are no such
complexities.
o We cannot assign a value if the fields are final. While in the copy constructor we can
assign values to the final fields.
o The object returned by the clone() method must be typecast. While in copy
constructor there is no such requirement.
METHOD IN JAVA
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods. In this section, we will learn what is a method
in Java, types of methods, method declaration, and how to call a method in Java.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we
call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
Demo.java
Output:
In the above example, we have used three predefined methods main(), print(), and max().
We have used these methods directly without declaration because they are predefined. The
print() method is a method of PrintStream class that prints the result on the console. The
max() method is a method of the Math class that returns the greater of two numbers.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
EvenOdd.java
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }
Output 1:
Output 2:
There are two types of modifiers 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.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
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.
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.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
•
The public members can be accessed everywhere.
• The private members can be accessed only inside the same class.
• The protected members are accessible to every child class (same package or other
packages).
• The default members are accessible within the same package but not outside the
package
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object. Sometimes a method will need to refer to the object that invoked
it. To allow this, Java defines the this keyword. this can be used inside any method to refer to
the current object. That is, this is always a reference to the object on which the method was
invoked. You can use this anywhere a reference to an object of the current class’ type is
permitted.
This keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.
Output:
GARBAGE COLLECTION
Garbage collection in Java is the automated process of deleting code that’s no longer needed
or used. This automatically frees up memory space and ideally makes coding Java apps easier
for developers.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
3) By anonymous object:
1. new Employee();
finalize() method
Sometimes an object will need to perform some action when it is destroyed. For example, if
an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed. To handle
such situations, Java provides a mechanism called finalization. By using finalization, you can
define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector. To add a finalizer to a class, you simply define the finalize( ) method. The
Java run time calls that method whenever it is about to recycle an object of that class. Inside
the finalize( ) method, you will specify those actions that must be performed before an object
is destroyed. The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects. Right before
an asset is freed, the Java run time calls the finalize( ) method on the object.
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
gc( ) method
The gc() method is used to invoke the garbage collector to perform cleanup processing that is
destroying the unreferenced objects. The gc() is found in System and Runtime classes.
Output:
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Output:
22
33
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Output:
22
24.
METHOD BINDING
Binding means an association of method call to the method definition. In other words
Connecting a method call to the method body is known as binding.
1. Static Binding
2. Dynamic Binding
Static Binding:
Static Binding is the binding that can be done at the compile time is know as static binding.
In static binding the compiler knows that methods cannot be overridden and will be accessed
by the object of the class. It is also know as early binding.
Example program:
class India {
Output:
We are in India
We are in India
We are in Delhi
Dynamic binding:
Dynamic binding is also referred to as a run-time polymorphism. In this type of binding, the
functionality of the method call is not decided at compile-time. In other words, it is not
possible to decide which piece of code will be executed as a result of a method call at
compile-time.
Consider two classes A and B such that A is the superclass of B. Assume B implements a
method already implemented in its parent class, thus overriding it. Now, this means when a
method is called on an object of the subclass type B, the implementation of the method in the
subclass will be used, even if the method is invoked through a reference of the superclass
type A.
Conditions:
• Inheritance: There must be a superclass and one or more subclasses that inherit from
the superclass. The superclass should define the method that is overridden in the
subclasses.
• Method Overriding: The subclass must override the method defined in the
superclass. The method signature (i.e., the name and parameter types) must be the
same in both the superclass and the subclass.
• Upcasting: The object of the subclass must be upcast to the type of the superclass.
This is necessary because the reference variable used to call the method must be of
the same type as the superclass.
• Method Invocation: The method must be called on the object of the subclass through
the reference variable of the superclass. The implementation of the method that is
invoked will be determined at runtime based on the actual type of the object being
used.
Limitations :
class India {
public void locate() {
System.out.println("We are in India");
}
}
class SubIndia extends India {
Output:
We are in India
We are in Delhi
We are in Delhi
Explanation:
• In this code, there is a superclass called India that has a method called locate(), which
simply prints "We are in India". The subclass SubIndia extends India and overrides
the locate() method to print "We are in Delhi".
• In the main() method, an object of India is created and its locate() method is called,
which prints "We are in India".
• Then, an object of SubIndia is created and upcast to the type of India. When
the locate() method is called on this object using the India reference variable, dynamic
binding comes into play and the overridden locate() method in the SubIndia class is
called, printing "We are in Delhi". This is because the actual type of the object is
SubIndia, and so its implementation of the locate() method is used.
• Finally, an object of SubIndia is created directly and its locate() method is called,
which again prints "We are in Delhi".
It takes place using normal functions It takes place using virtual functions
INHERITANCE CONCEPT
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in another
class. The inheritance provides a great advantage called code re-usability. With the help of
code re-usability, the commonly used code in an application need not be written again and
again.
The inheritance can be defined as follows.
The inheritance is the process of acquiring the properties of one class to another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.
The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.
CREATING CHILD CLASS IN JAVA
In java, we use the keyword extends to create a child class. The following syntax used to
create a child class in java.
Syntax
In a java programming language, a class extends only one class. Extending multiple classes is
not allowed in java.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
1. The method must have the same name as in the parent class.
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
class A{
public void number() {
int a=10;
System.out.println("a="+a);
}
}
class B extends A {
@Override
public void number() {
int a=30;
System.out.println("a="+a);
}
}
class Main {
public static void main(String[] args) {
B s1 = new B();
s1.number();
}
}
Output: 30
The method overriding is the process of re-defining a method in a child class that is already
defined in the parent class. When both parent and child classes have the same method, then
that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the method
which acquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method
binding which happens at run time is known as late binding. So, the method overriding
follows late binding.
EXCEPTION IN JAVA
An exception in java programming is an abnormal situation that is raised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use the
exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism
with a large number of built-in classes to handle most of the exceptions automatically.
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as follows.
• When we try to open a file that does not exist may lead to an exception.
• When the user enters invalid input data, it may lead to an exception.
• When a network connection has lost during the program execution may lead to an
exception.
• When we try to access the memory beyond the allocated range may lead to an
exception.
• The physical device problems may also lead to an exception.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7. public static void main(String args[]){
8. Operation op=new Operation();
9. System.out.println("before change "+op.data);
10. op.change(500);
11. System.out.println("after change "+op.data);
12. }
13. }
Output: before change 50
after change 50
1. class Operation2{
2. int data=50;
3. void change(Operation2 op){
4. op.data=op.data+100; //changes will be in the instance variable. The original value
will be changed as we are trying to pass the objects. Objects are passed by reference.
5. }
6. public static void main(String args[]){
7. Operation2 op=new Operation2();
8. System.out.println("before change "+op.data);
9. op.change(op);// passing the object as a value using pass-by-reference
10. System.out.println("after change "+op.data);
11. }
12. }
RECURSION IN JAVA
Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Output:
hello
hello
...
java.lang.StackOverflowError
Java Recursion Example 2: Finite times
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
In Java, just like methods, variables of a class too can have another class as its member.
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.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
class Outer_Demo {
class Inner_Demo {
}
}
Nested classes are divided into two types −
Inner classes are a security mechanism in Java. We know a class cannot be associated with
the access modifier private, but if we have the class as a member of other class, then the
inner class can be made private. And this is also used to access the private members of a
class.
Inner classes are of three types depending on how and where you define them. They are −
• Inner Class
• Method-local Inner Class
• Anonymous Inner Class
Inner Class
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we
make the inner class private and access the class through a method.
Example
Live Demo
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class, and
this method is invoked from the main method.
If you compile and execute the above program, you will get the following result −
Output
In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.
Example
Live Demo
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
If you compile and execute the above program, you will get the following result −
Output
It is an inner class without a name and for which only a single object is created. An
anonymous inner class can be useful when making an instance of an object with certain
“extras” such as overriding methods of a class or interface, without having to actually
subclass a class.
Here, an object to Age is not created but an object of Myclass is created and copied in the
entire class code as shown above. This is possible only with anonymous inner class. Such a
class is called ‘anonymous inner class’, so here we call ‘Myclass’ as anonymous inner
class.
Now let us do discuss the difference between regular class(normal classes) and Anonymous
Inner class
• A normal class can implement any number of interfaces but the anonymous
inner class can implement only one interface at a time.
• A regular class can extend a class and implement any number of interfaces
simultaneously. But anonymous Inner class can extend a class or can implement
an interface but not both at a time.
• For regular/normal class, we can write any number of constructors but we can’t
write any constructor for anonymous Inner class because the anonymous class
does not have any name and while defining constructor class name and
constructor name must be same.
Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing
Members of the Anonymous Class
Like local classes, anonymous classes can capture variables; they have the same access to
local variables of the enclosing scope:
• An anonymous class has access to the members of its enclosing class.
• An anonymous class cannot access local variables in its enclosing scope that are
not declared as final or effectively final.
• Like a nested class, a declaration of a type (such as a variable) in anonymous
class shadows any other declarations in the enclosing scope that have the same
name.
A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.
o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or
TestOuter1.java
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of the Outer class because the nested
class is static and static properties, methods, or classes can be accessed without an object.
Syntax
class MyOuter {
static class Nested_Demo {
}
}
Key Points to Remember
• Java treats the inner class as a regular member of a class. They are just like methods
and variables declared inside a class.
• Since inner classes are members of the outer class, you can apply any access
modifiers like private, protected to your inner class which is not possible in normal
classes.
• Since the nested class is a member of its enclosing outer class, you can use the dot (.)
notation to access the nested class and its members.
• Using the nested class will make your code more readable and provide better
encapsulation.
• Non-static nested classes (inner classes) have access to other members of the
outer/enclosing class, even if they are declared private.
The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations on
String objects such as trimming, concatenating, converting, comparing, replacing strings
etc.Java String is a powerful concept because everything is treated as a String if you submit
any form in window based, web based or mobile application.
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Output:
SACHIN
sachin
Sachin
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
Output:
Sachin
Sachin
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
Stringoperation3.java
Output:
true
true
Stringoperation4.java
Output:
S
h
The String class length() method returns length of the specified String.
Stringoperation5.java
Output:
The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.
Stringoperation8.java
Output: