Java - Unit-1 - Final
Java - Unit-1 - Final
Java - Unit-1 - Final
POP characteristics
Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#, Perl,
Python, Ruby, and PHP.
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.
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.
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.
Global data is shared among the functions in the Data is shared among the objects through the
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.
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.
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
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.
Object Definitions:
2. CLASS
o Fields
o Methods
o Constructors
o Blocks
5
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.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
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.
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
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc…
5 ABSTRACTION
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
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.
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.
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. 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
Object-oriented
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
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
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
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
o Security Manager: It determines what resources a class can access such as reading
Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
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
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++.
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
.
Hello.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,
include Classes, Interfaces, and Arrays.
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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.
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.
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.
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.
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.
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
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
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.
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.
Output
Example
Following example uses age without initializing it, so it would give an error at the time of compilation.
Output
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
{
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
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
Output
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.
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.
Java has a set of keywords that are reserved words that cannot be used as variables,
methods, classes, or any other identifiers:
implement impor
for goto if
s t
instanceo interfac
int long native
f e
synchronize throw
switch this throw
d s
Note: true, false, and null are not keywords, but they are literals and reserved words that
cannot be used as identifiers.
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.
prefix ++expr --expr +expr -expr ~ !
additive +-
equality == !=
bitwise ^
exclusive OR
bitwise |
25
inclusive OR
logical OR ||
Ternary ternary ?:
A joint statement defining the scope and lifetime of a variable is “how and where the
variable is defined.”
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.
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
Example
num1 = a;
num2 = b;
return a+b;
Expressions in java
int score;
score = 90;
if (number1 == number2)
System.out.println("Number 1 is larger than number 2");
Convert a value from one data type to another data type is known as 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:
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
In the above example, we have taken a variable x and converted it into a long type. After
that, the long type is converted into the float type.
Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If
we do not perform casting then the compiler reports a compile-time error.
1. double -> float -> long -> int -> char -> short -> byte
29
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
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) ,
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.
o Enum may implement many interfaces but cannot extend any class because it
1. enum Season { WINTER, SPRING, SUMMER, FALL }
Or,
1. enum Season { WINTER, SPRING, SUMMER, FALL; }
example—1 :
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output :
RED
32
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
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
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.
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.
The Java compiler internally adds the valueOf() method when it creates an enum. The
valueOf() method returns the value of given constant 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
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
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.
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
Yes, Of course! we can have abstract methods and can provide the implementation of these
methods.
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.
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
o Multidimensional Array
39
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
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
We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
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
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.
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
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:
In such case, data is stored in row and column based index (also known as matrix form).
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
1. int[][] arr=new int[3][3];//3 row and 3 column
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;
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
import java.util.Scanner;
from InputStream, File, and String respectively.
45
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;
// String input
String name = s.nextLine();
// Numerical input
int age = s.nextInt();
double salary = s.nextDouble();
output :
Enter name, age and salary
raju
24
5000
Name: raju
Age: 24
Salary: 5000.0
The print and println Methods
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");
}
}
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.
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:
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.
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.
2. Parameterized constructor
1. <class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
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
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
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.
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
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
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
There are many differences between constructors and methods. They are given below.
A constructor must not have a return A method must have a return type.
53
type.
The Java compiler provides a default The method is not provided by the
constructor in a class.
The constructor name must be same as The method name may or may not be
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
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
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
Yes, it is the current class instance (You cannot use return type yet it returns a value).
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.
Yes.
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.
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.
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
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, 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
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
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.
3. Block
4. Nested class
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.
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
o The static variable gets memory only once in the class area at the time of class
loading.
Static variable initialization
primitive integers(long, short etc): 0
primitive floating points(float, double): 0.0
boolean: false
object references: null
The static final variables are constants. Lets have a look at the code below:
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.
Key points:
final variable always needs initialization, if you don’t initialize it would throw a compilation
error. have a look at below example-
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.
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:
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.
Syntax:
Static keyword followed by return type, followed by method name.
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
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.
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. }
class Test{
static {
//Code goes here
}
}
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.
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. }
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
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
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.
Private
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.
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
}
}
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. }
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.
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.
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.
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
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.
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.
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:
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:
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.
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
1. class Student{
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
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
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
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
1. return_type method_name()
2. {
3. return this;
4. }
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
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
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
In Java, Method Overloading is not possible by changing the return type of the method only.
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.
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
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
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:
Student Id : 0
Student Name : null
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.
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.}
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:
Name: John
Id: 101
Contact No.: 9899234455
College Name: 9899234455
Passing Year: 2018
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
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.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
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
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. }
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10.}
Example-2
t1 = null;
System.gc();
t2 = null;
Runtime.getRuntime().gc();
}
92
@Override
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()
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".
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
strings
example
1. By equals() method
2. By = = operator
3. By compareTo() method
95
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
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
o s1 == s2 :0
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 is a powerful concept because everything is treated as a string if you submit
any form in window based, web based or mobile application.
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
1. String s=" Sachin ";
2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin
Test it Now
Sachin
Sachin
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
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
1. String s="Sachin";
2. System.out.println(s.length());//6
Test it Now
6
99
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
1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);
Output:
1010
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:
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. }
true
true
false
101
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.
Constructor Description
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. }
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. }
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. }
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. }
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. }
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
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.
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 java.util package: The java.util package provides the utility classes to deal with
objects.
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.
//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;
System.out.println(i1);
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.
//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
System.out.println(i1);
System.out.println(i2);
System.out.println("-----");
System.out.println(i);
System.out.println(j);
}
}
Output:
100
200
-----
100
200
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
5. }
6.
7. public static void main(String[] args) {
8. p();
9. }
10.}
Output:
hello
hello
...
java.lang.StackOverflowError