Java - Unit-1 - Final

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 108

1

1.0 Procedure oriented programming(POP)

POP is a conventional way of programming. Procedural programming is where the primary


focus is on getting the task done in sequential order. Flowchart organizes the flow of control
of the program. If the program is extensive, it is structured in some small units called
functions, which shares global data. Here, the concern of data security arises, as there is an
unintentional change in the program by functions.

POP characteristics

 While designing a program, POP follows a top-down programming approach.


 Majority of the functions allows global data to be shared.
 It also divides larger programs into smaller parts called as functions.
 It allows a free data movement around the system from functions to functions.
 Data is transformed by the functions from one form to another.
 It gives importance to the concept of the functions.

1.2 Object oriented programming paradigm:

Object-oriented programming (OOP) is a programming paradigm based upon objects (having both data


and methods) that aims to incorporate the advantages of modularity and reusability. Objects, which are
usually instances of classes, are used to interact with one another to design applications and computer
programs.
The important features of object–oriented programming are −

 Bottom–up approach in program design


 Programs organized around objects, grouped in classes
 Focus on data with methods to operate upon object’s data
 Interaction between objects through functions
 Reusability of design through creation of new classes by adding features to existing classes
2

Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#, Perl,
Python, Ruby, and PHP.

Advantages of Object Oriented Programming 

1. Data Re-usability:- “Write a once and use multiple time” we can achieve this by
using class. Once We Write a class we can bus it number of time by creating the
object for class.
2. Data Redundancy:- Inheritance is the good feature for data redundancy if you need
a same functionality in multiple class you can write a common class for the same
functionality and inherit that class to sub class.
3. Easy Maintenance:- It is easy to maintain and modify existing code as new objects
can be created with small differences to existing ones.
4. Data hiding:- Implementation details are hidden from other modules and other
modules has a clearly defined interface.
5. Security:- Using data hiding and abstraction we are providing necessary data only it
mean we are maintaining security.

Disadvantage of the Object Oriented Programming

  The message based communication between many objects in a complex system is


difficult to implement.
  Large program size : Object Oriented program typically involve more lines of code
than procedural program It require more memory to process at a great speed. So it
runs slower than the traditional programming language.
  It works on object and everything of the real world is not possible to divide into new
neat classes and sub-classes.
  There are problems that lend themselves well to functional programming style, logic
programming style, or procedure based programming style and applying object
oriented programming in those situation will not result in efficient programs.

Procedure oriented programming Object oriented programming

In procedural programming, program is divided In object oriented programming, program is


into small parts called functions. divided into small parts called objects.

Procedural programming follows top down Object oriented programming follows bottom


approach. up approach.

There is no access specifier in procedural Object oriented programming have access


programming. specifiers like private, public, protected etc.
3

Adding new data and function is not easy. Adding new data and function is easy.

Procedural programming does not have any Object oriented programming provides data
proper way for hiding data so it is less secure. hiding so it is more secure.

In procedural programming, overloading is not Overloading is possible in object oriented


possible. programming.

In procedural programming, function is more In object oriented programming, data is more


important than data. important than function.

Procedural programming is based on unreal Object oriented programming is based on real


world. world.

Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.

Their is no provision of inheritance. Inheritance achieved in three modes public

private and protected.

Global data is shared among the functions in the Data is shared among the objects through the

program. member functions.

1.3 Features of Object Oriented Programming:

Various features of object oriented programming are follows:

1. Object

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation

1.OBJECT:

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.

What is an object in Java


4

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.

o Behavior: represents the behavior (functionality) of an object such as deposit,

withdraw, etc.

o Identity: An object identity is typically implemented via a unique ID. The value of

the ID is not visible to the external user. However, it is used internally by the JVM to

identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state.
It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects


are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.

o An object is a runtime entity.

o The object is an entity which has state and behavior.

o The object is an instance of a class.

2. CLASS

A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields

o Methods

o Constructors

o Blocks
5

o Nested class and interface

Syntax to declare a class:

1. class <class_name>

2. {  

3.     field;  

4.     method;  

5. }  

3. inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template

or blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also

called a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass inherits

the features. It is also called a base class or a parent class.


6

o Reusability: As the name specifies, reusability is a mechanism which facilitates you

to reuse the fields and methods of the existing class when you create a new class.

You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name  

2. {  

3.    //methods and fields  

4. }  

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

4.POLYMORPHISM

If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc…

We can achieve polymorphism in Java using the following ways:


1. Method Overriding
2. Method Overloading

5 ABSTRACTION

Abstraction is the concept of object-oriented programming that "shows" only essential


attributes and "hides" unnecessary information. The main purpose of abstraction is hiding
the unnecessary details from the users.

Abstraction is selecting data from a larger pool to show only relevant details of the object to
the user. It helps in reducing programming complexity and efforts. It is one of the most
important concepts of OOPs.

Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
7

In Java, we use abstract class and interface to achieve abstraction.

6.Encapsulation

Encapsulation in Java is a process of wrapping code and data together into a single unit,
for example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

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.

Encapsulation is defined as the wrapping up of data under a single unit. It is the


mechanism that binds together code and the data it manipulates Technically in
encapsulation, the variables or data of a class is hidden from any other class and can be
accessed only through any member function of its own class in which it is declared.

 As in encapsulation, the data in a class is hidden from other classes using the data
hiding concept which is achieved by making the members or methods of a class
private, and the class is exposed to the end-user or the world without providing any
details behind implementation using the abstraction concept, so it is also known as
a combination of data-hiding and abstraction.
 Encapsulation can be achieved by Declaring all the variables in the class as private
and writing public methods in the class to set and get the values of variables

1.4 HISTORY OF JAVA


8

1.5 Features of JAVA or java buzzwords:

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 most important features of Java language is given below.

1. Simple

2. Object-Oriented

3. Portable

4. Platform independent

5. Secured

6. Robust

7. Architecture neutral

8. Interpreted

9. High Performance

10.Multithreaded

11.Distributed

12.Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun, 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.


9

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation

Platform Independen

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 the top of other hardware-based platforms. It has two components:

1. Runtime Environment

2. API(Application Programming Interface)

Java code can be run 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).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
10

o No explicit pointer

o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader 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 right 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.

Robust

Robust simply means strong. Java is robust because:

o It uses strong memory management.

o There is a lack of pointers that avoids security problems.

o There is automatic garbage collection in java which runs on the Java Virtual Machine

to get rid of objects which are not being used by a Java application anymore.

o There are exception handling and the type checking mechanism in Java. All these

points make Java robust.


11

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

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.

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.

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.

Dynamic

Java is a dynamic language. It supports 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).

1.6 java program structure

In this section, we have discussed the basic structure of a Java program. At the end of
this section, you will able to develop the Hello world Java program, easily.
12

1.7 simple java program

.
Hello.java

public class Hello


{
public static void main(String[] args)
{
System.out.println("Hello Java");
}
}

1.8 Data types in java

Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short,

int, long, float and double.

2. Non-primitive data types: The non-primitive data types

include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These
are the most basic data types available in Java language.
13

Java is a statically-typed programming language. It means, all variables must be declared before its use.
That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

1. boolean data type

2. byte data type

3. char data type

4. short data type

5. int data type

6. long data type

7. float data type

8. double data type

Data Type Default Default size


Value

boolean false 1 bit

char '\u0000' 2 byte


14

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is
most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value
is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.

Example: short s = 10000, short r = -5000


15

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between
- 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there
is no problem about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. The float data type should never be used for
precise values, such as currency. Its default value is 0.0F.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\
u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'

1.8 types of variables in java


 There are three kinds of variables in Java −
16

 Local variables
 Instance variables
 Class/Static variables

Local Variables
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the variable will
be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables, so local variables should be declared and an initial
value should be assigned before the first use.

Example

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this
method.

public class Test


{
public void pupAge()
{
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[])


{
Test test = new Test();
test.pupAge();
}
}

This will produce the following result −

Output

Puppy age is: 7

Example

Following example uses age without initializing it, so it would give an error at the time of compilation.

