Java
Java
We cannot store integer in byte but if we can contain byte into another byte value, here’s the
example.
class HelloWorld {
byte b = 10;
b = (byte) (b+1);
System.out.println(b);
Arithematic operator
String concatenation
If we are using + operator between 2 operands where one of the operands of the type
string the as the result both operands will merge with eachother.
The result of a string concatenation is also a string.
Example:-
"a" + b ="ab"
class HelloWorld {
int a = 10;
int b = 2;
Example-2
class HelloWorld {
String a = "abc";
int b = 10;
int c = 20;
int d = 30;
System.out.println( a + b + c + d);
System.out.println( b + a + c + d);
System.out.println( b + c + a + d);
System.out.println( b + c + d + a);
output- abc102030
10abc2030
30abc30
60abc
+ Operator is the only overloaded operator in java because in some case it acts as an
addition operator and in other case it as as a concatenation operator.
Example-
If we are using any arithematic operator between 2 variables x and y then the resultant
type will always be max(int, type of x, type of y).
b = b + 1 (we are considering b as x and 1 as y, b stands for byte and 1 stands as for int
so if we put the formula then, we get max(int, type of x and type of y) as int contains
more memory so the output will be in Int)
Relational operator
Relational operator is applicable for every primitive data type except boolean
Compound Assignment operator ( int x=10; x +=20; -> x = x+20;. Output will be
30)
Problem-1
Int a,b,c,d;
a=b-=c*=d/=2;
System.out.println(a+""+b+""+c+""+d);
output- -160,-180,200,10.
Equality Operator
class Test {
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = t1;
Test t4 = null;
System.out.println(t1 == t2); //False
System.out.println(t2 == t3);// False
System.out.println(t3 == t1); // False
System.out.println(t1 == null);// False
System.out.println(t4 == null); // True
}
}
Bitwise Operator (& | ^)
LOGICAL OPERATOR
Ternary operator( ? : )
Int x = ( 10 < 20) ? ((30 > 40) ? 50 :60)) = ((70<80) 90 : 100)); //output-60.
Condition
a) True
b) False
If condition is true then it will execute statement1.
If condition is false then it will execute statement 2.
Flow control
The order in which all the statements are executed is known as flow control and run time
is known as flow control.
Selection Statement
If-else
Syntax
If (condition) // true/false
{
Statement1; // if true
}
else {
statement2; // else false
}
class A {
public static void main(String[] args) {
if (true){
System.out.println("hi"); // true
}
if (false){
System.out.println("hi") // nothing
}
}
}
Example-2
class A {
public static void main(String[] args) {
if (true){
System.out.println("hi"); }
System.out.println("hiiii");
else {
System.out.println("heyy");
}
}
} // output will be compilation error because there is system.out.println in between
if and else. The condition says there should not be any other elements is between if
and else.
If we have only one statement inside if then no need to give curly braces.
class A {
public static void main(String[] args) {
if (true)
System.out.println("hi");
else
System.out.println("ryoiki");
}
}
If we are not providing any curly braces then only one statement is allowed, and
that statement should not be of declaritive type.
If(true); It is valid but has no use, it only declaires that it needed to stop there.
If else nested
class A
{
public static void main(String[] args) {
int age = 23;
if (age>=18 && age <23)
system.out.println("Focus on studies");
else if (age>27 && age<=32)
system.out.println("Get married");
else
System.out.println("no use of marriage");
}
}
Switch
switch(x)
{
case 1:
statement1:
break:
case 2:
statement2:
break;
default:
default statement;
break;
}
Allowed arguments
1.4v
Byte
Short
Int
Char
1.5v
Byte
Short
Integer
Character
Enum
1.7v
String
Switch(x)
{
Case 10:
System.out.println(10);
Break;
Case 20:
System.out.println(20);
Break;
Default:
System.out,println(“default”);
Break;
}
It is optional to mention case and default in switch.
switch(x){
}
If we are writing any statement inside switch it has to be under some case or default.
Curly braces are mandatory here.
Case label should be of constant expression. Example – case 10; but it can’t be case y.
because it contains variable which is not supposed to be there.
class HelloWorld {
public static void main(String[] args) {
int a = 10;
int b = 20;
switch(a)
{
case 10:
System.out.println(10);
break;
case 20:
System.out.println(20);
break;
default:
System.out.println("def");
break;
}
}
}
class HelloWorld {
public static void main(String[] args) {
byte b = 10;
switch(b)
{
case 10:
System.out.println(100);
break;
case 1000:
System.out.println(125);
break;
default:
System.out.println("def");
break;
}
}
}
Output will be compilation error, as we converting byte to int.
Duplicate case label is not allowed.
class HelloWorld {
public static void main(String[] args) {
int x = 97;
int y = 98;
switch(x){
case 97:
System.out.println(97);
break;
case 98:
System.out.println(98);
break;
case'a':
System.out.println(99);
break;
default:
System.out.println("def");
break;
}
}
}
If any case matches from that case onwards all the statements will be executed until
break or end of the switch, it is known as fall through inside switch.
class HelloWorld {
public static void main(String[] args) {
int x= 0;
int x= 1;
int x= 2;
int x= 3;
switch(x){
case 0:
System.out.println(0);
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
default:
System.out.println("default");
break;
}
}
}
Default
It is optional.
We can write default case atmost once.
It is not mandatory to write the default case as the last case.
class HelloWorld {
public static void main(String[] args) {
}
}
Initialization part
class HelloWorld {
public static void main(String[] args) {
int i = 0;
for(System.out.println("hii");i < 3; i++){
System.out.println("bye");
}
}
}
Output
Hii,bye,bye,bye.
Problem
for(int i = 0; ;i++){
System.out.println("bye");
}
Output – infinity bye, happened cuz we have not given any condition so the
compiler placed it true;
Updation part
All the three parts of for loop are optional and independent of each other.
Methods
Integer input – nextInt(),nextByte(), nextShort(),nextLong();
Decimal input – nextFloat(),nextDouble();
Boolean Input – nextBoolean()
String input – next(),nextLine()
Char input – nextLine(), charAt(0);
For string
public static void main(String[] args) {
System.out.println("Enter a string");
Scanner s = new Scanner(System.in);
String x = s.nextLine();
System.out.println(x);
s.close();
}
Write a program to find all the even and odd numbers from 0 to n numbers .
Write a program to find the sum of all the even and odd numbers from 0 to n
Write a program to check whether a number is prime or not.
Write a program to display all the prime numbers from 0 to n numbers
Write a program to find the sum of all prime numbers from 0 to n.
Whenever we are storing smaller data values into bigger data type then that process is
known as implicit type casting.
Implicit type casting will be done automatically by the compiler.
There will be no loss of data.
The other names for implicit type casting are
1. Upcasting
2. widening
class A{
public static void main(String[] args) {
int x = 100;
System.out.println(x);
double d = x;
System.out.println(d);
}
}
class A{
public static void main(String[] args) {
char x = 'a';
System.out.println(x);
double d = x;
System.out.println(d);
}
}
//Output will be 97.0
OOP’S CONCEPT
METHOD
Method is the set or block of code which is used to perform a particular task.
Syntax for method
Modifiers returnType methodName (parameter/arguments)
{
//body
}
Method Name
Method name always starts with lower case.
Example- mam(), concat(), append().
If a method name contains more than one word then method name always starts with
lower case but every inner word should start with uppercase known as camel’s rule.
Execution starts from the main method and ends from the main method.
There are two types of methods in java.
1-static method.
A method which is represented by static modifier is known as static method.
2-non-static method.
A method which is declared static known as non-static method.
If we want to print the codes present inside m1 method then we need to call that method.
Calling a method
It means go to that method, execute the codes present inside that method and come back.
Calling a static method
We can call a static method by the following ways.
1.directly
2.by object
3.by class name
Method argument
It is just like an input to a method.
Arguments of a method is optional.
There are two types of method argument
1.primitive data type
Public void m1(int x)
{
}
2.Non primitive data type
Public void m1(string x)
{
}
Calling a method with primitive data type as an argument
class Test{
public static void m1(int x) {
System.out.println(x);
System.out.println("hii");
}
class Test{
public static void m1(int x) {
System.out.println(x);
System.out.println("hii");
}
public static void m2(double d) {
System.out.println(d);
System.out.println("it's a double");
}
public static void m3(boolean b) {
System.out.println(b);
System.out.println("it's a boolean value");
}
We can call method with non primitive type as an argument by the following 2
ways
1.By passing of the same type as an argument
2.By using null as an argument
class Test{
public static void m1(String s) {
System.out.println("hii");
}
public static void main(String [] args){
m1("hey");
m1(new String());//possible ways for non primitive data types
m1(null);//possible ways for non primitive data types
}
}
Output- hii, hii,hii.
For object
class Test{
public static void m1(Test s) {
System.out.println("hii");
}
public static void main(String [] args){
m1(new Test());
m1(null);
}
}
Return type of a method
Void
If a method has return type as void then it doesn’t return any value when called.
class Test{
public static void m1() {
System.out.println("hii");
}
public static void main(String [] args){
m1();
}
}
class Test {
public static int m1() {
System.out.println("hii");
return 10;
}
}
}
Example
class A {
public static void main(String[] args) {
int x = 130;
byte b = (byte) x;
System.out.println(b);
m1(); //by directly
A t = new A ();
t.m1();//by object
System.out.println("hey");
}
}
A t = new A ();
t.m1();//by object
System.out.println("domain");
}
}
class A {
public static void main(String[] args) {
System.out.println("main starts");
m1();
System.out.println("main ends");
System.out.println("m1 starts");
m2();
System.out.println("m1 ends");
}
public static void m2(){
System.out.println("m2 starts");
System.out.println("m2 ends");
}
}
Output will be
2.directly
class Demo{
public static void main(String[] args) {
System.out.println(m1());
}
public static int m1() {
System.out.println("m1 method");
return 10;
}
} output will be – m1 method, 10.
By non-primitive
class Demo{
public static void main(String[] args) {
System.out.println(m1());
}
public static String m1() {
System.out.println("m1 method");
Return "hey";
}
}
Output will be – m1 method and hey.
If a method has non primitive data type then it returns null or object of that data type.
class Demo{
public static void main(String[] args) {
System.out.println(m1());
}
public static Test m1() {
System.out.println("m1 method");
return null;
}
}
Method signature
public void m1(int x) { // where method name(m1) and type of argument(int x) is the method
signature.
Inheritance(Is-A- Relationship)
Acquiring properties of one class by another class is known as inheritance.
Where property means Variables and methods.
This process involves minimum two classes.
Inheritance is represented by extends keyword.
The main advantage of inheritance is code reusability.
1.Parent class / super class/ Base class
2.Child Class / derived class / sub class
class Atom {
public void m1() {
System.out.println("hii");
}
}
}
}
Parent Class
The class whose property is acquired is known as Parent class.
Child Class
The class who acquires the property is known as child class.
Object class is the super most class in java means every class in java extends object
class either directly or indirectly.
If a class doesn’t extends any other class then that class is said to be direct child of
object
Class A{ direct child class of object class
}
Types of inheritance
1.Single Inheritance
2.Multiple Inheritance
3.multilevel inheritance
4.Hierarchial Inheritance
5.Hybrid Inheritance.
Single Inheritance
In single inheritance, there’s one parent and one children which extends the parent
class.
Multilevel inheritance
When a class is derived/child class of a class which itself is derived from another
class ,is known as Multi-Level Inheritance.
Hierarchial Inheritance
In Hierarchial inheritance there’s one parents class and multiple child classes
which extends the parent class.
Multiple inheritance
When one class extends more than one class then that type of inheritance is known as multiple
inheritance.
Class A{}
Class B{}
Class A
{
sopln(“a”)
Class B
Psvm()m{
c c = new c();
c.m1();
Method overloading
Creating multiple methods with same name but with different arguments known as method
overloading.
m1(int x )
m1(string s )
m1(boolean b )
m1(double d )
class A {
public void m1(float f){
System.out.println("hi");
}
public void m1(double d){
System.out.println("bye");
}
public static void main(String[] args) {
A a1 = new A();
a1.m1('a');
}
} output will be hi
class programming {
public static void main(String[] args) {
m1(10,10.5);
m1(10.5,10);
}
public static void m1(int i, double d){
System.out.println("hi");
}
public static void m1(double d,int i){
System.out.println("bye");
}
} output will be hi,bye
If there’s a relation between the arguments then the priority will be given to the child class.
A method which can be called by passing any number of arguments is known as var args.
public static void m1(int...x)// known as var arg method
We can call var arg method by passing any number of arguments including 0.
class A{
public static void main(String[] args) {
m1(5);
}
public static void m1(int...x){
System.out.println("var arg method");
}
}
Internally var arg method is converted into one dimensional array, wherever there is one
dimensional array it can be replaced with var arg method but vice versa is not true.
public static void main(String... args) { // we can use var args instead of []array.
Method over-riding
Changing the implementation of parent class method in a child class according to the
requirement of child is known as method over riding.
Known as initialization
}
class A{
public static void m1(){
}
}
class B extends A{
public static void m1(){
}
}
We can’t change the return type of method overriding, from 1.5v onwards co variant
concept came into picture.
If the method is overrriden then it will call the sub classs method again and again.
Co variant concept
According to this concept we can change the return type of method overriding.
This concept is not valid for primitive data types.
Co variant concept is applicable for non primitive data types but with some
restrictions.
Parent class method return type should be parent class of child class method
return type.
class A{
public Object m2(){
return null;
}
}
class B extends A{
public String m2(){
return null;
}
} // it is possible but vice versa is not possible
package
Package is the collection of classes and interfaces.
Import packagename.classname;
Modifiers
Modifiers are the reserved keywords using which a programmer can decide accessing
area or functionality of a class, method, variable or block.
In Java, modifiers are keywords that alter the behavior or attributes of a class, method,
variable or block.
1.Access Modifier
Public
If a class is public then we can access it within the package and outside the package
too but we have to make sure that we must import the class.
If a method is public then we can access it within the class, outside the class, within
the package and outside the package too.
If a variable is public then we can access it within the class, outside the class, within
the package, and outside the package too.
Protected modifier
If a method is declared as protected then we can access that method within a class,
outside a class, within same package as well as outside the package but only in child
class means only possible in inheritance.
Protected void m1(){
Default Modifier
If a method is default then we can only access within the same package but not
outside the package.
Void m1(){
Private modifier
If a method is declared as private then we can access that method within a class but
not outside the class.
Public>Protected>Default>private
While coming from parent to child class the scope of access modifier should increase
but shouldn’t decrease.
1.Final
Final variable
Final method
}
}
class Test extends Demo{
public void m1(){
}
}
Final class
If a class is declared as final, we can’t inherit that class that is we can’t create the
child class of that class.
All the methods present inside final class are by default final, variables may not be
final.
final class Demo{
}
class Test extends Demo{
Abstract Modifier
Abstract method
Child class is responsible for providing the implementation of abstract methods present in
parent class.
abstarct class experiment
{
abstarct void m1();
}
class B extends experiment{
public void m1(){
//implemented
}
}
Abstract Class
Abstract class can contain both abstract methods as well as concrete methods
abstract class experiment
{
abstract void m1(); // abstract method
public void m2(){
//concrete method
}
}
}
}
If child class not providing implementation for all the abstract method present in the parent
class then we have to declare child class as an abstract.
abstract class A{
abstract void m1();
public void m2(){
System.out.println("hii");
}
}
class B extends A{
public void m1(){
System.out.println("bye");
}
public static void main(String[] args) {
B b1 = new B();
b1.m1(); //bye
b1.m2();//hii
}
}
Static
It is the non access modifier which is applicable for methods and variable only.
Method hiding
Whenever we are declaring a static method in the child class which is already present in the
parent class where we will keep the method declaration same but by changing the
implementation is known as the process of method hiding.
class Tommy {
public static void m1(){
System.out.println("hii");
}
}
class VDY extends Tommy{
public static void m1(){
System.out.println("bye");
}
public static void main(String[] args) {
Tommy t = new Tommy();
t.m1(); // hii
VDY v = new VDY();
v.m1();// bye
Tommy m = new VDY();
m.m1();// hii the difference is here
}
}
In method hiding the method resolution takes place on the basis of object reference side and
compiler is responsible for the method resolution.
CONSTRUCTOR
WHENEVER WE CREATE AN OBJECT SOME PIECE OF CODE WILL BE EXECUTED
AUTOMATICALLY TO PERFORM INITIALIAZATION OF AN OBJECT, THAT PIECE OF
CODE IS NOTHING BUT CONSTRUCTOR.
Constructor is a special type of method which will be executed everytime whenever we
create an object to perform initialization of an object.
class eprogram {
Test(){
System.out.println("constructor");
}
public static void main(string[] args){
}
} // complie time error
//note- if we are creating a constructor with the name different from class name
then we will get compile error saying invalid method declaration
2.Return type concept is not applicable for constructor even void also.
If we provide return type to a constructor the compiler or jvm will not give any error and it will
be treated as a normal method.
class A{
void A(){
//IT IS NOT A CONSTRUCTOR IT IS A METHOD
}
}
class A {
A(){
System.out.println("const");
}
void A(){
System.out.println("method");
}
public static void main(String[] args) {
new A().A(); //OUT PUT WILL BE CONST AND THEN METHOD
}
}
3.All access modifier is applicable for constructor except non access modifier.
Q: What happens if a constructor is declared as private??
Ans: if we declare constructor as private then we cannot access constructor outside the class or
we restrict object creation inside any other class.
class Demo{
public static void main(String[] args) {
Test t = new Test();
}
}
class Test{
private Test(){
}
}
}
}
}
}
Case 1
The first statement inside constructor should be either super() (call to super) or this(), if we are
not writing any of these, compiler will place super() as the first statement.
class Demo{
Demo(){
System.out.println("hii");
}
}
Case-2
If we try to write super() anywhere except constructor then we will get compile error.
class Demo{
public static void m1(){
super();
System.out.println("hii"); //CE
}
}
Default Constructor
Difference
This,super
These are keywords.
These are used to refer current class or super class non static variable respectively.
These can be used anywhere expect static area.
These can be used any no time
this() , super()
class Demo{
int x = 10;
public static void main(String[] args) {
Test t = new Test();
t.m1();
}
}
class Test extends Demo{
int x = 100;
public void m1(){
System.out.println(this.x);//100
System.out.println(super.x);//10
}
}
Constructor overloading
Creating multiple constructor with same name but different arguments is known as constructor
overloading.
class A{
A(){
System.out.println("NO ARG CONST");
}
A(int x){
System.out.println("int arg const");
}
A(boolean b){
System.out.println("boolean arg const");
}
public static void main(String[] args) {
new A();//no arg const
new A(10);//int arg const
new A(true);//boolean arg const
}
}
Constructor chaining
We can achieve constructor chaining by the help of call to super() and call to this().
class A{
A(){
this(10);
System.out.println("NO ARG CONST");
}
A(int x){
this(true);
System.out.println("int arg const");
}
A(boolean b){
System.out.println("boolean arg const");
}
public static void main(String[] args) {
new A(); // boolean arg const, int arg const, no arg const
}
}
Super
class A{
A(int x){
class A{
A(){
ANS. No we can’t override a constructor neither we can inherit it and the main reason for this
is it will get confused thinking whether it is a method or constructor.
class A{
A(){
}
}
class B extends A{
A(){
//CE
}
}
}
}
class B extends A{
B(){
super(); // both B and A constructors are defaultly there
}
}
class A{
A(int x){
}
}
class B extends A{
B(){
super(); // CE
}
}
Reason why multiple inheritance is not allowed with the view of constructor
class A{
}
class B{
}
class C extends A,B{
C(){
super(); // the jvm will get confused
}
}
class Student {
String name;
System.out.println(s1.name);
System.out.println(s2.name);
} // abc,xyz
}
class Student {
String name;
int id;
Student(String name, int id){
this.name= name;
this.id = id;
}
Copy constructor
Factory method
It is a method which is called by a class name and when called it should return the object of
that class.
class Student{
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
Runtime r1 = Runtime.getRuntime();
System.out.println(r == r1);//true because there is no new object is created
}
}
Singleton class
For any java class if we are allowed to create only one object then that class is said to be
singleton class.
We can create our own singleton class by using the following ways
}
public static Test getTest(){
if(t == null) {
t = new Test();
}
return t;
}
public static void main(String[] args) {
Test t1= Test.getTest();
Test t2= Test.getTest();
}
}
Interface
Class B implements I{
}
{
}
One class can extends another class and can implement any of interfaces simultaneously.
Interface Demo{
Public static void main(…..){
Demo d = new Demo();
}
}
Interface variables
interface A{
int x = 10;
}
//-->public : we can access it from anywhere
//---> final : we can't change the value of variable
//--> static: It can't be local because variables of interface is by default public
//--> it can't be non static because we can't create object of interfce
Case1:
Final variable of interface must be initialized at the time of declaration.
interface A{
int x;//ce cuz it need to be initialized as we used final variable
}
interface A{
int x = 10;
}
class C implements A{
public static void main(String[] args) {
int x = 20;
System.out.println(x);// 20
}
}
Interface method
All the methods present inside interface are by default public and abstract
interface A{
void m1(); // by default public and abstarct are there
public void m2(); // by default abstarct is there
abstract void m3(); // by default public is there
public abstract void m4(); //true
}
interface A{
void m1();
void m2();
}
class B implements A{
public void m1(){
System.out.println("hii");
}
public void m2(){
System.out.println("bye");
}
public static void main(String[] args) {
B b = new B();
b.m1();
b.m2();
}
}
Case1
If 2 interfaces containing methods with same signature and same return type then in
implementation class, we need to provide implementation for only once.
interface A{
void m1();
}
interface B{
void m1();
}
class C implements A,B{ // this is possible
public void m1(){
System.out.println("hii");
}
interface A{
void m1();
}
interface B{
void m1();
}
class C implements A,B{ // but this ain't possible in the same class
public void m1(){
System.out.println("hii");
}
public void m1(){
System.out.println("hii");
}
Case-2
If two interfaces containing methods with same return type but different signature then in
implementation class we need to provide implementation for both methods separately and
these methods are known as overloaded methods.
interface A{
void m1();
}
interface B{
void m1(int x);
}
class C implements A,B{
public void m1(){
}
public void m1(){
}
}
If 2interfaces containing methods with same signature but different return type then it is
impossible to provide implementation.
interface A{
void m1();
}
interface B{
int m1();
}
class C implements A,B{
public void m1(){
}
public int m1() {
return 10; //CE
}
}
From 1.8v default and static method were allowed inside interface.
class Demo implements A{
public static void main(String[] args) {
Demo d = new Demo();
d.m1();
A a1 = new Demo();
a1.m1(); // both are possible outputs and output will be default method
which will be printed twice
}
}
interface A{
default void m1(){
System.out.println("default method");
}
}
}
}
interface A{
default void m2(){
this.m1();
}
private void m1(){
System.out.println("it is a private method");
}
}
Q- We can create constructor in every java class including abstract class but not inside
interface.
We cannot create constructor inside interface because as the by default the variable in interface
is final, we can’t over ride it and can’t reinitialize it.
Static block is a block which will be executed automatically before the execution of main
method.
class A{
static{
System.out.println("static block");
}
public static void main(String[] args) {
System.out.println("main block");
}
}
// static block, main block
If there is more than one static block is present then execution will start from top to
bottom.
class A {
static {
System.out.println("static block");
}
static {
System.out.println("hey");
}
}
// static block, hey ,main block
Q- Can we print any statement to the console without using main method.
Rules
Instance block is the block which will be executed whenever we create an object.
class Test{
{
System.out.println("Hiii");
}
public static void main(String[] args) {
Test t = new Test(); // Hiii, main
System.out.println("main");
}
}
By the help of object, we can call the instance or non-static block.
If more than one instance block is present then instance block will be executed from top to
bottom.
class Test{
Test(){
System.out.println("Hiii");
}
public static void main(String[] args) {
Test t = new Test(); // hii there, Hiii, main
System.out.println("main");
}
{
System.out.println("hi there");
}
}
If constructor and instance block is present then first instance block will be executed.
class A{
int i = 10;
{
m1();
System.out.println("fib");
}
A(){
System.out.println("const");
}
public static void main(String[] args) {
A a1 = new A();
System.out.println("main");
A a2 = new A();
}
public void m1(){
System.out.println(j); // 0,fib,sib,const,main,0,fib,sib,const,main 0
}
{
System.out.println("sib");
}
int j = 20;
}
class A{
static{
System.out.println("fsb");
}
{
System.out.println("fib");
}
A(){
System.out.println("const");
}
public static void main(String[] args) { // fsb,ssb,fib,sib,const,main,fib,sib,const
A a1 = new A();
System.out.println("MAIN");
A a2 = new A();
}
static{
System.out.println("ssb");
}
{
System.out.println("sib");
}
}
Converting from one type of object into another type of object is known as object type
casting.
Parent class reference can be used to hold it’s child class object(up casting).
object 0 = new String();
There must be some relation between C and A , otherwise we will get CE saying incompatible
types.
String s = new String("abc");
StringBuffer sb = (StringBuffer)s; //CE
‘C’ must be either same as ‘A’ or child class of ‘A’ otherwise we will get CE saying
incompatible types.
object o = new String();
String sb = (StringBuffer)o;
Step – 3(Runtime checking)
Runtime object of ‘d’ must be either same or child class of ‘c’ otherwise we will get Runtime
exception saying ClassCastException.
Integer i = new Integer(10);
Number n = (Number)i; //possible scenario
While object type casting no new object is created and the existing object will get a new
reference.
class Objtype {
void m1() {
System.out.println("a");
}
}
class E extends Objtype {
void m2() {
System.out.println("B");
}
Hiding our internal data in such a way that outside person should not access it, this is known as
data hiding.
Main advantage of data hiding is security.
class test{
private int x = 10;
public static void main(String[] args) {
}
}
We can access private variables outside the class with the help of getter and setter method.
Getter is used to get the value of a private variable and it is also known as accessor method.
Settor method is used to set the value of a private variable and it is known as mutator method.
Example
class A{
private int id;
public void setid(int id1){
this.id = id1;
}
public int getid(){
return id;
}
public static void main(String[] args) {
A a1 = new A();
a1.setid(101);
System.out.println(a1.getid()); //output will be 101
}
}
//declared the setter’s return type as void in setter so that it won’t return any value and
in getter we declared return statement so that it will return the value.
class A{
private int id;
public void setid(int id1){
this.id = id1;
}
public int getid(){
return id;
}
}
class B {
public static void main(String[] args) {
A a1 = new A();
a1.setid(101);
System.out.println(a1.getid()); //output will be 101
}
}
example
class abstractclass{
private double salary; //data hiding
getSalary() {
}
setSalary() {
}
}
Abstraction
Hiding our internal implementation and providing functionality to the user is known as
abstraction.
Advantages of abstraction
Security
Easy to use
Encapsulation
Wrapping or binding of data and the corresponding function in a single unit is known as
encapsulation.
Datavariables
Function Method
Every java class containing variable and methods, known as encapsulated class.
Types of encapsulation
Polymorphism
One name with many forms is known as polymorphism.
Poly Many morph forms
There are two types of polymorphism:
1.compile time polymorphism /static polymorphism/ early bonding
Consists of – method overloading, method hiding
2.Runtime polymorphism /dynamic polymorphism /late bonding
Consists of – method overriding.
Java.lang package
Topics we gonna cover inside java.lang package
Object class
Methods of object class
1.toString()
2.hashcode
3.equals()
4.finalize()
5..clone()
String class
StringBuffer
StringBuilder
Wrapper classes
Autoboxing and AutoUnboxing.
Every package is imported except java.lang package because by default it is
available in all java classes.
Object class
It is the supermost class in java because every class in java extends object
class either directly or indirectly.
A class is said to be direct child class of object class if it doesnn’t extend any
other class.
toString()
It is used to convert any object into string.
It’s the string representation of any object.
Syntax
public String toString(){
program
package com.abc;
public class Test {
public static void main(String[] args) {
Test t = new Test();
String str = t.toString();
System.out.println(s1);
System.out.println(t.toString());
}
}
// package com.abc;
public class program {
public static void main(String[] args) {
program t = new program();
System.out.println(t); //package@3c679bde
Whenever object class toString() method is called , output will always be in the
form of address.
class program{
String name;
program(String name){
this.name = name;
}
public static void main(String[] args) {
program p = new program("tushar");
System.out.println(p);//program@3c679bde
}
}
}
}
In string class, StringBuffer class, StringBuilder class, all wrapper classes and
collection classes, toString() is overridden to given the required output.
Hashcode
A unique number is generated by jvm for each and every object that number is known as
hashcode.
Syntax
class Test{
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.hashCode());// 1013423070
Test t2 = new Test();
System.out.println(t2.hashCode());// 428746855
}
}
Overriding hashcode
class program{
int roll;
program(int roll){
this.roll = roll;
}
public String toString(){
return roll+" ";
}
public int hashCode(){ //overriding hashcode
return roll;
}
public static void main(String[] args) {
program p = new program(12);
System.out.println(p); // 12
System.out.println(p.hashCode()); //12
}
}
program(int roll) {
this.roll = roll;
}
Obect class equals() is always used to compare the reference of the object.
If we want to compare the content of the objects then we need to override equals().
Syntax
To check content
class program {
int roll;
program(int roll) {
this.roll = roll;
}
public boolean equals(Object o){
int name1 = this.roll;
program s = (program)o;
int name2 = s.roll;
if(name1.equals(name2)){
return true;
}
else{
return false;
}
}
public static void main(String[] args) {
program p = new program(10);
program p1 = new program(10); //true
}
}
program(String roll) {
this.roll = roll;
}
public boolean equals(program pp){
return this.roll.equals(pp.roll);
}
public static void main(String[] args) {
program p = new program("abc");
program p1 = new program("abc");
System.out.println(p.equals(p1)); //true
}
}
Finalize method
1.
t2= null;
If an object is no longer required then assign null to it’s reference variable then that object will
become useless, this process Is known as nullifying the reference variable.
2.
If an object is no longer required then assign a new object to it’s reference variable then the old
object will become useless , this process is known as re assigning the reference variable.
If there is more than on thread then you can’t guess the output, it can be anything, depends
upon the thread.
finalization
class A{
public static void main(String[] args) {
A a = new A();
a = null;
System.gc();
System.out.println("The end");
}
public void finalize(){
System.out.println("end of finalize method"); // the end and end of finalize method
}
}
by String class
class A{
public static void main(String[] args) {
String s = new String();
s = null;
System.gc();
System.out.println("The end");
}
public void finalize(){
System.out.println("end of finalize method"); // the end and end of finalize
}
}
If we call finalize method on particular class object then the corresponding class finalize
method will be executed.
If we will call the finalize method , then it will not able to destroy the useless object but
when we use the garbage collector it is going to destroy the useless objects.
When we call finalize(), useless objects are not destroyed, it is only destroyed when
garbage collector calls finalize().
program
class Test{
public static void main(String[] args) {
Test t = new Test();
t.finalize();
t.finalize();
t =null;
System.gc();
System.out.println("end of main");
}
public void finalize(){
System.out.println("finalize method");
//output will be -finalize method will be printed twice , then end of main and again
finalize method
}
}
Java.lang.Stringclass
1.String class
2. stringBuffer class
3. stringBuilder class
Case-2
Case-3
In SCP area
In heap area
Whenever we create an object with the help of new keyword then two
object will be created in heap area, another in scp and that object
will have the reference in heap area.
String s = new String("abc");
System.out.println(s); // abc, by the helpof new keyword
rules
Object creation in scp area is optional , before creating new object
in SCP area first jvm goes scp area and checks whether an object with
the same content is present or not, if present no new object will be
created , if not then only a new object will be created.
class Test{
public static void main(String[] args) {
String s = new String("spring");
s.concat("fall");
s = s+"winter";
String s2 = s.concat("summer");
System.out.println(s);// springwinter
System.out.println(s2);//springwinter
}
}
Clone method
Cloneable()
class Test implements cloneable{
int x = 10;
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
Test t1 = (Test)t.clone();
System.out.println(t1.x);
System.out.println(t == t1);
}
} //10, 10
class Test{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abc");
String s = new String(sb);
System.out.println(s);
} //abc
11.compareTo()
class Test {
public static void main(String[] args) {
System.out.println("a".compareTo("b")); //-1
System.out.println("a".compareTo("a")); //0
System.out.println("A".compareTo("a")); //-32
foreach
class program {
public static void main(String[] args) {
String s = "abcd";
System.out.println(s);
char[]ch = s.toCharArray();
for(char x :ch){
System.out.println(x);// abcd
}
}
}
Split()
String s = "Tushar";
for (char c1 : s.toCharArray())
length++;
System.out.println("Length of String is : "+length);
}
}
Q2. Wap to find the no of words present inside a string.
public class program {
String s = "Tushar";
// String[] s1 = s.split("");
for (String x : s.split("x")) {
length++;
}
}
}
}
System.out.println("Length of String is : " );
}
}
Test(int x) {
this.x = x;
}
}
Final vs immutability
StrinBuffer
If the content will change frequently then never go for string object
because for every change it will create a new object internally.
Capacity = s.length()+16;
class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("abcd");
System.out.println(sb.capacity()); //20
}
}
Method of stringBuffer
}
}
}
}
Note - Every method is present inside stringBuffer is synchronized
means at a time only one thread allowed to operate stringBuffer
object.
StringBuilder
Wrapper classes
Wrapper class
Constructors
Int program
class Test {
public static void main(String[] args) {
Integer i = new Integer(10); // even tho it allows string but we still can't print
characters except numbers as parameter.
System.err.println(i); //float also takes up double as an argument, character only
takes up character/primitive as an constructor.
}
}
Boolean
If we are passing primitive type as an argument to the Boolean class
object, the only allowed arguments are true and false. Here it is
case sensitive.
allowed
1.valueOf()
2.xxxvalue()
3.parseXxxx()
4.toString()
1.valueOf()
This method is used to create wrapper class from the given primitive
and string.
Form-1
Public static wrapper valueOf (String s)
Form-2
2.XXXAValue
We can use this method to convert wrapper class object into it’s
corresponding primitive.
class program{
public static void main(String[] args) {
Integer I = new Integer(130);
System.out.println(I.byteValue());//-126
System.out.println(I.shortValue());//130
System.out.println(I.intValue());//130
System.out.println(I.longValue());//130
System.out.println(I.floatValue());//130.0
System.out.println(I.doubleValue());//130.0
}
}
charValue()
}
}
class program{
public static void main(String[] args) {
Character c = new Character('a');
char ch = c.charValue();
System.out.println(ch); //a
Boolean b = new Boolean(true);
boolean b1= b.booleanValue();
System.out.println(b1); //true
}
}
3.parseXxx()
Autoboxing
Integer x = 10;
Autounboxing
Automatic conversion of wrapper class object into it’s corresponding
to primitive data type by compiler is known as autounboxing.
Internally, autounboxing concept is implemented by using XxxValue().
Int x = I;
class program{
static Integer I = 10;//autoboxing
public static void main(String[] args) {
int i = I;//autounboxing
m1(i); //boxing
}
public static void m1(Integer K){
int x = k; //unboxing
System.out.println(x);
}
class HelloWorld {
public static void main(String[] args) {
Integer x = 10;
Integer y = x;
x++;
System.out.println(x); //11
System.out.println(y);//10
}
}
Multi dimensional array
Arrays of Array
S1 65 35 100 60
S2 42 60
S3 70 60 80
S4 10
S5 20
here [3] is the base size(first array size) and it will look like
this.
X [0,1,2];
To give the fixed value to an sub array we have to mention the value
in sub-array but if we don’t do then it will take the required sub
array length that it requires.
int [][]x = new int[3][];// sub array length which is not fixed.
x1 = new int[2][2]
Sopln(x[0]);
class program{
public static void main(String[] args) {
int[]x = new int[3];
System.out.println(x); // it will give the address
System.out.println(x[0]); //0
}
}
System.out.println(x);// address
System.out.println(x[0]); // address
System.out.println(x[0][0]); //0
If we are not satisfied with those default values then we can replace
with our customized value.
Defaultly
class program{
public static void main(String[] args) {
int[]x = new int[3];
System.out.println(x[0]); // 0
System.out.println(x[1]);//0
System.out.println(x[2]);//0
}
}
By assigning
class program{
public static void main(String[] args) {
int[]x = new int[3]; // known as creation
x[0] = 10;
x[1] = 20; // known as initialization
x[2] = 30;
System.out.println(x[0]); // 10
System.out.println(x[1]);//20
System.out.println(x[2]);//30
}
}
int [] x= {10,20,30};
length vs length()
length
length()
class program {
public static void main(String[] args) {
String[] s = {"a","aa","aaa"};
System.out.println(s.length); //3
System.out.println(s.length()); //CE
System.out.println(s[0].length);//CE
System.out.println(s[0].length());//1
}
}
Anonymous Array
example
class HelloWorld {
public static void main(String[] args) {
System.out.println(sum(new int[] {10,20,30}));
}
public static int sum(int [] x){
int total = 0;
for (int y:x)
total += y;
return total; // output will be 60
}
}
IN CASE OF PRIMITIVE ARRAYS AS ARRAY ELEMENENTS ANY TYPE IS ALLOWED
WHICH CAN BE PROMOTED TO DECLARED TYPE.
class HelloWorld {
public static void main(String[] args) {
int [] x = new int[5];
x[0]= 10; //valid
x[1] ='a'; //valid
byte b = 20;
x[2] = b; // valid
short s = 30;
x[3] = s; // valid
}
}
class HelloWorld {
public static void main(String[] args) {
Case – 2
class HelloWorld {
public static void main(String[] args) {
int [] a ={10,20,30};
int []b ={40,50};
a = b;
System.out.println(a[0]); //output will be 40
}
}
Exception
Exception Handling
For every thread jvm will create separate stack at the time of thread
creation.
Exception hierarchy
1.Lexical Error
MIStakes in keywords
2.syntax error
Grammatical Mistakes or syntactical mistakes.
3.semantic error
Providing operators in between in compatible types.
Errors are not caused by our program and these are due to lack of
resources and these are non recoverable.
1. Checked exception
2. Unchecked exception
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hi");
System.out.println(10/0);
System.out.println("bye"); //output will be only Hii
}
}
class A{
public static void main(String[] args) {
System.out.println("HII");
try{
System.out.println(10/0); // risky code should be inside of try block
}
catch(ArithmeticException e){
}
System.out.println("BYE"); // Hii and bye will be the output, we can also put any
required statement inside of catch block
}
}
Note
Case-1 (if there is no exception)
If there is no exception in try block then catch block will be
ignored.
class A{
public static void main(String[] args) {
try{
System.out.println("1");
System.out.println("2");
System.out.println("3");
}
catch(ArithmeticException e){
}
System.out.println("BYE"); //output will be 1,2,3,bye
}
}
class A{
public static void main(String[] args) {
try{
System.out.println("1");
System.out.println(10/0);
System.out.println("3");
}
catch(ArithmeticException e){
}
//output will be 1
}
}
class A{
public static void main(String[] args) {
try{
System.out.println("1");
System.out.println(10/0);
System.out.println("3");
}
catch(ArithmeticException e){
System.out.println("rYOIKI");
}
//1, RYOIKI
}
}
Note
If there is an exception rises in try block then rest of try
block won’t be executed irrespective of whether exception in
handled or not.
Case-4
If an exception rises at statement-4
class A{
public static void main(String[] args) {
try{
System.out.println("1");
System.out.println("2");
System.out.println("3");
}
catch(ArithmeticException e){
System.out.println("4");
}
//1,2,3
}
}
CATCH block will be ignored.
1.printStackTrace()
2. toString()
3. getMessage()
Example
class A {
public static void main(String[] args) {
try {
System.out.println(10 / 0);
} catch (Exception e) {
e.printStackTrace(); // will show the Name, description and Location
System.out.println(e.toString()); // will show the name and description
System.out.println(e.getMessage()); //only the description will be shown
}
}
}
Try with multiple catch block is allowed but order of catch block is
important.
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("hii");
} catch (Exception e) {
System.out.println("bye");
}
//Output will be -hii
}
}
Parent-child relationship
class A {
public static void main(String[] args) {
try {
System.out.println(10 / 0);
} catch (Exception e) {
System.out.println("hii");
} catch (ArithmeticException e) {
System.out.println("bye");
}
// unreachable
}
}
Finally Block
Case-1
If no exception rises
class A {
public static void main(String[] args) {
try {
System.out.println("try");
} catch (ArithmeticException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
//Output will be -hii, finally. catch block will be ignored
}
}
Case-2
try {
System.out.println("try");
System.out.println(10/0);
} catch (ArithmeticException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
//Output will be -hii,catch, finally
}
}
Case-3
try {
System.out.println("try");
System.out.println(10/0);
} catch (NullPointerException e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
//Output will be -hii,finally, exception
}
}
Return vs finally
} catch (NullPointerExceptionException e) {
System.out.println("CATCH");
} finally {
System.out.println("FINALLY"); // TRY, FINALLY , ERROR
}
}
}
try {
System.out.println("try");
System.out.println(10/0);
} catch (ArithmeticException e) {
System.out.println("CATCH");
System.exit(0); //TRY, CATCH
} finally {
System.out.println("FINALLY");
}
}
}
final
Finally
Finalize()
Throw keyword
Throws keyword
Drawbacks of array
1. Fixed in size
2. It contains only homogenous elements
3. No in built functions to perform operations to overcome this
problems collection framework came into picture.
Advantage of collection framework
1. Growable in nature
2. It contains heterogenous elements
3. It has inbuilt functions
Collection
List
Set
Queue
Boolean addAll(collection c)
It adds a group of elements at a time.
import java.util.ArrayList;
class A {
}
}
3.boolean remove(object o)
import java.util.ArrayList;
class A {
}
}
Boolean removeAll(collection c)
It will remove all the elements.
5.boolean retainAll(collection c)
class A {
}
}
6.void clear()
Removes all the elements
7.boolean contains()
import java.util.ArrayList;
class A {
}
}
8.boolean containsAll(collection c);
9.Boolean isEmpty()
import java.util.ArrayList;
class A {
}
}
10.int size()
Says about number of elements is present.
Import java.util.ArrayList;
class A {
}
}
11. toArray()
Converts it into array
import java.util.ArrayList;
class A {
}
}
12.Iterator iterator();
Cursor of java.
List
If we want to represent a group of individual objects as a
single entity where duplicates are allowed and insertion order
is preserved then we should go for list. index plays important
role in list.
List is the child interface of collection.
class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.add(2,"ddd");
System.out.println(l); //[10,aaa,ddd,bbb,ccc]
}
}
class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.add(2,"ddd");
System.out.println(l.get(3)); //[bbb]
}
}
class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.remove(1);
System.out.println(l); //[10,bbb,ccc]
}
}
import java.util.ArrayList;
class program{
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
l.set(1,"hi");
System.out.println(l); //[10,hi,bbb,ccc]
}
}
import java.util.ArrayList;
class program {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
System.out.println(l.indexOf("aaa")); // 1
}
}
Returns the index of an object.
ArrayList
Constructor
import java.util.ArrayList;
class program {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(10);
l.add("aaa");
l.add("bbb");
l.add("ccc");
System.out.println(l);
ArrayList li = new ArrayList(l);
li.add(10);
li.add(20);
System.out.println(li); //[10,aaa,bbb,ccc,10,20]
}
}
To check whether it is Serializable, Clonebale and RandomAccess
import java.io.Serializable;
import java.util.ArrayList;
import java.util.RandomAccess;
class oos{
public static void main(String[] args) {
ArrayList l = new ArrayList();
System.out.println(l instanceof Serializable); // true
System.out.println(l instanceof Cloneable); //true
System.out.println(l instanceof RandomAccess); //true
}
}
List li = Collections.synchronizedList(I);
Inon synchronized
li synchronized
Linked list
The first part/ starting part of a node is known as head and the last
part is known a tail.
class hi{
Node head;
Node tail;
int size;
Node createLL(int data){
Node node = new node();
node.value = data;
node.next=null;
head = node;
tail=node;
size = 1;
LinkedList methods
3.Object getFirst();
4. Object getLast();
5.Object removeFirst();
6.Object removeLast();
class program{
public static void main(String[] args) {
}
}
Vector
Constructor
class program{
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.capacity());
for(int i = 0; i<10;i++){
v.add(i);
}
System.out.println(v);
System.out.println(v.capacity());
v.add("aaa");
System.out.println(v.capacity());
}
}
Methods of vector
1. To add elements we have addElements (Object o)
2. To remove object we have removeElement(Object o);
3. To remove all the present object we have removeAllElement();
4. To remove object particular object then we have
removeElementAt(int index);
5. To get the object, we have
elementAt(int index);
firstElement();
lastElement();
6.other methods
Size();
Capacity();
Enumeration elements();
import java.util.*;
class oos2{
public static void main(String[] args) {
System.out.println(v.size());
System.out.println(v.capacity());
v.addElement("Hello");
v.addElement (100.3345);
v.addElement (null);
v.addElement (12300);
v.addElement('a');
v.add("home");
System.out.println(v);
System.out.println(v.removeElement(12300));
System.out.println(v);
v.removeElementAt(0);
System.out.println(v);
System.out.println(v.elementAt (1));
System.out.println(v.firstElement());
System.out.println(v.lastElement());
System.out.println(v.size());
System.out.println(v.capacity());
v.removeAllElements();
System.out.println();
}
}
Stack
Constructor
2. Object pop();
This method will be used to remove the top most object from the
stack.
3.Object peek();
This method will return the top most element from the stack without
removing .
4.boolean empty();
This method will return true if the stack is empty otherwise false.
}
}
Cursor of java
1.Enumeration
2.iterator
3.listIterator
Enumeration
If we want to get object one by one from any legacy class
(Vector and stack) then we will go for enumeration.
Declaration of elements()
Method of enumeration
}
System.out.println(v); // 1,2,3,4,5,6,7,8,9,10
Enumeration e = v.elements();
while(e.hasMoreElements()){
Integer i = (Integer)e.nextElement();
if(i %2 ==0){
System.out.println(i); // 2,4,6,8,10
}
}
}
}
Limitations of enumeration
1. Enumeration can be used to fetch one by one from the legacy class only.
2. In the enumeration we can perform only one activity that is read only
operation and we can’t perform operations like remove operation, this
iterator come into concept.
Iterator
By using iterator we can get object one by one from any collections implemented
class object.
By using the below format we can get object one by one any collection
implemented class object.
Syntax
Methods
Limitations of Iterator
By using iterator we can get, remove the object but we can’t perform the
operations like add or replace for this list iterator came into the
concept.
Both enumeration and iterator are unidirectional cursor which means it can
only move only in forward direction.
List iterator
It is the child interface of iterator.
If we want to get object one by one from any list interface implemented
class then we can go for list iterator.
It is only applicable for list interface.
This cursor is known as bi-directional cursor which means it can move in
both forward and backward direction.
If we want to get object one by one by using list Iterator then we will use
the below format.
Syantax
public ListIterator listIterator();
ArrayList i = new ArrayList();
ListIterator I = l.listIterator();
Methods
1.public Boolean hasNext();
2. public Object next();
3. public Boolean hasPrevious();
4. public void remove();
5. public void set(Object o);
6. public void add(Object new);
import java.util.ArrayList;
import java.util.ListIterator;
Set interface
If we want to represent a group of individual object as a single entity
where duplicates are not allowed and insertion order is not preserved then
we will go for set interface.
hasSet
the underlined data structure is hashtable.
Insertion order is not preserved.
Duplicates are not allowed.
Heterogenous elements can be inserted.
Null insertion is possible but only once.
If we try to insert duplicate elements then we will not get any kind of
compile time error or runtime exception.
Set don’t have any methods it will use the methods of collection interface.
Constructor
1. HashSet h = new HashSet();
It will create an empty HashSet object with the given Capacity and a fill
ratio of 0.75.
3. HashSet h = new HashSet(int initialCapacity, float fillratio);
4. HashSet h = new HashSet(Collection c);
import java.util.HashSet;
public class cls6{
public static void main(String[] args) {
HashSet h = new HashSet();
h.add("Tushar");
h.add("Sahoo");
System.out.println(h);
}
}
LinkedHashSet
LinkedHasSet
Program
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
public class A {
public static void main(String[] args) {
LinkedHashSet i = new LinkedHashSet();
i.add("Hello");
i.add("hii");
i.add("12");
i.add('a');
i.add("null");
i.add(false);
System.out.println(i); // hello,hii,12,a,null,false
}
}
Hashset
SortedSet
1.object first();
2.Object last();
Constructor of TreeSet
It will create an empty TreeSet Object where all the elements will be
inserted according to default natural sorting order (Ascending order).
import java.util.TreeSet;
import java.util.TreeSet;
System.out.println(t);
}
}
because in treeset null insertion is not possible and we know that while
performing any operation with null we will get NPE(NullPointerException
).
import java.util.TreeSet;
System.out.println(t);
}
}
As we know that in TreeSet all the elements will be inserted by using some
sorting order which means the objects will be compared with each other. And
we also know that for comparison we need same type of object(same class
type).
Map
Note
Program
Object put
import java.util.HashMap;
import java.util.HashMap;
Constructors of HashMap
It will create an empty HashMap object with default initial capacity of 16 and
default fill ratio of 0.75.
LinkedHashMap
HashMap
LinkedHashMap
}
}
Indentity HashMap
HashMap
In the case of HashMap JVM will always use equals() to identify duplicate
keys.
indentityHashMap
WeakHashMap
HashMap
In the case of normal HashMap an object isn’t eligible for GC if it became
useless, means no reference pointing towards it.
WeakHashMap
Method
1. Object firstKey();
2. Object lastKey();
3. SortedMap headMap(Object key);
4. SortedMap tailMap(Object key);
5. SortedMap subMap(Object key1, Object key);
TreeMap
Constructor
import java.util.TreeMap;
}
}
import java.util.TreeMap;
}
}
Generix
Possible way
import java.util.ArrayList;
public class mai {
public static void main(String[] args) {
ArrayList<String> i = new ArrayList(); // if we are using generix 0f string type then
it will show error if we try to insert anything except String Type
i.add("hii"); // hii, it is possible
}
}
Will not take any other input if we tryna insert different tpe of data type
except the given one in generix
import java.util.ArrayList;
}
}