What is Java?
*Java is Programming language
*it is independent platform, which means it runs any plat form(Windows, linux,
macOS)
Project :
• Collection of Packages
Package:
• Collection of Classes
Class :
• Collection of Variables and methods
Data Types in JAVA:
Primitive Data Types:
byte
short
int
long
double
float
char
Boolean
String -> Objective Data Type
What is Variable?
• Which store the value
Example:
Int id=10;
Types of Variables:
Instance Variables:
• These will declare in class level
• Which are stored in Heap memory Area
• For instance variables we should create the Object or Instance
Static variables:
• By using static key word to reference variable we can make variable as
static variable
Static int id=10;
• We call static method by using
[Link];
• Static variables are stored in method memory area
Local Variables:
• We can provide local variables inside method
Which are stored in Stack Area.
• The Scope of the local variables within the method
NOTE::
• If instance variable name and local variable name is same it will first
preference to local variable
• If you still wants to call instance variable you to use this keyword
[Link]
• if current class instance variable name and super class instance variable
name is same we have to use super keyword
[Link]
Methods:
• The above method is instance method
• For calling this method we need to create Instance or Object
• we can’t override the private and final methods
Static methods:
• If you are adding the static keyword to instance method, which static method.
• We can static methods [Link]();
• we can’t override static methods
• which will stored in method area.
Note: method inside method we can’t write.
Constructor:
• constructor is for initializing the data.
in Object it contains constructor.
Employee ee=new Employee();
• It is two types
1. No argument constructor 2) argument constructor
• by default java will provide default zero argument constructor for every class
• if we provide argument constructor in class, the default constructor will be
override,
if you still want zero argument constructor you have to provide manually.
Encapsulation:
• Encapsulation means protected the data in a class
• By creating private properties and public setters and getters methods.
Example:
• If you are taking accountholder details, accountholder can able to check all his data
including balance, but for others we need to show name, IFSC, account number, but
not he balance
Here we are making properties as private and protecting the data.
Inheritance:
• To acquiring super class data into subclass
• We denotes inheritance with extends Keyword
• If you can create Object for subclass you can able to access all super classes data
• If you can create Object for super class you can able to access super class data only.
• If you can create super class reference and subclass Object you can ‘t access
subclass specific methods.(Optional point either explain or not no problem)
• Final and private classes we can’t inherited
• Class to class A extends B
• Class to interface Redbus implements Phonepay
• Interface to class (Not possible)
Polymorphism:
• Poly means many, morphism mean changes
• One things in different forms
It is two types.
1. Compile time polymorphism(Method overloading)
2. Run time polymorphism(Method overriding)
Method Overloading:
• Method name is same, parameters list are different in same class
• Either number of parameters list are different, or data types are different or order
of parameters are different
For example:
public class Uniliver {
public void parachute(int coconutCost,String name) {
[Link]("coconut");
}
public void parachute(String aloveraType,int aloveraCost) {
[Link]("alovera");
}
public void parachute(String hybuscus) {
[Link]("hybuscus");
}
public static void main(String[] args) {
Uniliver un=new Uniliver();
[Link](100,"cocnut");
[Link]("alovera",100);
[Link]("hybuscus");
}
}
Overriding:
• Method name is same, parameter’s also same but in different classes
• we can’t override private, final and static methods.
For Example:
public class BillDesk {
public void payment() {
[Link]("BillDesk Payment");
}
}
public class CRED extends BillDesk{
public void shopping() {
[Link]("cred Shopping");
}
public void loans() {
[Link]("CRED loans");
}
public Boolean cibilScore() {
[Link]("cred Cibilscore");
Boolean cibil=true;
return cibil;
}
public static void main(String[] args) {
CRED cr=new CRED();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
public class HDFCLoans extends CRED{
@Override
public void shopping() {
[Link]("HDFC loans Shopping method");
}
@Override
public void loans() {
[Link]("HDFC loans method");
Boolean cibiliScore=cibilScore();
if(cibiliScore) {
[Link]("Approved loan");
}else {
[Link]("you don't have suficient creditScore");
}
}
public static void main(String[] args) {
HDFCLoans hl=new HDFCLoans();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Interface:
• which hide the data, which is pure abstract class
• we can provide implementation in child class only
• we can’t create Object for interface
• by default methods are public and abstract, whether you declared or not
• by default variables are public static final
• we can write only abstract methods(non-concrete)
• we can’t write concrete methods
• we can’t write constructor
• we can’t write instance blocks and static blocks
public interface PhonePay {
String name="Teja IT";
void booking();
}
public class RedBus implements PhonePay {
@Override
public void booking() {
[Link]("this is Red Bus booking");
}
public static void main(String[] args) {
RedBus rb=new RedBus();
[Link]();
[Link]([Link]);
}
}
Abstract:
• abstract is a keyword
• by adding abstract keyword to class we can make class as abstract
• it’s shows only necessary data, and hide unnessaray data
• we cant create objcect for abtract class.
• we can provide implementation for the abstract class in child class only
• it allows abstract methods and non-abstract methods
• it allows instance blocks and static blocks
• we can create constructor for abstract class
Exception Handling:
• Exception is a class, which is child class of Throwable
• Throwable contains child classes Exception & Error
• It disturbs the normal execution flow of the programme
• We can handle the exceptions by using try, catch blocks
Or by using throws keyword
• One try block may contain multiple catch blocks and one finally block
• But for providing catch block or finally block try block is mandatory.
• Exceptions are 2 types
1)checked exceptions(Compile time)
2)un Checked Exceptions(Runtime )
Checked Exceptions:
1) ArithmeticException:
if you are divided somethingValue/0, you will get arithmetic exception
ex:
public void arithmatic() {
[Link]("arithmatci start ");
try {
int i=100/0;
}catch (ArithmeticException e) {
[Link]();
}
[Link]("arithmatci end ");
}
ArrayIndexOutOfBoundsException
• If you are trying to print more than arrasize value, you will get
this exception
public void arrayIndexOutOfBoundsException() {
[Link]("ArrayOut start ");
try {
int[] id= {1,2,3,4};
[Link](id[5]);
}catch (ArrayIndexOutOfBoundsException e) {
[Link]();
}
[Link]("Array out end ");
}
• NullPointerException:
public void nullpointer() {
[Link]("NullPointer start ");
try {
Integer i=null;
int j=10;
[Link](i+j);
}catch (NullPointerException e) {
[Link]();
}
[Link]("NullPointer end ");
}
• NumberFormatException:
public void numberFormatException() {
[Link]("number format start");
try {
String id="teja";
Integer emp_id=[Link](id);
[Link](emp_id);
}catch (NumberFormatException e) {
[Link]();
}
[Link]("number format end");
}
• CloneNotSupportedException:
When you are write clone(), which is for Object Copy, then if that class is not implemented to
Clonable interface will get CloneNotSupportedException
• NotSerializableException:
if while serialization if you not provided serialversionUID the serializable implemented
class, you will get this exception.
StackOverflowError: it is child of Error class
public class Stack {
public void a() {
[Link]("this is AAA");
b();
}
public void b() {
[Link]("this is BBB");
c();
}
public void c() {
[Link]("this is CCC");
a();
}
public static void main(String[] args) {
Stack s=new Stack();
s.a();
}
}
•
In this case server will run continuously running, till fill the stack memory
How to create Custome Exception in Java?
• By Using throw new keywords
public class Amount {
int balance=100;
static int min_balance=250;
public void balanceCheck() throws InsufficientBalaceException {
if(balance>min_balance) {
[Link]("please allow him/her");
}else {
throw new InsufficientBalaceException("balance is
in- sufficient");
}
}
public static void main(String[] args) {
Amount a=new Amount();
try {
[Link]();
} catch (InsufficientBalaceException e) {
[Link]();
}
}
}
public class InsufficientBalaceException extends Exception {
public InsufficientBalaceException(String message) {
super(message);
}
}
Difference b/w thow, throws and Throwable?
• with throw we can create our custome exception
• with throws we can do the declaration of the exception
• Throwble is super class of all exception classes.
Difference b/w final, finally, finalize?
• Final is a keyword
• Final class we can’t extend
• Final method we can’t override
• Final variable we can’t re-initialize
Finally:
• Finally is block, which we can use wether we getting exception or not if you wants to print
some data we can provide the data inside of finally block
Finalize():
• it is a Object class method, the garbage collector before calling un-usable objects it’ll call
the finalize() method
What is marker interface?
• Which interface doesn’t contain any methods, is called marker interface
1)serializabele 2)clonable 3)remote
Note: the functionality will take care by JVM
Serialization & de serialization:
Object code converting into byteCode is called serialization
Converting byteCode to ObjectCode is called de-serialization.
• For that we need to implement serializable interface to class
• While deserialization the data has a chances to modify, for that we need to maintain
serialVersionUID
private static final long serialVersionUID =6849794470754667710L;
• If you are not provided serialVesionUID will get not serializable exception
• Static and transient variable’s are not serailized
Clonable:
• It is marker Interface
• Which will use for to write the Clone();
• Clone() is copy of Object
• When you are writing clone(), the class should be implements to Clonable interface otherwise
will get ClonNotSupportedException
Garabge Collector:
• Garbage collector will call the unusable Objects
String s=null;
String s1=”Teja IT”;
String s2=s1;
• S Object is unusable Object
• So, the garbage collector will call the unusable Object
• If we want call the externally the garbage collector, we need to use
[Link]();
• Garbage collector before collecting unusable Objects it will call the Object class finalize();
Access Modifiers:
• Public, default(No access modifier), private, protected
Public:
• we can create public class, method and variable
• we can access anywhere public access modifier data in project, within the class package and
outside packages also
default(No access modifier):
• we can create default class, method and variable
• we can default data with in the package only , we can’t access outside of the package
private :
• we can’t create class with private access modifier
• private class we can’t extend
• private method we can’t override
• private variable we can’t out side of the class
protected:
•we can’t create class with protected access modifier
•we can access protected data, within the class, within the package and outside package in
subclass
package [Link];
public class A {
protected int acsess_id=10;
protected void shop() {
[Link]("A class shop method");
}
public static void main(String[] args) {
A a=new A();
[Link](a.acsess_id);
[Link]();
}
}
package [Link];
public class B {
public static void main(String[] args) {
A a=new A();
[Link](a.acsess_id);
[Link]();
}
}
package [Link];
import [Link].A;
public class C extends A{
public static void main(String[] args) {
C a=new C();
[Link](a.acsess_id);
[Link]();
}
}
package [Link];
import [Link].A;
public class D{
public static void main(String[] args) {
A a=new A();
[Link](); XXXX error
[Link](a.acsess_id); XXXXX error
}
}
Collection:
ArrayList:
• ArrayList is a class , which is child class of List interface
• ArrayList is index based structure in Java
• Arraylist is re-sizable array
• ArrayList initial capacity is 10
• Arraylist size is increased to 50%
• Arraylist implements to RandomAccess interface
• Get method of arraylist directly gets the element on specific index
• Use arraylist when get operations is more frequent than add and remove operations
• Arraylist is Asynchrounous
LinkedList:
• Linked datastructure is Node
• New node will create for storing new element
• Initial capacity Zero
• For storing every element node will create
• Linked list doesn’t implements to Random access
• It is more preferable to add and remove the elements
• Linkedlist is Asynchronous
Vector:
• It is working like Arraylist
• It’s slower operation than Arraylist
• Here we iterate the data with enumerator
• It is legacy class
• And synchronized
• Intial capacity 10, the size will be increase double.
Stack:
• It is First-In and Last-out
• For adding element we need to use push()
• Removing the element we need to use pop()
• To know the which element needs to be remove use peek()
List Set
• Maintain insertion order doesn’t maintain insertion order
• List allows duplicate values don’t allow duplicate values
• Allow many null values it adds only one null value
• Get method allow list, to get the value don’t support get()
From specific index
• Araylist, linkedlist, vector are the childs Hashset, linkedHashset, treeset are child
• We can iterate the data with listiterator it works with iterator only
Also
• List are re-sizable array it internally follows map datastrcture
Hashset:
• it doesn’t maintain insertion order
• it allows to store one null value
• for storing element internally uses Hashmap
• it implements to set interface
LiskedHashset:
• it maintain insertion order
• it allows one null
• for storing elements internally it will use LinkedHashMap
Treeset:
• it follows sorting order
• doesn’t allow null values
• internally uses TreeMap
Comparable Comparator
• it used to compare instances of same compare instances same or different
class class
• which is for natural sorting order which is for customize sorting order
• comparable implements by default > we need to implement externally
all wrapper classes, String Integer,Long
Date etc.,
• Original class must implements class itself implements Comparator
Comparable or any other class can implements
• Provide sorting one criteria only it provides sorting many criteria’s
• CompareTo() Compare()
• [Link] [Link]
Comparable Example:
public class BirlaProducts implements Comparable<BirlaProducts>{
private int product_id;
private String product_name;
private long cost;
public BirlaProducts(int product_id, String product_name, long cost) {
super();
this.product_id = product_id;
this.product_name = product_name;
[Link] = cost;
}
public static void main(String[] args) {
BirlaProducts bp=new BirlaProducts(1,"birlaIT",200);
BirlaProducts bp1=new BirlaProducts(2,"ultra",350);
BirlaProducts bp2=new BirlaProducts(3,"pantaloons",100);
ArrayList<BirlaProducts> l=new ArrayList<BirlaProducts>();
[Link](bp);
[Link](bp1);
[Link](bp2);
[Link](l);
[Link](l);
}
@Override
public int compareTo(BirlaProducts o) {
return this.product_name.compareTo(o.product_name);
}
}
Comparator Example:
public class Pidilite{
int product_id;
String prodcut_name;
int price;
public Pidilite(int product_id, String prodcut_name, int price) {
super();
this.product_id = product_id;
this.prodcut_name = prodcut_name;
[Link] = price;
}
public int getProduct_id() {
return product_id;
}
public String getProdcut_name() {
return prodcut_name;
}
public int getPrice() {
return price;
}
public static void main(String[] args) {
Pidilite p1=new Pidilite(1, "m-seal", 35);
Pidilite p2=new Pidilite(2, "fevistick", 15);
Pidilite p3=new Pidilite(3, "fevicol", 40);
Pidilite p4=new Pidilite(4, "fevikwick", 10);
ArrayList<Pidilite> al=new ArrayList<Pidilite>();
[Link](p1);
[Link](p2);
[Link](p3);
[Link](p4);
[Link](al, new BasedOnPrice());
for(Pidilite p:al) {
[Link]([Link]());
}
[Link]();
[Link](al,new BasedOnName());
for(Pidilite p:al) {
[Link](p.getProdcut_name());
}
}}
public class BasedOnPrice implements Comparator<Pidilite>{
@Override
public int compare(Pidilite o1, Pidilite o2) {
return [Link] - [Link];
}
}
public class BasedOnName implements Comparator<Pidilite>{
@Override
public int compare(Pidilite o1, Pidilite o2) {
return o1.prodcut_name.compareTo(o2.prodcut_name);
}}
MAP::
• Map is a interface
• it is combination of key, value pair
• we can call key, value pair is an entity
• key is Object and value also a Object
HashMap:
• HashMap is a class
• which implements to map interface
• it doesn’t follow any insertion order
• the values will stored in Hash buckets
• it doesn’t allow duplicate keys, values may be duplicate
• if you provide the duplicate key’s it will override
• it allows one null key & many null values
• not legacy class, Asynchronous
Internal working:
• the data will be stored in Hash bucket
• the default size of hashmap is 16
• based hashing technique values will be stored in hashbucked
hashcode/load factor(0.75)=hash busket
• while storing the value it will compare the hashcode(), and compare with .equals()
if value is present in hashbucket, it will override
• the null key Object will stored Zero th hashbucket.
Hashing Collision:
• if two different objects contain same hashcode then both will be stored in same bucket
this nothing but Hashing collision, we can achieve this problem by using quadratic
algorithm.
Linked HashMap:
• it’s similar like Hashmap, but it follows insertion order
weakHashMap:
• in map, garbage collector can’t collect un-usable objects,
but in weakHashMap garbage collector can able to collect un-usable Objects.
• Remaining functionality working like HashMap Only.
How to iterate the Map Data?
Map<Integer, String> map=new ConcurrentHashMap<Integer, String>();
[Link](1, "Teja");
[Link](2, "Teja");
[Link](1, "Chakry");
[Link](4, "Kranthi");
[Link](2, "Shiva");
[Link](5, "Chakry");
[Link](7, "sai");
Iterator<Entry<Integer, String>> en=[Link]().iterator();
while([Link]()) {
Entry<Integer, String> entry=[Link]();
[Link]([Link]()+" "+[Link]());
}
//or
for(Entry<Integer, String> ent:[Link]())
{
[Link]([Link]()+" "+[Link]());
}
HashTable:
• it is a legacy class
• it doesn’t allow null key or null value
• it extends to Dictionary class
• it is Synchronized
• it is threadsafe
Concurrent HashMap:
• it is a class
• we can say it is a combination of HashMap and Hashtable
• it not synchronized
• but threadsafe
• because, on each bucket at time 1 read thread and 1 write thread can be act
• is it is threadsafe and synchronized
Concurrent modification Exception:
• while iterating the list object, if you are trying to add the element you will get concurrent
modification exception
• to overcome this problem,
if it is mapdata, need to take ConcurrentHashMap() Object
if it is list, copyOnWriteArraylist()
if it is set, copyOnwriteArraySet()
ArrayList<Integer> al=new ArrayList<Integer>();
[Link](2);
[Link](5);
[Link](3);
[Link](10);
[Link](7);
Object[] obj=[Link]();// convert to array
for(Object data:obj) {
[Link](data);
}
List<Object> l=[Link](obj);// convert to Arraylist
for(Object data:l) {
[Link](data);
}
HashMap<Integer, String> map=new HashMap<Integer, String>();
[Link](map);//converting hashmap into
synchronized
[Link](al);//sorted
[Link](al);// reverse
[Link](al);// find min number
[Link](al);// find max number
//UnmodifiebleList
List<Integer> l=[Link](list);
[Link](12); for(Integer i:l){
[Link](i);
}
• if you don’t want to modify the list data, then you can go with [Link]()
• still if you are trying to modify the list data you will get UnsupportedOperationException