public class Test {

public void pupAge()


{
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
17

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}

This will produce the following error while compiling it −

Output

Test.java:4:variable number might not have been initialized


age = age + 7;
^
1 error

Instance Variables
 Instance variables are declared in a class, but outside a method, constructor or any block.
 When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
 Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object's state that must be present throughout the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class. Normally,
it is recommended to make these variables private (access level). However, visibility for
subclasses can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers, the default value is 0, for Booleans it is
false, and for object references it is null. Values can be assigned during the declaration or within
the constructor.
 Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they should be
called using the fully qualified name. ObjectReference.VariableName.

Example

import java.io.*;
public class Employee
{

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName)
{
name = empName;
}
18

// The salary variable is assigned a value.


public void setSalary(double empSal)
{
salary = empSal;
}

// This method prints the employee details.


public void printEmp()
{
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[])


{
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This will produce the following result −

Output

name : Ransika
salary :1000.0

Class/Static Variables
 Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many objects
are created from it.
 Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final, and static. Constant variables never change from their
initial value.
 Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program stops.
 Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for Booleans,
it is false; and for object references, it is null. Values can be assigned during the declaration or
within the constructor. Additionally, values can be assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class name ClassName.VariableName.
 When declaring class variables as public static final, then variable names (constants) are all in
upper case. If the static variables are not public and final, the naming syntax is the same as
instance and local variables.

Example

import java.io.*;
19

public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}

This will produce the following result −

Output

Development average salary:1000

1.9 constants in java


As the name suggests, a constant is an entity in programming that is immutable. In other
words, the value that cannot be changed. In this section, we will learn about Java
constant and how to declare a constant in Java.

What is constant?

Constant is a value that cannot be changed after assigning it. Java does not directly
support the constants. There is an alternative way to define the constants in Java by using
the non-access modifiers static and final.

How to declare constant in Java?

In Java, to declare any variable as constant, we use static and final modifiers. It is also


known as non-access modifiers. According to the Java naming convention the identifier
name must be in capital letters.
20

Static Modifier
The static modifier allows a class variable to be used without creating an instance of that
class. A static class members are associated with the class itself, rather than an individual
object. All of the instances of a class share the same copy of a static variable.

here, class classOne contains a static variable days_in_week, thus we are allowed to use it in classTwo
without explicitly creating a classOne object.

Final Modifier
The final modifier makes a variable’s value immutable. Once the value is assigned, it cannot
be changed later in program. The final modifier is used in conjunction with Primitive data
types (i.e., int, short, long, byte, char, float, double, boolean) to make a variable
immutable.

1.10 keywords in java

Java has a set of keywords that are reserved words that cannot be used as variables,
methods, classes, or any other identifiers:

Java Keywords List


21

abstract assert boolean break byte

case catch char class const

continue default do double else

enum extends final finally float

implement impor
for goto if
s t

instanceo interfac
int long native
f e

new package private protected public

return short static strictfp super

synchronize throw
switch this throw
d s

transient try void volatile while

Note: true, false, and null are not keywords, but they are literals and reserved words that
cannot be used as identifiers.

1.11 operators in java


Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are- 
 
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
22

8. Shift Operators

 Arithmetic Operators:
 They are used to perform simple arithmetic operations on primitive data types. 
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction

 Unary Operators: 
Unary operators need only one operand. They are used to increment, decrement or
negate a value. 
 – :Unary minus, used for negating the values.
 + :Unary plus, indicates positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is byte, char, or short. This is called unary numeric promotion.
 ++ :Increment operator, used for incrementing the value by 1. There are
two varieties of increment operator. 
 Post-Increment : Value is first used for computing the result
and then incremented.
 Pre-Increment : Value is incremented first and then result is
computed.
 — : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operator. 
 Post-decrement : Value is first used for computing the result
and then decremented.
 Pre-Decrement : Value is decremented first and then result is
computed.
 ! : Logical not operator, used for inverting a boolean value.

 Assignment Operator :
‘=’ Assignment operator is used to assign a value to any variable. It has a right to left
associativity, i.e value given on right hand side of operator is assigned to the variable
on the left and therefore right hand side value must be declared before using it or
should be a constant. 
General format of assignment operator is, 
 
variable = value;
 In many cases assignment operator can be combined with other operators to build a
shorter version of statement called Compound Statement. For example, instead of
a = a+5, we can write a += 5. 
 +=, for adding left operand with right operand and then assigning it to
variable on the left.
 -=, for subtracting left operand with right operand and then assigning it to
variable on the left.
 *=, for multiplying left operand with right operand and then assigning it to
variable on the left.
 /=, for dividing left operand with right operand and then assigning it to
variable on the left.
 %=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
23


 Relational Operators :
 These operators are used to check for relations like equality, greater than, less than.
They return boolean result after the comparison and are extensively used in looping
statements as well as conditional if else statements. General format is, 
 
variable relation_operator value
 Some of the relational operators are- 
 ==, Equal to : returns true if left hand side is equal to right hand side.
 !=, Not Equal to : returns true if left hand side is not equal to right hand
side.
 <, less than : returns true if left hand side is less than right hand side.
 <=, less than or equal to : returns true if left hand side is less than or
equal to right hand side.
 >, Greater than : returns true if left hand side is greater than right hand
side.
 >=, Greater than or equal to: returns true if left hand side is greater than
or equal to right hand side.

 Logical Operators : 
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the
function similar to AND gate and OR gate in digital electronics.

One thing to keep in mind is the second condition is not evaluated if the first one is
false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions
for making a decision. 
Conditional operators are-
 &&, Logical AND : returns true when both conditions are true.
 ||, Logical OR : returns true if at least one condition is true.

 Ternary operator :
  Ternary operator is a shorthand version of if-else statement. It has three operands
and hence the name ternary. General format is- 
 
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’. 

 Bitwise Operators : 
These operators are used to perform manipulation of individual bits of a number. They
can be used with any of the integer types. They are used when performing update and
query operations of Binary indexed tree. 
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit by bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns
the one’s compliment representation of the input value, i.e. with all bits
inversed.

 Shift Operators : 
24

These operators are used to shift the bits of a number left or right thereby multiplying
or dividing the number by two respectively. They can be used when we have to
multiply or divide a number by two. General format- 
 
number shift_op number_of_places_to_shift;

