Java PDF
Java PDF
Java PDF
Topics
Class has
If we make 5 Object of same class, each object will have one copy of attributes/Behaviour
Advantage of Method
Code reusability
Code optimisation.
package ClassExample;
Java main method is the entry point of any java program. Its syntax is always public static
void main(String[] args). You can only change the name of String array argument, for
example you can change args to myStringArgs.
Also String array argument can be written as String... args or String args[].
public
This is the access modifier of the main method. It has to be public so that java runtime can
execute this method. Remember that if you make any method non-public then it’s not
allowed to be executed by any program, there are some access restrictions applied. So it
means that the main method has to be public.
static
When java runtime starts, there is no object of the class present. That’s why the main
method has to be static so that JVM can load the class into memory and call the main
method. If the main method won’t be static, JVM would not be able to call it because there
is no object of the class is present
void
Java programming mandates that every method provide the return type. Java main method
doesn’t return anything, that’s why it’s return type is void. This has been done to keep
things simple because once the main method is finished executing, java program
terminates. So there is no point in returning anything, there is nothing that can be done for
the returned object by JVM. If we try to return something from the main method, it will give
compilation error as an unexpected return value.
package ClassExample;
return 0;
String[] args
Java main method accepts a single argument of type String array. This is also called as java
command line arguments.
package classExample;
• By JAVA Switch
• JAVA Break
• JAVA Continue
If
If else
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
package controlStatements;
package controlStatements;
else{
System.out.println("Invalid data");
}
}
}
switch-case
switch-case The switch statement is a multiway branch statement. It provides an easy way
to dispatch execution to different parts of code based on the value of the expression.
package controlStatements;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
public class SwitchExample {
package controlStatements;
For Loop
The Java for loop is a control flow statement that iterates a part of the programs
multiple times.
package controlStatements;
1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
2. Condition: It is the second condition which is executed each time to test the
condition of the loop. It continues execution until the condition is false. It must
return boolean value either true or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the second
condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an
optional condition.
package controlStatements;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
public class ForLoopExample1 {
For-each Loop
package controlStatements;
System.out.println("============");
while loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
package controlStatements;
int i = 5;
while (i <= 10) {
System.out.println(i);
i++;
}
}
}
package controlStatements;
while(true){
System.out.println("while loop is running in infinitive");
}
}
}
package controlStatements;
Java Break
package controlStatements;
package controlStatements;
package controlStatements;
package controlStatements;
package controlStatements;
package controlStatements;
• Local
• Instance
• Static
package VariableDataType;
Data Type
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
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.
Default Value
Data Type Default size
FALSE
boolean 1 bit
'\u0000'
char 2 byte
0
byte 1 byte
0
short 2 byte
0
int 4 byte
0L
long 8 byte
0.0f
float 4 byte
0.0d
double 8 byte
package ReturnTypeInJava;
constructors are used to assign values to the class variables at the time of object creation,
either explicitly done by the programmer or by Java itself (default constructor).
Default Constructor
package constructor;
Example1() {
}
Parameterized constructor
package constructor;
int length;
int breadth;
int height;
package constructor;
public Example3(int i) {
this.i = i;
System.out.println("Parameterized");
}
Example3() {
System.out.println("default");
}
package constructor;
private Example4(){
System.out.println("default");
}
package constructor;
void Example5(){
System.out.println("default");
}
• Constructor(s) must have the same name as the class within which it defined while it is
not necessary for the method in java.
• Constructor(s) do not return any type while method(s) have the return type or void if
does not return any value.
• Constructor is called only once at the time of Object creation while method(s) can be
called any numbers of time.
package constructor;
Example6() {
super();
}
package constructor;
Example7() {
System.out.println("I am Example7()");
}
Example7(int i) {
this();
System.out.println("I am Example7(int i)");
}
Example8(int i) {
this();
System.out.println("I am Example7(int i)");
}
Example8(int i, int j) {
this(5);
System.out.println("I am Example8(int i,int j) ");
}
package constructor;
public Example9(){
}
public Example9(String name, int age, String state) {
this.name = name;
this.age = age;
this.state = state;
}
package constructor;
package staticBlock;
static {
System.out.println("this is sttaic block");
}
}
Static Blocks
If you want to do some calculation in order to initialise the static variables, we can declare
them in static block, and static block gets executed only once per class, when the class is first
loaded.
package staticBlock;
static {
System.out.println("Static block initialized.");
j = i * 2;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
Static Variable
When you declare variable as static, then only one copy of variable is created and shared
among the object. Static variable is always class variable or global variable.
package staticBlock;
package staticBlock;
static {
System.out.println("static block");
}
static {
System.out.println("value of i=" + i);
}
}
}
package staticBlock;
void display() {
System.out.println("value of k is:=" + k);
}
obj.display();
int i = 90;
static int k = 80;
static{
k = 100;
i = 60;
}
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.
package staticBlock;
void test2() {
i = 20;
b = 10;
System.out.println("from m2");
}
package staticBlock;
void test2(){
System.out.println("test1()");
}
package staticBlock;
package staticBlock;
package staticBlock;
class MyNestedClass {
public void disp() {
System.out.println(str);
}
}
package staticBlock;
class MyNestedClass {
public void disp() {
System.out.println(str);
}
}
package staticBlock;
package staticBlock;
Student(String studentName) {
this.studentName = studentName;
this.rollnumber = increaseRollNumber();
}
package ThisExample;
void display() {
System.out.println(rollno + " " + name + " " + fee);
}
package ThisExample;
void display() {
System.out.println(rollno + " " + name + " " + fee);
}
package ThisExample;
void display() {
this.show();
void show() {
System.out.println("Inside show funcion");
}
package ThisExample;
Example4() {
this(10, 20);
System.out.println("Inside default constructor \n");
}
Example4(int a, int b) {
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}
package ThisExample;
void p() {
m(this);
}
Example7 obj;
Example6(Example7 obj) {
this.obj = obj;
obj.display();
}
}
package ThisExample;
int i = 90;
Example7() {
Example6 obj = new Example6(this);
}
void display() {
System.out.println("Value of i in Class Example7 : " + i);
}
}
}
package ThisExample;
public class Example8 {
int a;
int b;
Example8() {
a = 10;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
b = 20;
}
Example8 get() {
return this;
}
void display() {
System.out.println("a = " + a + " b = " + b);
}
Inheritance in Java
As we know, a child inherits the properties from his parents. A similar concept is followed in
Java, where we have two classes:
A class which inherits the properties is known as Child Class whereas a class whose properties
are inherited is known as Parent class.
Syntax
package inheritance;
2. Multilevel Inheritance
package inheritance;
int roolnumber;
package inheritance;
void does() {
System.out.println("Teaching");
}
}
package inheritance;
Multilevel Inheritance
package inheritance;
package inheritance;
package inheritance;
int age;
String name;
package inheritance;
int speed;
package inheritance;
int price;
String name;
@Override
public String toString() {
return "Car [price=" + price + ", name=" + name + ", speed=" + speed + "]";
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
}
package inheritance;
int price;
String name;
@Override
public String toString() {
return "Jeep [price=" + price + ", name=" + name + ", speed=" + speed + "]";
}
package inheritance;
void msg(){
}
}
package inheritance;
}
}
package inheritance;
package inheritance;
int a;
public Conts1(int a) {
this.a = a;
}
Conts1() {
}
}
package inheritance;
Aggregation in Java
Aggregation in Java is a relationship between two classes that is best described as a "has-a"
and "whole/part" relationship. ... The aggregate class contains a reference to another class
and is said to have ownership of that class. Each class referenced is considered to be part-of
the aggregate class.
int square(int n) {
return n * n;
}
package inheritance;
Operation operation;
Employee has an object of Address, address object contains its own informations such as
city, state, country etc. In such case relationship is Employee HAS-A address.
package inheritance;
package inheritance;
int id;
String name;
Address address;
void display() {
System.out.println(id + " " + name);
System.out.println(address.city + " " + address.state + " " + address.country);
}
e.display();
e2.display();
}
}
Java Polymorphism
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor overloading
in Java, that allows a class to have more than one constructor having different argument
lists.
package methodOverloading;
%d Decimal integer
Important Points
• Two or more methods can have same name inside the same class if they accept
different arguments. This feature is known as method overloading.
• Method overloading is achieved by either:
o changing the number of arguments.
o or changing the datatype of arguments.
• Method overloading is not possible by changing the return type of methods.
Suppose, you have to perform addition of the given numbers but there can be any number
of arguments (let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods sum1num(int,
int) and sum2num(int, int, int) for two and three parameters respectively. However, other
programmers as well as you in future may get confused as the behaviour of both methods is
same but they differ by name.
The better way to accomplish this task is by overloading methods. And, depending upon the
argument passed, one of the overloaded methods is called. This helps to increase readability
of the program
Why Method Overloading is not possible by changing the return type of method only?
. package methodOverloading;
class TestOverloading3 {
public static void main(String[] args) {
System.out.println(Adder.add(11, 11));// ambiguity
}
}
Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as arguments
only
package methodOverloading;
package methodOverloading;
package methodOverloading;
When parent class has only parameterised constructor Then child class has to explicitly
call the parent class parameterised constructor.
package methodOverloading;
Overloading8(int i) {
}
}
package methodOverloading;
Overloading9(int i) {
super(i);
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
}
}
When parent class has parameterised and default constructor Then child class has not
explicitly call to the parent class constructor. Since Java compiler will keep spuer() as
first line of constructor.
package methodOverloading;
Overloading10(int i) {
Overloading10() {
}
}
package methodOverloading;
Overloading11(){
package methodOverriding;
}
package methodOverriding;
Overriding2.test1();
}
}
package methodOverriding;
}
package methodOverriding;
package methodOverriding;
}
package methodOverriding;
It is because the static method is bound with class whereas instance method is bound with
an object. Static belongs to the class area, and an instance belongs to the heap area.
package methodOverriding;
package methodOverriding;
// Example2.test2();
}
}
Interface in Java
Points to remember
• An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
2. Another feature that was added in JDK 8 is that we can now define static methods in
interfaces which can be called independently without an object. Note: these
methods are not inherited.
Syntax
package interfaceInjava;
int i = 90;
void test1();
package interfaceInjava;
int i = 90;
void test1();
package interfaceInjava;
@Override
public void test1() {
// TODO Auto-generated method stub
@Override
public void test2() {
// TODO Auto-generated method stub
Example3(){
}
}
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
package interfaceInjava;
Example4 example4;
void method5();
}
package interfaceInjava;
void method6();
}
package interfaceInjava;
package interfaceInjava;
void method6();
When class implements interface which extends more than one interface.
package interfaceInjava;
void method5();
}
package interfaceInjava;
void method6();
}
package interfaceInjava;
}
package interfaceInjava;
@Override
public void method5() {
// TODO Auto-generated method stub
@Override
public void method6() {
// TODO Auto-generated method stub
package interfaceInjava;
package interfaceInjava;
int speed;
int gear;
@Override
public void changeGear(int a) {
gear = a;
}
@Override
public void speedUp(int a) {
speed = a;
}
@Override
public void applyBrakes(int a) {
speed = speed - a;
}
package interfaceInjava;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
public class Bike implements Vehicle {
int speed;
int gear;
@Override
public void changeGear(int a) {
gear = a;
}
@Override
public void speedUp(int a) {
speed = a;
}
@Override
public void applyBrakes(int a) {
speed = speed - a;
}
package interfaceInjava;
Abstract classes
1. An abstract class is a class that is declared with abstract keyword.
2. An abstract method is a method that is declared without an implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be
concrete methods
4. A method defined abstract must always be redefined in the subclass, thus
making overriding compulsory OR either make subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with
abstract keyword.
6. There can be no object of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator.
7. An abstract class can have parametrized constructors and default constructor is always
present in an abstract class.
Syntax
package abstractInJava;
void test1() {
package abstractInJava;
int i = 80;
package abstractInJava;
@Override
public String toString() {
return "Name=" + this.name + "::Gender=" + this.gender;
}
package abstractInJava;
@Override
public void work() {
if (empId == 0) {
System.out.println("Not working");
} else {
System.out.println("Working as employee");
}
}
Ans: NO
Because these classes are incomplete, they have abstract methods that have no body so if
java allows you to create object of this class then if someone calls the abstract method using
that object then What would happen? There would be no actual implementation of the
method to invoke.
Also because an object is concrete. An abstract class is like a template, so you have to
extend it and build on it before you can use it.
Ans: Yes
package abstractInJava;
int i;
String name;
Example3() {
}
}
Abstract Vs Interface
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain
a mix of methods declared with or without an implementation. However, with abstract
classes, you can declare fields that are not static and final, and define public, protected, and
private concrete methods. With interfaces, all fields are automatically public, static, and
final, and all methods that you declare or define (as default methods) are public. In addition,
you can extend only one class, whether or not it is abstract, whereas you can implement any
number of interfaces.
• Consider using abstract classes if any of these statements apply to your situation:
• You want to share code among several closely related classes.
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
• You expect that classes that extend your abstract class have many common
methods or fields, or require access modifiers other than public (such as
protected and private).
• You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they
belong.
• Consider using interfaces if any of these statements apply to your situation:
• You expect that unrelated classes would implement your interface. For
example, the interfaces Comparable and Cloneable are implemented by
many unrelated classes.
• You want to specify the behaviour of a particular data type, but not
concerned about who implements its behaviour.
• You want to take advantage of multiple inheritance of type.
Access Modifier
package accessmodifier;
String s4;
void name4() {
What are the members we can access in different class, within same package?
package accessmodifier;
example1.name1();
example1.name2();
example1.name4();
System.out.println(example1.s1);
System.out.println(example1.s3);
System.out.println(example1.s4);
}
}
What are the members we can access in different class, in different package?
package access.modifier.test;
import accessmodifier.Example1;
example1.name2();
System.out.println(example1.s1);
}
package access.modifier.test;
import accessmodifier.Example1;
System.out.println(example4.s1);
System.out.println(example4.s3);
}
Java Enum
Enum in java is a data type that contains 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) etc. The java enum
constants are static and final implicitly.
package enumjava;
}
}
package enumjava;
enum Season {
WINTER(5), SPRING(10), SUMMER(15), FALL(20);
}
}
package enumjava;
package enumjava;
package enumjava;
package enumjava;
System.out.println(data);
}
}
package enumjava;
long l = i;
float f = l;
double d = i;
Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot
be done.
• Here, target-type specifies the desired type to convert the specified value to.
long l = (long) d;
int i = (int) l;
short b = (short)d;
Byte Class which is used to return number of bits required to represent a byte value in
binary representation (two’s complement).
package typeCasting;
b = (byte) i;
System.out.println("i = " + i + " b = " + b);
package typeCasting;
public class A {
package typeCasting;
obj.test2();
((B) obj1).test1();
}
package typeCasting;
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
package finalInJava;
void run() {
speedlimit = 400; // Compile Time error
}
package finalInJava;
}
}
package finalInJava;
}
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
3) Java Final Class
package finalInJava;
}
package finalInJava;
A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
package finalInJava;
int id;
String name;
final String PAN_CARD_NUMBER;
Example6(String panNumber) {
this.PAN_CARD_NUMBER = panNumber;
}
package finalInJava;
int id;
String name;
final String PAN_CARD_NUMBER="123";
Example6(String panNumber) {
this.PAN_CARD_NUMBER = panNumber;
}
}
package finalInJava;
Example7() {
speedlimit = 70;
System.out.println(speedlimit);
}
A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
package finalInJava;
package finalInJava;
void run() {
System.out.println("running");
}
}
package RuntimePolymorphism;
void run() {
System.out.println("running safely with 60km");
}
package RuntimePolymorphism;
float getRateOfInterest() {
return 0;
}
}
class TestPolymorphism {
public static void main(String args[]) {
Example3 b;
b = new SBI();
System.out.println("SBI Rate of Interest: " + b.getRateOfInterest());
b = new ICICI();
System.out.println("ICICI Rate of Interest: " + b.getRateOfInterest());
b = new HDFC();
System.out.println("HDFC Rate of Interest: " + b.getRateOfInterest());
}
}
package RuntimePolymorphism;
void eat() {
System.out.println("eating...");
}
}
package RuntimePolymorphism;
void eat() {
System.out.println("eats rat...");
}
}
void eat() {
System.out.println("eats bread...");
}
package RuntimePolymorphism;
void eat() {
System.out.println("eats meat...");
}
}
If there is any private, final or static method in a class, there is static binding.
package staticAndDynamicBinding;
Dynamic binding
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
package instanceOfInJava;
package instanceOfInJava;
package instanceOfInJava;
package instanceOfInJava;
Encapsulation in Java
Suppose you have an account in the bank. If your balance variable is declared as a public
variable in the bank software, your account balance will be known as public, In this case,
anyone can know your account balance. So, would you like it? Obviously No.
So, they declare balance variable as private for making your account safe, so that anyone
cannot see your account balance. The person who has to see his account balance, he will
have to access private members only through methods defined inside that class and this
method will ask your account holder name or user Id, and password for authentication.
Thus, We can achieve security by utilizing the concept of data hiding. This is called
Encapsulation.
Key point:
In Java, Encapsulation is one of the four principles of OOPs concepts and the other three are
Abstraction, Inheritance, and Polymorphism.
How to achieve or implement Encapsulation in Java
package encapsulationInJava;
package encapsulationInJava;
System.out.println("name="+obj.getName()+" age="+obj.getAge());
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
}
package encapsulationInJava;
}
this.name = name;
}
package encapsulationInJava;
obj.setAge(9);
System.out.println(obj.getAge());
}
package encapsulationInJava;
@Override
public String toString() {
return "Example4 [schoolName=" + schoolName + ", studentName=" +
studentName + "]";
}
package encapsulationInJava;
System.out.println(obj);
}
}
Let's understand how Encapsulation allows modifying implemented Java code without
breaking others code who have implemented the code? Since data type of Id has been
changed from String to Integer. So, I will only change in getter and setter method to avoid
breaking of other codes.
package encapsulationInJava;
package encapsulationInJava;
Suppose in above program 3, anyone changes the data type of id from String to Integer like
this:
package encapsulationInJava;
package encapsulationInJava;
Now, what will happen? Whenever Id has been used then the compilation time error will be
generated.
When you have encapsulation , this issue can be solved without breaking the
implementation.
Integer id;
What is Abstraction
Abstraction is a process of hiding the implementation details from the user. Оnly the
functionality will be provided to the user. In Java, abstraction is achieved using abstract
classes and interfaces.
package abstractionInJava;
The Contractor class inherits all properties from its parent Employee but have to provide it’s
own implementation of calculateSalary() method. In this case we multiply the value of
payment per hour with given working hours.
package abstractionInJava;
@Override
public int calculateSalary() {
return getPaymentPerHour() * workingHours;
}
}
The FullTimeEmployee also has it’s own implementation ofcalculateSalary()method. In this
case we just multiply by constant 8 hours.
package abstractionInJava;
@Override
public int calculateSalary() {
return getPaymentPerHour() * 8;
}
}
String In Java
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is
an immutable object which means it is constant and can cannot be changed once it has
been created.
Creating a String
1. String literal
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
2. Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
if the object already exist in the memory it does not create a new Object rather it assigns
the same old object to the new instance, that means even though we have two string
instances above(str1 and str2) compiler only created on string object (having the value
“Welcome”) and assigned the same to both the instances. For example there are 10 string
instances that have same value, it means that in memory there is only one object having the
value and all the 10 string instances would be pointing to the same object.
In this case compiler would create two different object in memory having the same string.
Immutable String
Immutable String means , once String object is created it can’t be changed or modified.
Example:
package stringInjava;
Here output remains “Bhanu” , since String is immutable and new object is created in
memory “BhanuJava”
String compare
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. 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.
o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value
package stringInjava;
String s1 = "Bhanu";
String s2 = "Bhanu";
String s3 = new String("Bhanu");
String s4 = "Test";
System.out.println(s1.equals(s2));// true
System.out.println(s1.equals(s3));// true
System.out.println(s1.equals(s4));// false
s1 = "Bhanu";
s2 = "BHANU";
System.out.println(s1.equals(s2));// false
System.out.println(s1.equalsIgnoreCase(s2));// true
s1 = "Bhanu";
s2 = "Bhanu";
s3 = "Bist1";
System.out.println(s1.compareTo(s2));// 0
System.out.println(s1.compareTo(s3));// -1(because s1>s3)
System.out.println(s3.compareTo(s1));// 1(because s3 < s1 )
}
Concatenation
package stringInjava;
Substring
You can get substring from the given string object by one of the two methods:
In case of string:
o startIndex: inclusive
o endIndex: exclusive
package stringInjava;
charAt()
package stringInjava;
name.charAt(20);
}
}
contains()
package stringInjava;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
public class Example7 {
package stringInjava;
endsWith()
package stringInjava;
package stringInjava;
equalsIgnoreCase()
package stringInjava;
format()
The java string format() method returns the formatted string by given locale, format
and arguments.
package stringInjava;
package stringInjava;
example where we are setting width and padding for an integer value.
getBytes()
package stringInjava;
getChars()
Method copies the content of this string into specified char array
public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginInde
x)
package stringInjava;
java.lang.ArrayIndexOutOfBoundsException
package stringInjava;
indexOf()
Method Description
int indexOf(int ch) returns index position for the given char value
package stringInjava;
intern()
package stringInjava;
package stringInjava;
isEmpty()
package stringInjava;
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
join()
package stringInjava;
lastIndexOf()
Method Description
int lastIndexOf(int ch) returns last index position for the given char value
int lastIndexOf(int ch, int returns last index position for the given char value
fromIndex) and from index
int lastIndexOf(String substring) returns last index position for the given substring
int lastIndexOf(String substring, int returns last index position for the given substring
fromIndex) and from index
package stringInjava;
s1.lastIndexOf('s', 5);
System.out.println(index);
s1.lastIndexOf("of");
System.out.println(index);
}
}
package stringInjava;
replace()
package stringInjava;
split()
package stringInjava;
startsWith()
package stringInjava;
System.out.println(s1.startsWith("a",7));
System.out.println(s1.startsWith("a",40));
}
}
substring()
Parameters
package stringInjava;
// java.lang.StringIndexOutOfBoundsException:
String substr3 = s1.substring(5, 15);
}
}
toCharArray()
package stringInjava;
toLowerCase()
toUpperCase()
package stringInjava;
String s1 = "HELLO";
System.out.println(s1.toLowerCase());
}
}
trim()
package stringInjava;
System.out.println("123"+s1.trim()+"12");
System.out.println("123"+s1+"12");
}
}
valueOf()
The java string valueOf() method converts different types of values into string.
• public static String valueOf(boolean b)
• public static String valueOf(char c)
• public static String valueOf(char[] c)
• public static String valueOf(int i)
• public static String valueOf(long l)
• public static String valueOf(float f)
• public static String valueOf(double d)
• public static String valueOf(Object o)
package stringInjava;
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 creates an empty string buffer with the specified capacity as
capacity) length.
package stringBuffer;
// insert() method
// delete() method
StringBuffer sb3 = new StringBuffer("Hello");
sb3.delete(1, 3);
System.out.println(sb3);
// capacity() method
package stringBuffer;
Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as
length.
Exception in Java
Exceptions are events that occur during the execution of programs that disrupt the normal
flow of instructions (e.g. divide by zero, array access out of bound, etc.). In Java,
an exception is an object that wraps an error event that occurred within a method and
contains: Information about the error including its type.
package exception;
Types of Exception
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
1. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than
the size of the string
package exception;
package exception;
package exception;
package exception;
package exception;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 ex) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 ex) {
// exception handler for ExceptionType2
}
// optional
finally {
// block of code to be executed after try block ends
}
Points to remember :
• In a method, there can be more than one statements that might throw exception, So
put all these statements within its own try block and provide separate exception
handler within own catch block for each of them.
• If an exception occurs within the try block, that exception is handled by the exception
handler associated with it. To associate exception handler, we must put catch block
after it. There can be more than one exception handlers. Each catch block is a
exception handler that handles the exception of the type indicated by its argument.
The argument, Exception Type declares the type of the exception that it can handle
and must be the name of the class that inherits from Throwable class.
• For each try block there can be zero or more catch blocks, but only one finally block.
• The finally block is optional. It always gets executed whether an exception occurred in
try block or not . If exception occurs, then it will be executed after try and catch
blocks. And if exception does not occur then it will be executed after the try block. The
finally block in java is used to put important codes such as clean up code e.g. closing
the file or closing the connection.
package exception;
package exception;
package exception;
String s1 = null;
System.out.println(s1.length());
} catch (ArithmeticException e) {
System.out.println("ArithmeticException handeled");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException handeled");
} catch (Exception e) {
System.out.println("Exception=" + e.getClass().getName());
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
System.out.println("code execution completed");
}
package exception;
package exception;
package exception;
A finally block contains all the crucial statements that must be executed whether exception
occurs or not. The statements present in this block will always execute regardless of
whether exception occurs in try block or not such as closing a connection, stream etc.
package exception;
Finally will get executed even if there is exception in program and it is not handled.
package exception;
package exception;
package exception;
package exception;
checkEligibiltyProcess(9, 25);
}
}
package exception;
package exception;
import java.io.IOException;
void tset1() {
try {
tset2();
} catch (Exception e) {
System.out.println("exception handled");
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
}
void test3() {
try {
test2();
} catch (ArithmeticException e) {
System.out.println("ArithmeticException handled");
}
}
package exception;
class Example24 {
public static void main(String args[]) throws ArithmeticException {
Example23 obj = new Example23();
obj.method();
System.out.println("End Of Program");
}
}
package exception;
package customException;
import java.io.Serializable;
/**
*
*/
private static final long serialVersionUID = 1L;
DataException(String msg) {
super(msg);
}
package customException;
package customException;
import java.io.Serializable;
/**
*
*/
private static final long serialVersionUID = 1L;
DAOException(String msg) {
super(msg);
}
package customException;
INVALID_DATA,
INVALID_STATAE,
INVALID_CITY;
}
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
package customException;
Collections in Java
A Collection is a group of individual objects represented as a single unit. Java provides
Collection Framework which defines several classes and interfaces to represent a group of
objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two
main “root” interfaces of Java collection classes.
Java ArrayList class extends AbstractList class which implements List interface. The List
interface extends Collection and Iterable interfaces in hierarchical order.
• Ordered – Elements in arraylist preserve their ordering which is by default the order
in which they were added to the list.
• Index based – Elements can be randomly accessed using index positions. Index start
with '0'.
• Dynamic resizing – ArrayList grows dynamically when more elements needs to be
added than it’s current size.
• Non synchronized – ArrayList is not synchronized, by default. Programmer needs to
use synchronized keyword appropriately or simply use Vector class.
• Duplicates allowed – We can add duplicate elements in array list. It is not possible in
sets.
package arrayList;
import java.util.ArrayList;
}
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
Addition and removal of data from array list
package arrayList;
import java.util.ArrayList;
package arrayList;
import java.util.ArrayList;
import java.util.Iterator;
}
}
package arrayList;
import java.util.ArrayList;
list.addAll(list1);
System.out.println(list);
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
}
}
package arrayList;
import java.util.ArrayList;
list.clear();
System.out.println(list);
}
}
package arrayList;
@Override
public String toString() {
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
return "Student [age=" + age + ", name=" + name + ", school=" + school + "]";
}
package arrayList;
import java.util.ArrayList;
import java.util.List;
System.out.println(list);
}
ArrayList clone()
ArrayList clone() method is used to create a shallow copy of the list. In the new list, only
object references are copied.
If we change the object state inside first arraylist, then changed object state will be reflected
in cloned arraylist as well.
So cloning is about creating the copy of original object. Its dictionary meaning is : “make an
identical copy of“.
By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea
about the structure of class on which clone() method will be invoked.
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
So, JVM when called for cloning, do following things:
If the class has only primitive data type members then a completely new copy of the object
will be created and the reference to the new object copy will be returned.
If the class contains members of any class type then only the object references to those
members are copied and hence the member references in both the original object as well as
the cloned object refer to the same object.
Apart from above default behavior, you can always override this behavior and specify your
own. This is done using overriding clone() method.
1. First statement guarantees that cloned object will have separate memory address
assignment.
2. Second statement suggest that original and cloned objects should have same class
type, but it is not mandatory.
3. Third statement suggest that original and cloned objects should have be equal using
equals() method, but it is not mandatory.
Let’s understand Java clone with example. Our first class is Employee class with 3
attributes – id, name and department.
Shallow clone is “default implementation” in Java. In overridden clone method, if you are
not cloning all the object types (not primitives), then you are making a shallow copy.
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
package arrayList;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
package arrayList;
package arrayList;
package arrayList;
// Let change the department name in cloned object and we will verify in
// original object
cloned.getDepartment().setName("Finance");
System.out.println(original.getDepartment().getName());
System.out.println(cloned.getDepartment().getName());
}
}
Oops, cloned object changes are visible in original also. This way cloned objects can make
havoc in the system if allowed to do so. Anybody can come and clone your application
objects and do whatever he likes. Can we prevent this??
Answer is yes,
package arrayList;
package arrayList;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package arrayList;
// Let change the department name in cloned object and we will verify in
// original object
cloned.getDepartment().setName("Finance");
System.out.println(original.getDepartment().getName());
System.out.println(cloned.getDepartment().getName());
}
}
package arrayList;
import java.util.ArrayList;
list.contains("Test1");
}
package arrayList;
import java.util.ArrayList;
This method returns the index of the first occurrence of the specified element in this list. It
will return '-1'if the list does not contain the element.
package arrayList;
import java.util.ArrayList;
import java.util.Arrays;
firstIndex = list.indexOf("hello");
System.out.println(firstIndex);
}
}
This method returns the index of the last occurrence of the specified element in this list. It
will return '-1' if the list does not contain the element.
package arrayList;
import java.util.ArrayList;
import java.util.Arrays;
System.out.println(lastIndex);
lastIndex = list.lastIndexOf("hello");
System.out.println(lastIndex);
}
package arrayList;
import java.util.ArrayList;
System.out.println(list);
list.removeAll(list);
System.out.println(list);
}
}
package arrayList;
import java.util.ArrayList;
System.out.println(list);
list.removeAll(list1);
System.out.println(list);
}
ArrayList retainAll() retains only the elements in this list that are contained in the specified
method argument collection. Rest all elements are removed from the list. This method is
exact opposite to removeAll() method.
package arrayList;
import java.util.ArrayList;
System.out.println(list);
list.retainAll(list1);
System.out.println(list);
}
ArrayList replaceAll() retains only the elements in this list that are contained in the specified
method argument collection. Rest all elements are removed from the list. This method is
exact opposite to removeAll() method.
package arrayList;
import java.util.ArrayList;
import java.util.Collections;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
public class Example16 {
System.out.println(list);
Collections.replaceAll(list, "Test1","Test30");
System.out.println(list);
}
}
package arrayList;
package arrayList;
}
}
ArrayList sort()
package arrayList;
import java.util.ArrayList;
import java.util.Collections;
System.out.println("before sorting="+list);
Collections.sort(list);
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
System.out.println("After sorting="+list);
}
package arrayList;
import java.util.ArrayList;
import java.util.Collections;
Collections.sort(list);
Comparators are most useful when we want to sort a given list of objects – but not
in natural order.
package arrayList;
@Override
public String toString() {
return "State [population=" + population + ", district=" + district + ",
language=" + language + "]";
}
}
import java.util.Comparator;
@Override
public int compare(State o1, State o2) {
return o1.getLanguage().compareToIgnoreCase(o2.getLanguage());
}
}
package arrayList;
import java.util.Comparator;
@Override
public int compare(State o1, State o2) {
if (o1.getPopulation() == o2.getPopulation())
return 0;
else if (o1.getPopulation() > o2.getPopulation())
return 1;
else
return -1;
}
}
package arrayList;
import java.util.Comparator;
@Override
public int compare(State o1, State o2) {
return o1.getDistrict().compareTo(o2.getDistrict());
}
package arrayList;
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
list.sort(new PopulationSorter());
System.out.println(list);
//Collections.sort(list,new LanguageSorter());
//System.out.println(list);
list.sort(new LanguageSorter());
System.out.println(list);
Collections.sort(list,new DistrictSorter());
System.out.println(list);
ArrayList.subList() method
package arrayList;
import java.util.ArrayList;
import java.util.Arrays;
System.out.println(sublist);
}
package arrayList;
import java.util.ArrayList;
import java.util.Arrays;
list.add("A");
list.add("B");
list.add("C");
list.add("D");
System.out.println(Arrays.toString(array));
System.out.println(s);
}
}
}
package arrayList;
import java.util.ArrayList;
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list1.add("E");
list1.add("F");
list1.add("G");
list1.add("H");
list.addAll(list1);
System.out.println(list);
}
}
ArrayList clear()
ArrayList clear() method is used to removes all of the elements from the list. The list will be
empty after this call returns.
package arrayList;
import java.util.ArrayList;
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list1.add("E");
list1.add("F");
list1.add("G");
list1.add("H");
list.addAll(list1);
System.out.println(list);
list.clear();
System.out.println(list);
}
}
Java LinkedList class is doubly-linked list implementation of the List and Deque interfaces. It
implements all optional list operations, and permits all elements (including null).
LinkedList Features
• Doubly linked list implementation which implements List and Deque interfaces.
Therefore, It can also be used as a Queue, Deque or Stack.
• Permits all elements including duplicates and NULL.
• LinkedList maintains the insertion order of the elements.
• It is not synchronized. If multiple threads access a linked list concurrently, and at
least one of the threads modifies the list structurally, it must be synchronized
externally.
• Use Collections.synchronizedList(new LinkedList()) to get synchronized linkedlist.
• The iterators returned by this class are fail-fast and may throw
ConcurrentModificationException.
• It does not implement RandomAccess interface. So we can access elements in
sequential order only. It does not support accessing elements randomly.
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
• We can use ListIterator to iterate LinkedList elements.
LinkedList Methods
• boolean add(Object o) : appends the specified element to the end of a list.
• void add(int index, Object element) : inserts the specified element at the specified
position index in a list.
• void addFirst(Object o) : inserts the given element at the beginning of a list.
• void addLast(Object o) : appends the given element to the end of a list.
• int size() : returns the number of elements in a list
• boolean contains(Object o) : return true if the list contains a specified element, else
false.
• boolean remove(Object o) : removes the first occurence of the specified element in a
list.
• Object getFirst() : returns the first element in a list.
• Object getLast() : returns the last element in a list.
• int indexOf(Object o) : returns the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain specified element.
• lastIndexOf(Object o) : returns the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain specified element.
• Iterator iterator() : returns an iterator over the elements in this list in proper
sequence.
• Object[] toArray() : returns an array containing all of the elements in this list in
proper sequence.
• List subList(int fromIndex, int toIndex) : returns a view of the portion of this list
between the specified fromIndex (inclusive) and toIndex (exclusive).
package linkedList;
import java.util.LinkedList;
import java.util.ListIterator;
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
linkedList.add(4, "4A");
linkedList.add(5, "5A");
linkedList.addFirst("TT");
linkedList.addLast("LL");
System.out.println(linkedList);
package linkedList;
import java.util.LinkedList;
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
linkedList1.add("AA");
linkedList1.add("BB");
linkedList1.add("CC");
linkedList1.add("DD");
linkedList.addAll(linkedList1);
System.out.println(linkedList);
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
linkedList.addAll(1, linkedList1);
System.out.println(linkedList);
}
}
package linkedList;
import java.util.LinkedList;
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
System.out.println(linkedList.get(0));
System.out.println(linkedList.getFirst());
System.out.println(linkedList.getLast());
}
}
}
ArrayList vs LinkedList
Java HashSet
The important points about Java HashSet class are:
Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(int capacity) It is used to initialize the capacity of the hash set to the given
integer value capacity. The capacity grows automatically as
elements are added to the HashSet.
HashSet(int capacity, It is used to initialize the capacity of the hash set to the given
float loadFactor) integer value capacity and the specified load factor.
HashSet(Collection<? It is used to initialize the hash set by using the elements of the
extends E> c) collection c.
package setClass;
import java.util.HashSet;
import java.util.Iterator;
set.add("Test1");
set.add("Test2");
set.add("Test3");
set.add("Test4");
set.add("Test5");
Iterator<String> i = set.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
package setClass;
import java.util.HashSet;
import java.util.Iterator;
package setClass;
import java.util.HashSet;
package setClass;
int id;
String name, author, publisher;
int quantity;
package setClass;
import java.util.HashSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
Test1
Test40
Test20
Test3
Test2
=========
Test1
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
Test40
Test3
Test2
Test20
TreeSet
The important points about Java TreeSet class are:
package setClass;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.TreeSet;
Points to remember
• Java HashMap class contains values based on the key.
• Java HashMap class contains only unique keys.
• Java HashMap class may have one null key and multiple null values.
• Java HashMap class is non synchronized.
• Java HashMap class maintains no order.
package mapClass;
import java.util.HashMap;
}
Constructor In HashMap
Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map<? extends It is used to initialize the hash map by using the elements
K,? extends V> m) of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the
given integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of
loadFactor) the hash map by using its arguments.
package mapClass;
import java.util.HashMap;
import java.util.Map;
import java.util.HashMap;
System.out.println(map.get("Test1"));
}
}
package mapClass;
import java.util.HashMap;
System.out.println(map);
System.out.println("=========");
HashMap<String, String> map1 = new HashMap<>();
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
map1.put("Test5", "A1");
map1.put("Test6", "B1");
map1.put("Test7", "C1");
map1.put("Test8", "D1");
map.putAll(map1);
System.out.println(map);
}
}
package mapClass;
import java.util.HashMap;
/**
* Removes all of the mappings from this map. The map will be empty
* after this call returns.
*/
map.clear();
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*/
System.out.println(map.containsKey("Test1"));
/**
* value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
*/
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
System.out.println(map.containsValue("A"));
map.put("Test1", "A");
map.put("Test2", "B");
map.put("Test3", "C");
map.put("Test4", "D");
System.out.println(map.containsKey("Test1"));
System.out.println(map.containsValue("A"));
}
}
package mapClass;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/**
* @return a set view of the mappings contained in this map.
*/
Set<Entry<String, String>> entry = map.entrySet();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
*/
System.out.println(map.isEmpty());
/**
* Removes the mapping for the specified key from this map if present.
*/
map.remove("Test1");
map.replace("Test2", "Test1000");
System.out.println(map);
}
}
package mapClass;
import java.util.HashMap;
import java.util.Map;
System.out.println(map);
}
}
package mapClass;
map.put(1, s1);
map.put(2, s2);
map.put(3, s3);
System.out.println(map);
}
}
package mapClass;
import java.util.HashMap;
import java.util.Map;
map.put(null, "Test1");
map.put(null, "Test1");
map.put(null, "Test1");
By Bhanu Pratap Singh
https://www.youtube.com/user/MrBhanupratap29/playlists
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/seleniumbybhanu/
map.put(null, "Test1");
map.put(1, null);
map.put(2, null);
map.put(3, null);
map.put(4, null);
System.out.println(map);
}
}
Map Overview
There are 4 commonly used implementations of Map in Java SE - HashMap, TreeMap,
Hashtable and LinkedHashMap. If we use one sentence to describe each implementation, it
would be the following:
package mapClass;
import java.util.LinkedHashMap;
import java.util.TreeMap;
System.out.println(linkedHashMap);
treeMap.put(10, "Test1");
treeMap.put(11, "Test2");
treeMap.put(1000, "Test1");
treeMap.put(40, "Test4");
treeMap.put(20, "Test5");
System.out.println(treeMap);
}
}