Professional Documents
Culture Documents
Unit 1 - Java
Unit 1 - Java
Unit 1 - Java
Prepared By:
Dr. ANTONY PAUL RAJ.A M.Sc., M.Phil., B.Ed., Ph.D
Assistant Professor
Department of Computational Studies
School of Arts and Science, SMVEC
PROBLEM SOLVING USING JAVA
(A20CPT305)
UNIT I INTRODUCTION TO JAVA PROGRAMMING
The History and Evolution of Java – Byte code – Java buzzwords – Data types – Variables –
Arrays –operators – Control statements – Type conversion and casting- Basic Concepts of
OOPs – Concepts of classes and objects - Constructors – static keyword – Final with data –
Access control – This key word –Garbage collection – Nested classes and inner classes –
String class.
Inheritance: Basic concepts – Forms of inheritance – Super key word – method overriding –
Abstract classes – Dynamic method dispatch – The Object class. Packages: Defining –
Creating and Accessing –importing packages. Interfaces: Defining – Implementing –
Applying – Variables and extending interfaces.
Collections: List – Vector – Stack – Queue – De queue – Set – Sorted Set. Input / Output
Basics – Streams – Byte streams and Character streams – Reading and Writing Console –
Reading and Writing Files.
Events – Delegation event model – Event handling – Adapter classes. AWT: Concepts of
components –Font class – Color class and Graphics - Introduction to Swing - Layout
management - Swing Components -Java Database Connectivity – JDBC Connections –
JDBC Create Databases - Develop real time applications.
History of Java:
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the
time. The history of Java starts with the Green Team. Java team members (also known as
Green Team), initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known
as the father of Java, in 1995. James Gosling and his team members started the project in the
early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc. Following are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Why had they choose the name Java for Java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc.
They wanted something that reflected the essence of the technology: revolutionary, dynamic,
lively, cool, unique, and easy to spell, and fun to say. According to James Gosling, "Java was
one of the top choices along with Silk". Since Java was so unique, most of the team members
preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is
a kind of espresso bean. Java name was chosen by James Gosling while having a cup of
coffee nearby his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc. Each
new version adds new features in Java.
Evolution of java:
Java bytecode is the instruction set for the Java Virtual Machine.
It acts similar to an assembler which is an alias representation of a C++ code.
As soon as a java program is compiled, java bytecode is generated.
In more apt terms, java bytecode is the machine code in the form of a .class file. With
the help of java bytecode we achieve platform independence in java.
Thus, we have realized that the bytecode implementation makes Java a platform-independent
language. This helps to add portability to Java which is lacking in languages like C or C++.
Portability ensures that Java can be implemented on a wide array of platforms like desktops,
mobile devices, severs and many more. Supporting this, Sun Microsystems captioned JAVA
as "write once, read anywhere" or "WORA" in resonance to thebytecode interpretation.
The Java programming language is a high-level language that can be characterized by all of
the following buzzwords:
Simple
Object-oriented
Distributed
Interpreted
Robust
Secure
Architecture neutral
Portable
High performance
Multithreaded
Dynamic
1. Simple:
Java was designed to be easy for a professional programmer to learn and use
effectively.
It’s simple and easy to learn if you already know the basic concepts of Object
Oriented Programming.
Best of all, if you are an experienced C++ programmer, moving to Java will require
very little effort. Because Java inherits the C/C++ syntax and many of the object-
oriented features of C++, most programmers have little trouble learning Java.
Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
2. Object Oriented
3. Distributed
Java is designed fa or distributed environment of the Internet. Its used for creating
applications on networks.
Java applications can access remote objects on the Internet as easily as they can do in
the local system.
Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.
It provides many features that make the program execute reliably in a variety of
environments.
Java is a strictly typed language. It checks code both at compile time and runtime.
Java takes care of all memory management problems with garbage collection.
Java, with the help of an exception handling, captures all types of serious errors and
eliminates any risk of crashing the system.
6. Secure
7. Architecture Neutral
Java language and Java Virtual Machine helped in achieving the goal of “write once;
run anywhere, any time, forever.”
Changes and upgrades in operating systems, processors and system resources will not
force any changes in Java Programs.
8. Portable
Java Provides a way to download programs dynamically to all the various types of
platforms connected to the Internet.
It helps in generating Portable executable code.
9. High Performance
10. Multithreaded
11. Dynamic
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
JAVA VARIABLES
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
Reserved Area
a
50
RAM
int a=50;//Here a is variable
Types of Variables
o local variable
o instance variable
o static variables
1) Local Variable:
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable:
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not
shared among instances.
3) Static variable:
JAVA ARRAYS:
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
dataType[]arr; (or)
dataTypearr[];
arrayRefVar=new datatype[size];
class Testarray{
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
System.out.println(a[i]);
}}
Output:
10 20 70 40 50
Output:
123
245
445
OPERATORS IN JAVA
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
System.out.println(--x);//10 }} Output: 10 12 12 10
Java Arithmetic Operators:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output: 15 5 50 2 0
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.
1) If Statement:
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in Java.
if statement
if-else statement
if-else-if ladder
nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed }
Example:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18.
Java if-else Statement:
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
````````````````````````````````````````````````````````````````````````````````````````````````
Leap Year Example:
A year is leap, if it is divisible by 4 and 400. But, not by 100.
public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Output:
LEAP YEAR
SWITCH STATEMENT:
Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
Example:
SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
output:
20
LOOPING:
for Loop:
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Statement: The statement of the loop is executed each time until the second condition
is false.
Syntax:
1 2 3 4 5 6 7 8 9 10
The for-each loop is used to traverse array or collection in Java. It is easier to use than simple
for loop because we don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the
defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example:
//Java For-each loop example which prints the elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12 23 44 56 78
WHILE LOOP:
The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false,
the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is
not fixed, it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement ;
}
EXAMPLE:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately. It can be used with for loop or while loop.
SYNTAX:
jump-statement;
continue;
Example:
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
} }
Output: 1 2 3 4 6 7 8 9 10
Break Statement
Syntax:
jump-statement; break;
Example:
BreakExample.java
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
TYPE CONVERSION AND CASTING
In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler
and manual conversion performed by the programmer. Type Casting in Java
Type casting: Convert a value from one data type to another data type is known as type
casting.
Types of Type Casting
There are two types of type casting:
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically. It is safe because
there is no chance to lose data. It takes place when:
Both data types must be compatible with each other.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.
Widening Type Casting Example.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a long type. After
that, the long type is converted into the float type.
Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we do
not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First,
we have converted the double type into long data type after that long data type is converted
into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
System.out.println("After conversion into long type: "+l); //fractional part lost
System.out.println("After conversion into int type: "+i); //fractional part lost
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some
concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism. There
are different levels of inheritance such as.
Polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
DEFINING A CLASS
Def: In the real world, you'll often find many individual objects. Collection of
objects is called class.
A class is a user-defined data type with a template that serves to define its properties.
once the class type has been defined, we can create “variable s” of that type using
declarations that are similar to the basic type declarations.
In java, these variables are termed as instances are of classes, which are the actual
objects.
The basic form of a class definition is:
Class Syntax:-
Class classname
{
type instance-variable1 ;
type instance-variable2 ;
….. FIELDS DECLARATION
…..
type instance-variableN ;
Data is encapsulated in a class by placing data fields inside the body of the class
definition.
These variables are called instance variables because they are created whenever an
object of the class is instantiated.
We can declare the instance variable exactly the same way as we declare local
variables.
Examples:
Class box
{
double height;
double width;
}
The class box contains double integer type instance variables. It allowed to
declare them in one line as
double length, width;
Remember these variables are only declared and therefore no storage space has
been created in the memory.
Simple class
Here is a class called Box that defines three instance variables: width, height, and
depths.
Currently, Box does not contain any methods (but some will be added soon).
class Box
{
double width;
double height;
double depth;
}
As stated, a class defines a new type of data.
In this case, the new data type is called Box.
You will use this name to declare objects of type Box.
It is important to remember that a class declaration only creates a template; it does not
create an actual object.
Thus, the preceding code does not cause any objects of type Box to come into
existence.
To actually create a Box object, you will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
After this statement executes, mybox will be an instance of Box.
Thus, it will have “physical” reality.
For the moment, don’t worry about the details of this statement.
Again, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class.
Thus, every Box object will contain its own copies of the instance variables width,
height, and depth.
To access these variables, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.
For example, to assign the width variable of mybox the value 100, you would use the
following statement:
mybox.width = 100;
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
Box b1 = new Box();
double vol;
b1.width = 10;
b1.height = 20;
b1.depth = 15;
vol = b1.width * b1.height * b1.depth;
System.out.println("Volume is " + vol);
}
}
You should call the file that contains this program BoxDemo.java, because the main(
) method is in the class called BoxDemo, not the class called Box.
When you compile this program, you will find that two .class files have been created,
one for Box and one for BoxDemo.
The Java compiler automatically puts each class into its own .class file. It is not
necessary for both the Box and the BoxDemo class to actually be in the same source
file.
You could put each class in its own file, called Box.java and BoxDemo.java,
respectively.
To run this program, you must execute BoxDemo.class.
When you do, you will see the following output:
Volume is 3000.0
CREATING OBJECTS
Object reference variables act differently than you might expect when an assignment
takes place.
For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object referred
to by b1.
That is, you might think that b1 and b2 refer to separate and distinct objects.
However, this would be wrong. Instead, after this fragment executes, b1 and b2 will
both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object.
This situation is depicted here:
Although b1 and b2 both refer to the same object, they are not linked in any other
way.
For example, a subsequent assignment to b1 will simply unhook b1 from the original
object without affecting the object or affecting b2. For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
METHODS DECLARATION
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Rules for creating Java constructor:
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.
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.
class Student{
String name;
//constructor
rollno = r;
name = n;
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
Output:
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only.
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
EXAMPLE:
class Bike9{
void run(){
speedlimit=400;
obj.run();
}//end of class
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.
this keyword :
EXAMPLE:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,Stringname,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
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.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
1) By nulling a reference:
e=null;
2) By assigning a reference to another:
3) By anonymous object:
new Employee();
finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class as:
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
class Java_Outer_class{
//code
class Java_Inner_class{
//code
There are three advantages of inner classes in Java. They are as follows:
Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Code Optimization: It requires less code to write.
Sometimes users need to program a class in such a way so that no other class can
access it. Therefore, it would be better if you include it within other classes.
If all the class objects are a part of the outer object then it is easier to nest that class
inside the outer class. That way all the outer class can access all the objects of the
inner class.
An inner class is a part of a nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested classes. The non-static
nested classes are also known as inner classes.
Non-static nested class (inner class)
A non-static class that is created inside a class but outside a method is called member inner
class. It is also known as a regular inner class. It can be declared with access modifiers like
public, default, private, and protected.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
Java Member Inner Class Example
In this example, we are creating a msg() method in the member inner class that is accessing
the private data member of the outer class.
TestMemberOuter1.java
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30
Java Anonymous inner class
Java anonymous inner class 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 overloading methods of a class or interface, without
having to actually subclass a class.
In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:
Output:
nice fruits
JAVA STRING:
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. string s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
The Char Sequence interface is used to represent the sequence of characters. String, String
Buffer and String Builder classes implement it. It means, we can create strings in Java by
using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use String Buffer and String
Builder classes.
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
1. By string literal
2. By new keyword
1) String Literal
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
StringExample.java
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.
The java.lang.String class provides many useful methods to perform operations on sequence
of char values.
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());