 <<, Left shift operator: shifts the bits of the number to the left and fills 0
on voids left as a result. Similar effect as of multiplying the number with
some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of
initial number. Similar effect as of dividing the number with some power of
two.
 >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.

1.11 operator hierarchy


Java Operator Precedence

Operator Category Precedence


Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise ^
exclusive OR

bitwise |
25

inclusive OR

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

1.12 scope and lifetime of variable


The scope of a variable refers to the areas or the sections of the program in which the
variable can be accessed, and the lifetime of a variable indicates how long the variable stays
alive in the memory.

A joint statement defining the scope and lifetime of a variable is “how and where the
variable is defined.”

There are three types of variables.

1. Instance Variables
2. Class Variables
3. Local Variables

Now, let us dig into the scope and lifetime of each of the above mentioned type.

Instance Variables

A variable which is declared inside a class, but is declared outside any methods and blocks
is known as instance variable.

Scope: Throughout the class except in the static methods.


Lifetime: Until the object of the class stays in the memory.

Class Variables

A variable which is declared inside a class, outside all the blocks and is declared as static is
known as class variable.
Scope: Throughout the class.
Lifetime: Until the end of the program.

Local Variables
26

All variables which are not instance or class variables are known as local variables.

Scope: Within the block it is declared.


Lifetime: Until control leaves the block in which it is declared.
Now, let us look at an example code to paint a clear picture and understand the concept of
scope and lifetime of variables better.

Example

public class scope_and_lifetime {

int num1, num2; //Instance Variables

static int result; //Class Variable

int add(int a, int b){ //Local Variables

num1 = a;

num2 = b;

return a+b;

public static void main(String args[]){

scope_and_lifetime ob = new scope_and_lifetime();

result = ob.add(10, 20);

System.out.println("Sum = " + result);

Expressions in java

A Java expression consists of variables, operators, literals, and method calls. To know more

about method calls, visit Java methods. For example,

int score;
score = 90;

Here, score = 90 is an expression that returns an int. Consider another example,


27

Double a = 2.2, b = 3.4, result;


result = a + b - 3.4;

Here, a + b - 3.4 is an expression.

if (number1 == number2)
System.out.println("Number 1 is larger than number 2");

Here, number1 == number2 is an expression that returns a boolean value.

Similarly, "Number 1 is larger than number 2" is a string expression.

1.13 Type Casting or type conversion in Java


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. In this section, we will
discuss type casting and its types with proper examples.

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:

o Widening Type Casting

o Narrowing 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:

o Both data types must be compatible with each other.

o The target type must be larger than the source type.


28

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

WideningTypeCastingExample.java

1. public class WideningTypeCastingExample  

2. {  

3. public static void main(String[] args)  

4. {  

5. int x = 7;  

6. //automatically converts the integer type into long type  

7. long y = x;  

8. //automatically converts the long type into float type  

9. float z = y;  

10. System.out.println("Before conversion, int value "+x);  

11. System.out.println("After conversion, long value "+y);  

12. System.out.println("After conversion, float value "+z);  

13. }  

14. }  

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.

Narrowing Type Casting

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.

1. double -> float -> long -> int -> char -> short -> byte  
29

Let's see an example of narrowing type casting.

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

1. public class NarrowingTypeCastingExample  

2. {  

3. public static void main(String args[])  

4. {  

5. double d = 166.66;  

6. //converting double data type into long data type  

7. long l = (long)d;  

8. //converting long data type into int data type  

9. int i = (int)l;  

10. System.out.println("Before conversion: "+d);  

11. //fractional part lost  

12. System.out.println("After conversion into long type: "+l);  

13. //fractional part lost  

14. System.out.println("After conversion into int type: "+i);  

15. }  

16. }  

Output

Before conversion: 166.66


After conversion into long type: 166
After conversion into int type: 166
30

1.14 enumerated type (ENUM):

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

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) ,

directions (NORTH, SOUTH, EAST, and WEST),

season (SPRING, SUMMER, WINTER, and AUTUMN or FALL),

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

According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.

Java Enums can be thought of as classes which have a fixed set of constants (a variable
that does not change).

The Java enum constants are static and final implicitly. It is available since JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also known
as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java
is more powerful. Here, we can define an enum either inside the class or outside the class.

Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods
in Java enum.

Points to remember for Java Enum

o Enum improves type safety

o Enum can be easily used in switch

o Enum can be traversed


31

o Enum can have fields, constructors and methods

o Enum may implement many interfaces but cannot extend any class because it

internally extends Enum class

o enum is created inside clas or outside class.

Defining Java Enum


The enum can be defined within or outside the class because it is similar to a class. The
semicolon (;) at the end of the enum constants are optional. For example:

1. enum Season { WINTER, SPRING, SUMMER, FALL }  

Or,

1. enum Season { WINTER, SPRING, SUMMER, FALL; }  

Both the definitions of Java enum are the same.

Enum declaration inside a class .

example—1 :

public class Test


{
enum Color
{
RED, GREEN, BLUE;
}

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output :

RED
32

Important points of enum :

Every enum internally implemented by using Class.

internally above enum Color is converted to

class Color extends Enum


{
public static final Color RED = new Color();
public static final Color BLUE = new Color();
public static final Color GREEN = new Color();
}

Every enum constant represents an object of type enum.

Java Enum Example—2 : Defined inside class

1. class EnumExample3

2. {  

3. enum Season 

4. {

5.  WINTER, SPRING, SUMMER, FALL; 

6. }//semicolon(;) is optional here  

7. public static void main(String[] args) {  

8. Season s=Season.WINTER;//enum type is required to access WINTER  

9. System.out.println(s);  

10. }}  
Test it Now

Output:

WINTER

Java Enum Example: Defined outside class

1. enum Season { WINTER, SPRING, SUMMER, FALL }  

2. class EnumExample2

3. {  
33

4. public static void main(String[] args) 

5. {  

6. Season s=Season.WINTER;  

7. System.out.println(s);  

8. }}   
Test it Now

Output:

WINTER

Simple Example of Java Enum

1. class EnumExample1

2. {  

3. //defining the enum inside the class  

4. public enum Season { WINTER, SPRING, SUMMER, FALL }  

5. //main method  

6. public static void main(String[] args) 

7. {  

8. //traversing the enum  

9. for (Season s : Season.values())  

10. System.out.println(s);  

11. }}  
Test it Now

Output:

WINTER
SPRING
SUMMER
FALL

Let us see another example of Java enum where we are using value(), valueOf(), and
ordinal() methods of Java enum.

1. class EnumExample1

2. {  
34

3. //defining enum within class  

4. public enum Season { WINTER, SPRING, SUMMER }  

5. //creating the main method  

6. public static void main(String[] args) {  

7. //printing all enum  

8. for (Season s : Season.values())

9. {  

10. System.out.println(s);  

11. }  

12. System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));  

13. System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());  

14. System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());  

15.   

16. }}  

Output:

WINTER
SPRING
SUMMER
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2

Note: Java compiler internally adds values(), valueOf() and ordinal() methods within the enum at compile
time. It internally creates a static and final class for the enum.

What is the purpose of the values() method in the enum?

The Java compiler internally adds the values() method when it creates an enum. The
values() method returns an array containing all the values of the enum.

What is the purpose of the valueOf() method in the enum?

The Java compiler internally adds the valueOf() method when it creates an enum. The
valueOf() method returns the value of given constant enum.

What is the purpose of the ordinal() method in the enum?

The Java compiler internally adds the ordinal() method when it creates an enum. The
ordinal() method returns the index of the enum value.
35

Java Enum Example: main method inside Enum

If you put main() method inside the enum, you can run the enum directly.

1. enum Season {   

2. WINTER, SPRING, SUMMER, FALL;  

3. public static void main(String[] args) 

4. {  

5. Season s=Season.WINTER;  

6. System.out.println(s);  

7. }  

8. }  

Output:

WINTER

Initializing specific values to the enum constants

The enum constants have an initial value which starts from 0, 1, 2, 3, and so on. But, we
can initialize the specific value to the enum constants by defining fields and constructors. As
specified earlier, Enum can have fields, constructors, and methods.

Example of specifying initial value to the enum constants

1. class EnumExample4

2. {  

3. enum Season

4. {   

5. WINTER(5), SPRING(10), SUMMER(15), FALL(20);   

6.   

7. private int value;  

8. private Season(int value)
36

9. {  

10. this.value=value;  

11. }  

12. } //ENUM 

13.

14. public static void main(String args[])

15. {  

16. for (Season s : Season.values())  

17. System.out.println(s+" "+s.value);  

18.   

19. }

20. }  

21.       
Test it Now

Output:

WINTER 5
SPRING 10
SUMMER 15
FALL 20

Constructor of enum type is private. If you don't declare private compiler internally creates private
constructor.

1. enum Season

2. {  

3. WINTER(10),SUMMER(20);  

4. private int value;  

5. Season(int value)

6. {  

7. this.value=value;  

8. }  

9. }      
37

Can we create the instance of Enum by new keyword?

No, because it contains private constructors only.

Can we have an abstract method in the Enum?

Yes, Of course! we can have abstract methods and can provide the implementation of these
methods.

Java Enum in a switch statement

We can apply enum on switch statement as in the given example:

Example of applying Enum on a switch statement

1. class EnumExample5

2. {  

3. enum Day{ 

4. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

5. }  

6. public static void main(String args[])

7. {  

8. Day day=Day.MONDAY;  

9.   

10. switch(day)

11. {  

12. case SUNDAY:  System.out.println("sunday");  

13.   break;  

14. case MONDAY:  System.out.println("monday");  

15.   break;  

16. default: System.out.println("other day");  

17. }  

18. }
38

19. }  
Test it Now

Output:

monday
2.0 Arrays in java

Normally, an array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we
need to use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data

efficiently.

o Random access: We can get any data located at an index position.


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

Types of Array in java

There are two types of array.

o Single Dimensional Array

o Multidimensional Array
39

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)  

2. dataType []arr; (or)  

3. dataType arr[];  

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];  

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize  

2. //and traverse the Java array.  

3. class Testarray

4. {  

5. public static void main(String args[])

6. {  

7. int a[]=new int[5];//declaration and instantiation  

8. a[0]=10;//initialization  

9. a[1]=20;  

10. a[2]=70;  

11. a[3]=40;  

12. a[4]=50;  

13. //traversing array  

14. for(int i=0;i<a.length;i++)//length is the property of array  

15. System.out.println(a[i]);  

16. }

17. }  

Output:
40

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation   

2. //and initialization of Java array in a single line  

3. class Testarray1

4. {  

5. public static void main(String args[])

6. {  

7. int a[]={33,3,4,5};//declaration, instantiation and initialization  

8. //printing array  

9. for(int i=0;i<a.length;i++)//length is the property of array  

10. System.out.println(a[i]);  

11. }}  

Output:

33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the
array elements one by one. It holds an array element in a variable, then executes the body
of the loop.

The syntax of the for-each loop is given below:


41

1. for(data_type variable:array)

2. {  

3. //body of the loop  

4. }  

Let us see the example of print the elements of Java array using the for-each loop.

1. //Java Program to print the array elements using for-each loop  

2. class Testarray1

3. {  

4. public static void main(String args[])

5. {  

6. int arr[]={33,3,4,5};  

7. //printing array using for-each loop  

8. for(int i:arr)  

9. System.out.println(i);  

10. }}  

Output:

33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

1. //Java Program to demonstrate the way of passing an array  

2. //to method.  

3. class Testarray2

4. {  

5. //creating a method which receives an array as a parameter  
42

6. static void min(int arr[])

7. {  

8. int min=arr[0];  

9. for(int i=1;i<arr.length;i++) 

10. { 

11.  if(min>arr[i])  

12.   min=arr[i];  

13.   }

14. System.out.println(min);  

15. }  

16.   

17. public static void main(String args[]){  

18. int a[]={33,3,4,5};//declaring and initializing an array  

19. min(a);//passing array to method  

20. }}  

Output:

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)  

2. dataType [][]arrayRefVar; (or)  

3. dataType arrayRefVar[][]; (or)  

4. dataType []arrayRefVar[];   

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in Java


43

1. arr[0][0]=1;  

2. arr[0][1]=2;  

3. arr[0][2]=3;  

4. arr[1][0]=4;  

5. arr[1][1]=5;  

6. arr[1][2]=6;  

7. arr[2][0]=7;  

8. arr[2][1]=8;  

9. arr[2][2]=9;  

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

1. //Java Program to illustrate the use of multidimensional array  

2. class Testarray3

3. {  

4. public static void main(String args[])

5. {  

6. //declaring and initializing 2D array  

7. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  

8. //printing 2D array  

9. for(int i=0;i<3;i++)

10. {  

11.  for(int j=0;j<3;j++)

12. {  

13.    System.out.print(arr[i][j]+" ");  

14.  }  

15.  System.out.println();  

16. }  

17. }}  
44

Output:

1 2 3
2 4 5
4 4 5

2.1 console input and output


The Scanner class of the java.util package is used to read input data from different sources
like input streams, users, files, etc.

we need to import the java.util.Scanner package before we can use the Scanner class.

import java.util.Scanner;

 To read strings, we use nextLine().


 To read a single character, we use next().charAt(0). next() function returns the next token/word in
the input as a string and charAt(0) function returns the first character in that string.

Create a Scanner Object in Java

Once we import the package, here is how we can create Scanner objects.

// read input from the input stream


Scanner sc1 = new Scanner(InputStream input);

// read input from files


Scanner sc2 = new Scanner(File file);

// read input from a string


Scanner sc3 = new Scanner(String str);

Here, we have created objects of the Scanner class that will read input

from InputStream, File, and String respectively.
45

Java Scanner Methods to Take Input

The Scanner class provides various methods that allow us to read inputs of different types.

Method Description
nextInt() reads an int value from the user
nextFloat() reads a float value form the user
nextBoolean() reads a boolean value from the user
nextLine() reads a line of text from the user
next() reads a word from the user
nextByte() reads a byte value from the user
nextDouble() reads a double value from the user
nextShort() reads a short value from the user
nextLong() reads a long value from the user

Example:

import java.util.Scanner;

public class ScannerDemo


{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);

System.out.println("Enter name, age and salary");

// String input
String name = s.nextLine();

// Numerical input
int age = s.nextInt();
double salary = s.nextDouble();

// Output input by user


System.out.println("Name: "+ name);
System.out.println("Age: "+ age);
System.out.println("Salary: "+ salary);
}
}
46

output :
Enter name, age and salary
raju
24
5000
Name: raju
Age: 24
Salary: 5000.0

2.1.1 formatting output:


 print and println format individual values in a standard way.
 format formats almost any number of values based on a format string, with many
options for precise formatting.

The print and println Methods

Invoking print or println outputs a single value after converting the value using the


appropriate toString method. We can see this in the Root example:

public class Root


{
public static void main(String[] args)
{
int i = 2;
double r = Math.sqrt(i);

System.out.print("The square root of ");


System.out.print(i);
System.out.print(" is ");
System.out.print(r);
System.out.println(".");

i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");
}
}

Here is the output of Root:

The square root of 2 is 1.4142135623730951.


The square root of 5 is 2.23606797749979.

The i and r variables are formatted twice: the first time using code in an overload of print,
the second time by conversion code automatically generated by the Java compiler, which
also utilizes toString. You can format any value this way, but you don't have much control
over the results.
47

The format Method

The format method formats multiple arguments based on a format string. The format string
consists of static text embedded with format specifiers; except for the format specifiers, the
format string is output unchanged.

Format strings support many features. In this tutorial, we'll just cover some basics. For a
complete description, see format string syntax in the API specification.

The Root2 example formats two values with a single format invocation:

public class Root2


{
public static void main(String[] args)
{
int i = 2;
double r = Math.sqrt(i);

System.out.format("The square root of %d is %f.%n", i, r);


}
}

Here is the output:

The square root of 2 is 1.414214.

Like the three used in this example, all format specifiers begin with a % and end with a 1-
or 2-character conversion that specifies the kind of formatted output being generated. The
three conversions used here are:

 d formats an integer value as a decimal value.


 f formats a floating point value as a decimal value.
 n outputs a platform-specific line terminator.

2.2 constructors in Java


In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
48

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

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name

2. A Constructor must have no explicit return type

3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other
words, we can have private, protected, public or default constructor in Java.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

ava Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked

at the time of object creation.

1. //Java Program to create and call a default constructor  

2. class Bike1{  

3. //creating a default constructor  

4. Bike1(){System.out.println("Bike is created");}  

5. //main method  
49

6. public static void main(String args[]){  

7. //calling a default constructor  

8. Bike1 b=new Bike1();  

9. }  

10. }  

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

Example of default constructor that displays the default values

1. //Let us see another example of default constructor  

2. //which displays the default values  

3. class Student3{  

4. int id;  

5. String name;  

6. //method to display the value of id and name  

7. void display(){System.out.println(id+" "+name);}  

8.   

9. public static void main(String args[]){  

10. //creating objects  

11. Student3 s1=new Student3();  

12. Student3 s2=new Student3();  
50

13. //displaying values of the object  

14. s1.display();  

15. s2.display();  

16. }  

17. }  

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides
you a default constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.  

2. class Student4{  

3.     int id;  

4.     String name;  

5.     //creating a parameterized constructor  

6.     Student4(int i,String n){  

7.     id = i;  

8.     name = n;  

9.     }  

10.     //method to display the values  
51

11.     void display(){System.out.println(id+" "+name);}  

12.    

13.     public static void main(String args[]){  

14.     //creating objects and passing values  

15.     Student4 s1 = new Student4(111,"Karan");  

16.     Student4 s2 = new Student4(222,"Aryan");  

17.     //calling method to display the values of object  

18.     s1.display();  

19.     s2.display();  

20.    }  

21. }  

Output:

111 Karan
222 Aryan

Constructor Overloading in Java

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.

Example of Constructor Overloading

1. //Java program to overload constructors  

2. class Student5{  

3.     int id;  

4.     String name;  

5.     int age;  

6.     //creating two arg constructor  

7.     Student5(int i,String n){  

8.     id = i;  
52

9.     name = n;  

10.     }  

11.     //creating three arg constructor  

12.     Student5(int i,String n,int a){  

13.     id = i;  

14.     name = n;  

15.     age=a;  

16.     }  

17.     void display(){System.out.println(id+" "+name+" "+age);}  

18.    

19.     public static void main(String args[]){  

20.     Student5 s1 = new Student5(111,"Karan");  

21.     Student5 s2 = new Student5(222,"Aryan",25);  

22.     s1.display();  

23.     s2.display();  

24.    }  

25. }  

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the A method is used to expose the behavior

state of an object. of an object.

A constructor must not have a return A method must have a return type.
53

type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the

constructor if you don't have any compiler in any case.

constructor in a class.

The constructor name must be same as The method name may or may not be

the class name. same as the class name.

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

o By constructor

o By assigning the values of one object into another

o By clone() method of Object class

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;  
54

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

Copying values without constructor

We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.

1. class Student7{  

2.     int id;  

3.     String name;  

4.     Student7(int i,String n){  

5.     id = i;  

6.     name = n;  

7.     }  

8.     Student7(){}  
55

9.     void display(){System.out.println(id+" "+name);}  

10.    

11.     public static void main(String args[]){  

12.     Student7 s1 = new Student7(111,"Karan");  

13.     Student7 s2 = new Student7();  

14.     s2.id=s1.id;  

15.     s2.name=s1.name;  

16.     s1.display();  

17.     s2.display();  

18.    }  

19. }  

Output:

111 Karan
111 Karan

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform any
operation in the constructor as you perform in the method.

Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information of a
constructor in the class. It is found in the java.lang.reflect package.

2.3 Methods in java:


A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code
again and again.
56

It also provides the easy modification and readability of code, just by adding or


removing a chunk of code. The method is executed only when we call or invoke it.

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

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 brace

2.4 parameter passing methods in java


There are two ways parameters are passing in java

1) Call by value or pass by value


2) Call by reference or pass by reference

What is Call by Value method?

Call by value method copies the value of an argument into the formal parameter of that
function. Therefore, changes made to the parameter of the main function do not affect the
argument.

In this parameter passing method, values of actual parameters are copied to function's
formal parameters, and the parameters are stored in different memory locations. So any
changes made inside functions are not reflected in actual parameters of the caller.

In Call by value method original value is not modified whereas,

in Call by reference method, the original value is modified.

In Call by value, a copy of the variable is passed whereas

in Call by reference, a variable itself is passed.

In Call by value, actual and formal arguments will be created in different memory locations
whereas

in Call by reference, actual and formal arguments will be created in the same memory
location.

Call by value is the default method in programming languages like C++, PHP, Visual Basic
NET, and C# whereas Call by reference is supported only Java language.

Call by Value, variables are passed using a straightforward method whereas Call by
Reference, pointers are required to store the address of variables.
58

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.      
8.  public static void main(String args[]){  
9.    Operation op=new Operation();  
10.  
11.   System.out.println("before change "+op.data);  
12.   op.change(500);  
13.   System.out.println("after change "+op.data);  
14.  
15. }  
16.}  
Output:before change 50
after change 50

What is Call by Reference method?

Call by reference method copies the address of an argument into the formal parameter. In
this method, the address is used to access the actual argument used in the function call. It
means that changes made in the parameter alter the passing argument.

In this method, the memory allocation is the same as the actual parameters. All the
operation in the function are performed on the value stored at the address of the actual
parameter, and the modified value will be stored at the same address.

In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be
changed. In this example we are passing object as a value. Let's take a simple
example:

1. class Operation2{  
2.  int data=50;  
3.   
4.  void change(Operation2 op){  
59

5.  op.data=op.data+100;//changes will be in the instance variable  
6.  }  
7.      
8.     
9.  public static void main(String args[]){  
10.   Operation2 op=new Operation2();  
11.  
12.   System.out.println("before change "+op.data);  
13.   op.change(op);//passing object  
14.   System.out.println("after change "+op.data);  
15.  
16. }  
17.}  

Output:before change 50
after change 150

2.5 static fields or variables and static methods

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 but not to instance of the class.

The static can be:

1. Variable (also known as a class variable)

2. Method (also known as a class method)

3. Block

4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.


60

Static variable in Java is variable which belongs to the class and initialized only once at
the start of the execution. It is a variable which belongs to the class and not to
object(instance ).

Static variables are initialized only once, at the start of the execution. These variables will
be initialized first, before the initialization of any instance variables.

 A single copy to be shared by all instances of the class


 A static variable can be accessed directly by the class name and doesn’t need any
object

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.

Static variable initialization

1. Static variables are initialized when class is loaded.


2. Static variables are initialized before any object of that class is created.
3. Static variables are initialized before any static method of the class executes.

Default values for static and non-static variables are same

primitive integers(long, short etc): 0
primitive floating points(float, double): 0.0
boolean: false
object references: null

Static final variables

The static final variables are constants. Lets have a look at the code below:

public class MyClass


{
public static final int MY_VAR=27;
}
61

Note: Constant variable name should be in Caps! you can use underscore(_)
between.

1) The above code will execute as soon as the class MyClass is loaded, before static method
is called and even before any static variable can be accessed.

2) The variable MY_VAR is public which means any class can use it. It is a static variable


so you won’t need any object of class in order to access it. It’s final so the value of this
variable can never be changed in the current or in any class.

Key points:
final variable always needs initialization, if you don’t initialize it would throw a compilation
error. have a look at below example-

public class MyClass


{
public static final int MY_VAR;//compile time error
}

Error: variable MY_VAR might not have been initialize

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

1. class Student

2. {  

3.      int rollno;  

4.      String name;  

5.      String college="ITS";  

6. }  

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.

note : Java static property is shared to all objects.


62

Example of static variable

1. //Java Program to demonstrate the use of static variable  

2. class Student

3. {  

4.    int rollno;//instance variable  

5.    String name;  

6.    static String college ="ITS";//static variable  

7.    //constructor  

8.    Student(int r, String n)

9. {  

10.    rollno = r;  

11.    name = n;  

12.    }  

13.    //method to display the values  

14.    void display ()

15. {

16. System.out.println(rollno+" "+name+" "+college);}  

17. }  

18. //Test class to show the values of objects  

19. public class TestStaticVariable1{  

20.  public static void main(String args[])

21. {  

22.  Student s1 = new Student(111,"Karan");  

23.  Student s2 = new Student(222,"Aryan");  

24.  //we can change the college of all objects by the single line of code  

25.  //Student.college="BBDIT";  

26.  s1.display();  

27.  s2.display();  
63

28.  }  

29. }  

Output:

111 Karan ITS


222 Aryan ITS

Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.

o A static method can be invoked without the need for creating an instance of a class.

o A static method can access static data member and can change the value of it.

o Static Methods can access class variables(static variables) without using

object(instance) of the class, however non-static methods and non-static variables

can only be accessed using objects.

Static methods can be accessed directly in static and non-static methods.

 A static method cannot refer to "this" or "super" keywords in anyway

Syntax:
Static keyword followed by return type, followed by method name.

 static return_type method_name();


64

Example of static method

1. //Java Program to demonstrate the use of a static method.  

2. class Student

3. {  

4.      int rollno;  

5.      String name;  

6.      static String college = "ITS";  

7.      //static method to change the value of static variable  

8.      static void change()

9. {  

10.      college = "BBDIT";  

11.      }  

12.      //constructor to initialize the variable  

13.      Student(int r, String n)

14. {  

15.      rollno = r;  

16.      name = n;  

17.      }  

18.      //method to display values  

19.      void display()

20. {

21. System.out.println(rollno+" "+name+" "+college);

22. }  

23. }  

24. //Test class to create and display the values of object  

25. public class TestStaticMethod

26. {  
65

27.     public static void main(String args[])

28. {  

29.     Student.change();//calling change method  

30.     //creating objects  

31.     Student s1 = new Student(111,"Karan");  

32.     Student s2 = new Student(222,"Aryan");  

33.     Student s3 = new Student(333,"Sonoo");  

34.     //calling display method  

35.     s1.display();  

36.     s2.display();  

37.     s3.display();  

38.     }  

39. }  
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Restrictions for the static method

following are main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method

directly.

2. this and super cannot be used in static context.


3. They can only directly call other static methods.
4. They can only directly access static data.

1. class A

2. {  

3.  int a=40;//non static  

4.    
66

5.  public static void main(String args[])

6. {  

7.   System.out.println(a);  

8.  }  

9. }        

Java static block


The static block is a block of statement inside a Java class that will be executed when a
class is first loaded into the JVM. A static block helps to initialize the static data
members, just like constructors help to initialize instance members.

class Test{
static {
//Code goes here
}
}

o Is used to initialize the static data member.

o It is executed before the main method at the time of classloading.

Static block is used for initializing the static variables.This block gets executed when the

class is loaded in the memory. A class can have multiple Static blocks, which will execute in

the same sequence in which they have been written into the program.

Example of static block

1. class A2{  

2.   static

3. {

4. System.out.println("static block is invoked");

5. }  

6.   public static void main(String args[])
67

7. {  

8.    System.out.println("Hello main");  

9.   }  

10. }  

Output:static block is invoked


Hello main

2.5 Access control or access modifier or access specifiers in java


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.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be

accessed from outside the class.

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.

 Visible to the package, the default. No modifiers are needed.


 Visible to the class only (private).
68

 Visible to the world (public).


 Visible to the package and all subclasses (protected).

Private

 The private access modifier is accessible only within the class.

The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class from outside of
the class.

private access modifier is specified using the keyword private. 


 The methods or data members declared as private are accessible only within
the class in which they are declared.
 Any other class of the same package will not be able to access these
members.

 Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.
 Private access modifier is the most restrictive access level.
 Using the private modifier is the main way that an object encapsulates itself and
hides data from the outside world.

 class A

 {  

 private int data=40;  

 private void msg()

 {

 System.out.println("Hello java");

 }  

 }  

   

 public class Simple

 {  

  public static void main(String args[])

 {  
69

    A obj=new A();  

    System.out.println(obj.data);//Compile Time Error  

    obj.msg();//Compile Time Error  

    }  

 }  

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

1. class A{  

2. private A()

3. {}//private constructor  

4. void msg()

5. {

6. System.out.println("Hello java");

7. }  

8. }  

9. public class Simple

10. {  

11.  public static void main(String args[])

12. {  

13.    A obj=new A();//Compile Time Error  

14.  }  

15. }  

Note: A class cannot be private or protected except nested class.

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private.

But, it is more restrictive than protected, and public.


70

A variable or method declared without any access control modifier is available to any other
class in the same package.

The fields in an interface are implicitly public static final and the methods in an interface are
by default public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.

1. //save by A.java  

2. package pack;  

3. class A{  

4.   void msg()

5. {

6. System.out.println("Hello");

7. }  

8. }  

1. //save by B.java  

2. package mypack;  

3. import pack.*;  

4. class B{  

5.   public static void main(String args[])

6. {  

7.    A obj = new A();//Compile Time Error  

8.    obj.msg();//Compile Time Error  

9.   }  

10. }  

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) Protected
71

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.

The protected access modifier can be applied on the data member, method and constructor.

It can't be applied on the class.

It provides more accessibility than the default modifer.

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package.

But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.

1. //save by A.java  

2. package pack;  

3. public class A

4. {  

5. protected void msg()

6. {

7. System.out.println("Hello");}  

8. }  

1. //save by B.java  

2. package mypack;  

3. import pack.*;  

4.   

5. class B extends A

6. {  

7.   public static void main(String args[])

8. {  

9.    B obj = new B();  
72

10.    obj.msg();  

11.   }  

12. }  
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

The public access modifier has the widest scope among all other access modifiers.
Classes, methods, or data members that are declared as public are  accessible from
everywhere in the program. There is no restriction on the scope of public data
members.

1. //save by A.java  

2.   

3. package pack;  

4. public class A{  

5. public void msg(){System.out.println("Hello");}  

6. }  

1. //save by B.java  

2.   

3. package mypack;  

4. import pack.*;  

5.   

6. class B{  

7.   public static void main(String args[]){  

8.    A obj = new A();  

9.    obj.msg();  

10.   }  

11. }  
Output:Hello

Access Control and Inheritance


73

The following rules for inherited methods are enforced −


 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in subclasses;
they cannot be private.
 Methods declared private are not inherited at all, so there is no rule for them.

2.6 this keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.


74

1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.

1) this: to refer current class instance variable


The 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. {  
7. rollno=rollno;  
8. name=name;  
9. fee=fee;  
10.}  
11.void display()
12.{
13.System.out.println(rollno+" "+name+" "+fee);}  
14.}  
15.class TestThis1{  
16.public static void main(String args[]){  
17.Student s1=new Student(111,"ankit",5000f);  
75

18.Student s2=new Student(112,"sumit",6000f);  
19.s1.display();  
20.s2.display();  
21.}
22.}  
Test it Now

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.

Solution of the above problem by this keyword

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int rollno,String name,float fee){  
6. this.rollno=rollno;  
7. this.name=name;  
8. this.fee=fee;  
9. }  
10.void display(){System.out.println(rollno+" "+name+" "+fee);}  
11.}  
12.  
13.class TestThis2{  
14.public static void main(String args[]){  
15.Student s1=new Student(111,"ankit",5000f);  
16.Student s2=new Student(112,"sumit",6000f);  
17.s1.display();  
18.s2.display();  
19.}}  
Test it Now
76

Output:

111 ankit 5000


112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no


need to use this keyword like in the following program:

Program where this keyword is not required

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int r,String n,float f){  
6. rollno=r;  
7. name=n;  
8. fee=f;  
9. }  
10.void display(){System.out.println(rollno+" "+name+" "+fee);}  
11.}  
12.  
13.class TestThis3{  
14.public static void main(String args[]){  
15.Student s1=new Student(111,"ankit",5000f);  
16.Student s2=new Student(112,"sumit",6000f);  
17.s1.display();  
18.s2.display();  
19.}}  
Test it Now

Output:

111 ankit 5000


112 sumit 6000

It is better approach to use meaningful names for variables. So we use same name for
instance variables and parameters in real time, and always use this keyword.

2) this: to invoke current class method


77

You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method. Let's see the example

class A{  

1. void m()
2. {
3. System.out.println("hello m");
4. }  
5. void n()
6. {  
7. System.out.println("hello n");  
8. //m();//same as this.m()  
9. this.m();  
10.}  
11.}  
12.class TestThis4{  
13.public static void main(String args[]){  
14.A a=new A();  
15.a.n();  
16.}}  

Output:
78

hello n
hello m

3) this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor. In other words, it is used for constructor chaining.

Rule: Call to this() must be the first statement in constructor.

1. class Student{  

Calling default constructor from parameterized constructor:

1. class A{  
2. A()
3. {
4. System.out.println("hello a");
5. }  
6. A(int x)
7. {  
8. this();  
9. System.out.println(x);  
10.}  
11.}  
12.class TestThis5
13.{  
14.public static void main(String args[])
15.{  
16.A a=new A(10);  
17.}
18.
19.}  

Output:

hello a
79

10

Calling parameterized constructor from default constructor:

1. class A{  
2. A(){  
3. this(5);  
4. System.out.println("hello a");  
5. }  
6. A(int x)
7. {  
8. System.out.println(x);  
9. }  
10.}  
11.class TestThis6{  
12.public static void main(String args[]){  
13.A a=new A();  
14.}}  

Output:

5
hello a

4) this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling. Let's see the example:

1. class S2{  
2.   void m(S2 obj)
3. {  
4.   System.out.println("method is invoked");  
5.   }  
6.   void p()
7. {  
8.   m(this);  
9.   }  
80

10.  public static void main(String args[]){  
11.  S2 s1 = new S2();  
12.  s1.p();  
13.  }  
14.}  

Output:

method is invoked

Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to


another one. It is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:

1. class B{  
2.   A4 obj;  
3.   B(A4 obj){  
4.     this.obj=obj;  
5.   }  
6.   void display(){  
7.     System.out.println(obj.data);//using data member of A4 class  
8.   }  
9. }  
10.  
11.class A4{  
12.  int data=10;  
13.  A4(){  
14.   B b=new B(this);  
15.   b.display();  
16.  }  
81

17.  public static void main(String args[]){  
18.   A4 a=new A4();  
19.  }  
20.}  

Output:10

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

1. return_type method_name()
2. {  
3. return this;  
4. }  

Example of this keyword that you return as a statement from


the method

1. class A
2. {  
3. A getA()
4. {  
5. return this;  
6. }  
7. void msg(){System.out.println("Hello java");}  
8. }  
9. class Test1{  
10.public static void main(String args[]){  
11.new A().getA().msg();  
12.}  
13.}  
Test it Now
82

Output:

Hello java

Proving this keyword

Let's prove that this keyword refers to the current class instance variable. In this program,

we are printing the reference variable and this, output of both variables are same.

1. class A5{  
2. void m()
3. {  
4. System.out.println(this);//prints same reference ID  
5. }  
6. public static void main(String args[])
7. {  
8. A5 obj=new A5();  
9. System.out.println(obj);//prints the reference ID  
10.obj.m();  
11.}  
12.}  

Output:

A5@22b3ea59
A5@22b3ea59

2.7 Overloading Method and overloading constructor

If a class has multiple methods having same name but different in parameters, it is


known as Method Overloading.

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.

So, we perform method overloading to figure out the program quickly.


83

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

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)
3. {
4. return a+b;
5. }  
6. static int add(int a,int b,int c)
7. {
8. return a+b+c;
9. }  
10.}  
11.class TestOverloading1{  
12.public static void main(String[] args)
84

13.{  
14.System.out.println(Adder.add(11,11));  
15.System.out.println(Adder.add(11,11,11));  
16.}
17.}  
Test it Now

Output:

22
33

2) Method Overloading: changing data type of arguments

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. {  
3. static int add(int a, int b)
4. {
5. return a+b;
6. }  
7. static double add(double a, double b)
8. {
9. return a+b;
10.}  
11.}  
12.class TestOverloading2
13.{  
14.public static void main(String[] args){  
15.System.out.println(Adder.add(11,11));  
16.System.out.println(Adder.add(12.3,12.6));  
17.}}  
Test it Now

Output:
85

22
24.9

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be
defined as the concept of having more than one constructor with different parameters
so that every constructor can perform a different task.

Consider the following Java program, in which we have used different constructors in


the class.

Example

1. public class Student {  
2. //instance variables of the class  
3. int id;  
4. String name;  
5.   
6. Student()
7. {  
8. System.out.println("this a default constructor");  
9. }  
10.  
11.Student(int i, String n){  
12.id = i;  
13.name = n;  
14.}  
15.  
16.public static void main(String[] args) {  
17.//object creation  
18.Student s = new Student();  
19.System.out.println("\nDefault Constructor values: \n");  
20.System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);  
21.  
22.System.out.println("\nParameterized Constructor values: \n");  
23.Student student = new Student(10, "David");  
86

24.System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);  
25.}  
26.}  

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

In the above example, the Student class constructor is overloaded with two different
constructors, I.e., default and parameterized.

Here, we need to understand the purpose of constructor overloading. Sometimes, we


need to use multiple constructors to initialize the different values of the class.

We must also notice that the java compiler invokes a default constructor when we do
not use any constructor in the class. However, the default constructor is not invoked if
we have used any constructor in the class, whether it is default or parameterized. In
this case, the java compiler throws an exception saying the constructor is undefined.

Consider the following example, which contains the error since the Colleges object can't
be created using the default constructor now since it doesn't contain one.

1. public class Colleges {  
2. String collegeId;  
3. Colleges(String collegeId){  
4. this.collegeId = "IIT " + collegeId;   
5. }  
6. public static void main(String[] args) {  
7. // TODO Auto-generated method stub  
8. Colleges clg = new Colleges(); //this can't create colleges constructor now.  
9. }  
87

10.  
11.  
12.}  

Use of this () in constructor overloading

However, we can use this keyword inside the constructor, which can be used to invoke
the other constructor of the same class.

Consider the following example to understand the use of this keyword in constructor
overloading.

1. public class Student {  
2. //instance variables of the class  
3. int id,passoutYear;  
4. String name,contactNo,collegeName;  
5.   
6. Student(String contactNo, String collegeName, int passoutYear){  
7. this.contactNo = contactNo;  
8. this.collegeName = collegeName;  
9. this.passoutYear = passoutYear;  
10.}  
11.  
12.Student(int id, String name){  
13.this("9899234455", "IIT Kanpur", 2018);  
14.this.id = id;  
15.this.name = name;  
16.}  
17.  
18.public static void main(String[] args) {  
19.//object creation  
20.Student s = new Student(101, "John");  
21.System.out.println("Printing Student Information: \n");  
22.System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact No.: "+s.contactNo+"\
nCollege Name: "+s.contactNo+"\nPassing Year: "+s.passoutYear);  
23.}  
88

24.}  

Output:

Printing Student Information:

Name: John
Id: 101
Contact No.: 9899234455
College Name: 9899234455
Passing Year: 2018

2.8 Java Garbage Collection


In java, garbage means unreferenced objects or unused objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.


In other words, it is a way to destroy the unused objects.

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

Ways for requesting JVM to run Garbage Collector

Once we made object eligible for garbage collection, it may not destroy immediately
by the garbage collector. Whenever JVM runs the Garbage Collector program, then
only the object will be destroyed. But when JVM runs Garbage Collector, we can not
expect.

 We can also request JVM to run Garbage Collector. There are two ways to do it :
1. Using System.gc() method : System class contain static method gc() for
requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime class allows the
application to interface with the JVM in which the application is running.
Hence by using its gc() method, we can request JVM to run Garbage
Collector.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.
89

o It is automatically done by the garbage collector(a part of JVM) so we don't


need to make extra efforts.

How can an object be unreferenced?


There are many ways:

o By nulling the reference

o By assigning a reference to another

o By anonymous object etc.

1) By nulling a reference:

1. Employee e=new Employee();  
2. e=null;  

2) By assigning a reference to another:

1. Employee e1=new Employee();  
2. Employee e2=new Employee();  
3. e1=e2;//now the first object referred by e1 is available for garbage collection  

3) By anonymous object:

1. new Employee();  

finalize() method
Finalization
 Just before destroying an object, Garbage Collector calls finalize() method on the
object to perform cleanup activities. Once finalize() method completes, Garbage
Collector destroys that object.
 finalize() method is present in Object class with following prototype.
 protected void finalize() throws Throwable
90

Based on our requirement, we can override finalize() method for perform our


cleanup activities like closing connection from database.

Note :
1. The finalize()  method called by Garbage Collector not JVM. Although Garbage
Collector is one of the module of JVM.
2. Object class finalize() method has empty implementation, thus it is
recommended to override finalize() method to dispose of system resources or
to perform other cleanup.
3. The finalize()  method is never invoked more than once for any given object.

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:

1. protected void finalize()
2. {
3. }  

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.

1. public static void gc()
2. {
3. }  

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).


This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java


1. public class TestGarbage1{  
2.  public void finalize(){System.out.println("object is garbage collected");}  
3.  public static void main(String args[]){  
4.   TestGarbage1 s1=new TestGarbage1();  
5.   TestGarbage1 s2=new TestGarbage1();  
91

6.   s1=null;  
7.   s2=null;  
8.   System.gc();  
9.  }  
10.}  

object is garbage collected


object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Example-2

// Java program to demonstrate requesting

// JVM to run Garbage Collector

public class Test

public static void main(String[] args) throws InterruptedException

Test t1 = new Test();

Test t2 = new Test();

// Nullifying the reference variable

t1 = null;

// requesting JVM for running Garbage Collector

System.gc();

// Nullifying the reference variable

t2 = null;

// requesting JVM for running Garbage Collector

Runtime.getRuntime().gc();

}
92

@Override

// finalize method is called on object once

// before garbage collecting it

protected void finalize() throws Throwable

System.out.println("Garbage collector called");

System.out.println("Object garbage collected : " + this);

Output:

1. Output:
2. Garbage collector called
3. Object garbage collected : Test@46d08f12
4. Garbage collector called
5. Object garbage collected : Test@481779b8
Note :
6. There is no guarantee that any one of above two methods will definitely run
Garbage Collector.
7. The call System.gc() is effectively equivalent to the
call : Runtime.getRuntime().gc()

2.9 What is String in java


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.

How to create a string object?


There are two ways to create String object:

1. By string literal

2. By new keyword
93

1) String Literal
Java String literal is created by using double quotes. For Example:

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

Note: String objects are stored in a special memory area known as the "string constant
pool".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).

2) By new keyword
94

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

Java String Example


1. public class StringExample{  
2. public static void main(String args[])
3. {  
4. String s1="java";//creating string by java string literal  
5. char ch[]={'s','t','r','i','n','g','s'};  
6. String s2=new String(ch);//converting char array to string  
7. String s3=new String("example");//creating java string by new keyword  
8. System.out.println(s1);  
9. System.out.println(s2);  
10.System.out.println(s3);  
11.}}  
Test it Now

java
strings
example

Java String compare

We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo()


method), reference matching (by == operator) etc.

There are three ways to compare string in java:

1. By equals() method

2. By = = operator

3. By compareTo() method
95

1) String compare by equals() method


The String equals() method compares the original content of the string. It compares
values of string for equality. String class provides two methods:

o public boolean equals(Object another) compares this string to the specified


object.

o public boolean equalsIgnoreCase(String another) compares this String to


another string, ignoring case.

1. class Teststringcomparison1{  
2.  public static void main(String args[])
3. {  
4.    String s1="Sachin";  
5.    String s2="Sachin";  
6.    String s3=new String("Sachin");  
7.    String s4="Saurav";  
8.    System.out.println(s1.equals(s2));//true  
9.    System.out.println(s1.equals(s3));//true  
10.   System.out.println(s1.equals(s4));//false  
11. }  
12.}  
Test it Now

Output:true
true
false
1. class Teststringcomparison2{  
2.  public static void main(String args[])
3. {  
4.    String s1="Sachin";  
5.    String s2="SACHIN";  
6.   
7.    System.out.println(s1.equals(s2));//false  
8.    System.out.println(s1.equalsIgnoreCase(s2));//true  
9.  }  
10.}  
96

Test it Now

Output:

false
true
Click here for more about equals() method

2) String compare by == operator


The = = operator compares references not values.

1. class Teststringcomparison3{  
2.  public static void main(String args[]){  
3.    String s1="Sachin";  
4.    String s2="Sachin";  
5.    String s3=new String("Sachin");  
6.    System.out.println(s1==s2);//true (because both refer to same instance)  
7.    System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool) 
 
8.  }  
9. }  
Test it Now

Output:true
false

3) String compare by compareTo() method


The String compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second
string.

Suppose s1 and s2 are two string variables. If:

o s1 == s2 :0

o s1 > s2   :positive value

o s1 < s2   :negative value


97

1. class Teststringcomparison4{  
2.  public static void main(String args[])
3. {  
4.    String s1="Sachin";  
5.    String s2="Sachin";  
6.    String s3="Ratan";  
7.    System.out.println(s1.compareTo(s2));//0  
8.    System.out.println(s1.compareTo(s3));//1(because s1>s3)  
9.    System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
10. }  
11.}  
Test it Now

Output:0
1
-1

java String class methods


The java.lang.String class provides a lot of methods to work on string. By the help of
these methods, we can perform operations on string 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.

Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and
string toLowerCase() method into lowercase letter.

1. String s="Sachin";  
2. System.out.println(s.toUpperCase());//SACHIN  
3. System.out.println(s.toLowerCase());//sachin  
4. System.out.println(s);//Sachin(no change in original)  
Test it Now

SACHIN
sachin
Sachin
98

Java String trim() method


The string trim() method eliminates white spaces before and after string.

1. String s="  Sachin  ";  
2. System.out.println(s);//  Sachin    
3. System.out.println(s.trim());//Sachin  
Test it Now

Sachin
Sachin

Java String startsWith() and endsWith() method

1. String s="Sachin";  
2.  System.out.println(s.startsWith("Sa"));//true  
3.  System.out.println(s.endsWith("n"));//true  
Test it Now

true
true

Java String charAt() method


The string charAt() method returns a character at specified index.

1. String s="Sachin";  
2. System.out.println(s.charAt(0));//S  
3. System.out.println(s.charAt(3));//h  
Test it Now

S
h

Java String length() method


The string length() method returns length of the string.

1. String s="Sachin";  
2. System.out.println(s.length());//6  
Test it Now

6
99

Java String intern() method


A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equals(Object) method, then the string from the
pool is returned. Otherwise, this String object is added to the pool and a reference to
this String object is returned.

1. String s=new String("Sachin");  
2. String s2=s.intern();  
3. System.out.println(s2);//Sachin  
Test it Now

Sachin

Java String valueOf() method


The string valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into string.

1. int a=10;  
2. String s=String.valueOf(a);  
3. System.out.println(s+10);  

Output:

1010

Java String replace() method


The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.

1. String s1="Java is a programming language. Java is a platform. Java is an Island.";    
2. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "
Kava"    
3. System.out.println(replaceString);    

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.


100

Java String substring() method example


The java string substring() method returns a part of the string.

We pass begin index and end index number position in the java substring method
where start index is inclusive and end index is exclusive. In other words, start index
starts from 0 whereas end index starts from 1.

1. public class SubstringExample{  
2. public static void main(String args[])
3. {  
4. String s1="javatpoint";  
5. System.out.println(s1.substring(2,4));//returns va  
6. System.out.println(s1.substring(2));//returns vatpoint  
7. }
8. }  

Java String contains() method example


1. class ContainsExample{  
2. public static void main(String args[])
3. {  
4. String name="what do you know about me";  
5. System.out.println(name.contains("do you know"));  
6. System.out.println(name.contains("about"));  
7. System.out.println(name.contains("hello"));  
8. }
9. }  
Test it Now

true
true
false
101

2.10 Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the


initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified


string.

StringBuffer(int capacity) creates an empty string buffer with the


specified capacity as length.

What is mutable string


A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method


The append() method concatenates the given argument with this string.

1. class StringBufferExample{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello ");  
4. sb.append("Java");//now original string is changed  
102

5. System.out.println(sb);//prints Hello Java  
6. }  
7. }  

2) StringBuffer insert() method


The insert() method inserts the given string with this string at the given position.

1. class StringBufferExample2{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello ");  
4. sb.insert(1,"Java");//now original string is changed  
5. System.out.println(sb);//prints HJavaello  
6. }  
7. }  

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and
endIndex.

1. class StringBufferExample3{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.replace(1,3,"Java");  
5. System.out.println(sb);//prints HJavalo  
6. }  
7. }  

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.

1. class StringBufferExample4{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.delete(1,3);  
103

5. System.out.println(sb);//prints Hlo  
6. }  
7. }  

5) StringBuffer reverse() method


The reverse() method of StringBuilder class reverses the current string.

1. class StringBufferExample5{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.reverse();  
5. System.out.println(sb);//prints olleH  
6. }  
7. }  

6) StringBuffer capacity() method


The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.

1. class StringBufferExample6{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer();  
4. System.out.println(sb.capacity());//default 16  
5. sb.append("Hello");  
6. System.out.println(sb.capacity());//now 16  
7. sb.append("java is my favourite language");  
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
9. }  
10.}  
104

2.11 Wrapper classes in Java


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

A Wrapper class is a class whose object wraps or contains primitive data types. When
we create an object to a wrapper class, it contains a field and in this field, we can
store primitive data types. In other words, we can wrap a primitive value into a
wrapper class object.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and


objects into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects
many times like in Collections, Serialization, Synchronization, etc. Let us see the
different scenarios, where we need to use the wrapper classes.

o Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.

o Serialization: We need to convert the objects into streams to perform the


serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.

o java.util package: The java.util package provides the utility classes to deal with
objects.

o Collection Framework: Java collection framework works with objects only. All


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

o They convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method (because primitive types are
passed by value).
105

o The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
o Data structures in the Collection framework, such as ArrayList and Vector, store
only objects (reference types) and not primitive types.
o An object is needed to support synchronization in multithreading.

The eight classes of the java.lang package are known as wrapper classes in Java. The
list of eight wrapper classes are given below:

Primitive Wrapper
Type class

boolea Boolean
n

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long
to Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.

Wrapper class Example: Primitive to Wrapper


106

//Java program to convert primitive into objects  
//Autoboxing example of int to Integer  
public class WraperExample
{
public static void main(String args[])
{
//Converting int into Integer explicitly and automatically
int a=20;

Integer i1=Integer.valueOf(a);//converting int into Integer explicitly

System.out.println(i1);

Integer i2= new Integer(10);//autoboxing


Integer y=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(i2);
System.out.println(y);

}
}

Output:

20
10
20

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

Wrapper class Example: Wrapper to Primitive

//Java program to convert object into primitives  
//Unboxing example of Integer to int  
public class Unboxing
{
public static void main(String args[])
{
//Converting Integer to int

Integer i1=Integer.valueOf(100);//explicit conversion of int to Integer object


107

Integer i2=new Integer(200);//auto boxing implicit conversion of int to Integer object

System.out.println(i1);
System.out.println(i2);
System.out.println("-----");

int i=i1.intValue();//converting Integer to int explicitly

int j=i2;//unboxing, now compiler will write a.intValue() internally

System.out.println(i);
System.out.println(j);
}
}

Output:

100
200
-----
100
200

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

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){  
2. //code to be executed  
3. methodname();//calling same method  
4. }  

Java Recursion Example 1: Infinite times


1. public class RecursionExample1 {  
2. static void p(){  
3. System.out.println("hello");  
4. p();  
108

5. }  
6.   
7. public static void main(String[] args) {  
8. p();  
9. }  
10.}  

Output:

hello
hello
...
java.lang.StackOverflowError

You might also like