Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Core-Java Material

Uploaded by

siva kick
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Core-Java Material

Uploaded by

siva kick
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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;

variable

int 10
value
the ID consists value id is 10
DitaType

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

reference Constructor

Product pYod=new Product();


keyword
class

Static variables:
B y using static key word to reference variable we can make variable as
static variable
Static int id=10;
.We call static method by using
ClassName.VariableName;

className.varaible
.Static variables are stored in method memory area

Local Variables:
.Wecan provide local variables inside method
Which are stored in Stack Area.

The Scope ofthe local variables within the method


NOTE::
I f instance variable name and local variable name is same it will first
preference to local variable
I f you still wants to call instance variable you to use this keyword
this.variableName
i f current class instance variable name and super class instance
variable name is same we have to use super keyword
super.variableName

Methods:

return Type
Access
mpdifier methodName

public String products({


return "Uniliver";

return Statement
T h e above method is instance method
For calling this method we need to create Instance or Object
override the private and final methods
we can't
Static methods:

If you are adding the static keyword to instance method, which static method.
We can static methods
Class Name.methodName();
we can't override static nmethods
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 Employeel);
It is two types
1) No argument constructor 2) argument constructor
b y default java will provide default zero argument constructor for every class
i f 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:
I f 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:

T o acquiring super class data into subclass


W e denotes inheritance with extends Keyword
I f you can create Object for subclass you can able to access all super classes data
I f you can create Object for super class you can able to access super class data
only.
I f 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) {
System.out.println("coconut");
public void parachute (String aloveraType, int aloveraCost)
System.out.println("alovera");
public void parachute(String hybuscus) {
System.out.println( "hybuscus");
public static void main(String[] args) {
Uniliver un=new Uniliver();
un.parachute(100, "cocnut");
un.parachute("alovera", 100) ;
un.parachute("hybuscus ");

Overriding:
Method name is same, parameter's also same but in different classes
override private, final and static methods.
we can't
For Example:

public class BillDesk


public void payment () {
System.out.println("BillDesk Payment");

public class CRED extends Billdesk


public void shopping() {
System.out.printIn("cred Shopping");
public void loans()
System.out.printIn("CRED loans ") ;
public Boolean cibilScore() {
System.out.printIn("cred
Boolean cibil=true;
Cibilscore");
return cibil;

public static void main (String[] args) {


CRED cr=new CRED0;
cr.shopping();
cr.loans ();
cr.cibilScore();
cr.payment();

public class HDFCLoans extends CRED


@Override
public void shopping() {
System.out. println("HDFC loans Shopping method ") ;

@Override
publicvoid loans()
System.out.println( "HDFC loans method");
Boolean cibiliscore=cibilScore();
if(cibiliScore)
Svstem.out.println("Approved
else {
loan");
System.out.println("you don't have suficient creditscore");

public static void main(String[] args) {


HDFCLoanss hl=new HDFCLoans(0;
hl.shopping()
hl.loans();
hl.cibilscore();
hl.payment();

Interface:

which hide the data, which is pure abstract class


we can provide implementation in child class only
w e can't create Object for interface
b y default methods are public and abstract, whether you declared or not
b y defaut variables are public static final
w e can write only abstract
methods(non-concrete
we can't write concrete methods
we can't write constructor
w e can't write instance blocks and static blocks

public interface PhonePay


String name=" Teja IT";
void booking() 5
public class RedBus implements PhonePay
@Override
publicSystem.out.println("this
void booking(0 is Red Bus booking");

public static void main(String[] args)


edBus rb=new RedBus ()
rb.booking()
System.out-println(PhonePay.name);

Abstract:

abstract is a keyword
by adding abstract keyword to class we can make class as abstract
we can provide implementation for the abstract class in child class only
i t 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 & Eror
t 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
B u t for providing catch block or finaly block try block is mandatory.

Exceptions are 2 types


1checked exceptions(Compile time)
2Jun Checked Exceptions{Runtime)

Checked Exceptions:

1) ArithmeticException
if you are divided somethingValue/0, you will get arithmetic exception
ex:

public void arithmatic() {


System.out.println("arithmatci start ")
try
int is100/05
}catch (ArithmeticException e) {
e.printstackTrace ():
System.out.println("arithmatci end ");
ArrayIndexoutofBounds Exception
I f you are trying to print more than arrasize value, you will get
this exception
public void arrayIndexOutofBounds Exception()
System.out.println("ArrayOut start ");
try
int[] id= {1,2,3,4)
System.out.println(id[5]D:
catch (ArrayIndex0utofBoundsException e) {
e.printstackTrace();

System.out.printIn("Array out end ");

Nul1PointerException:
public void nullpointer()
System.out.println("Nul1Pointer start ");
try {
Integer i=null;
int j-10
System.out.println(i+j);
catch (Nul1PointerException e)
e.printStackTrace ();
System.out.println("Nul1Pointer end ) ;

NumberformatException:
public void numberFormat Exception() {
System.out.println("number format start");
try
String id="teja";
Integer emp id=Integer. value0f(id);
System.out.println(emp_id);
}catch (NumberFormatException e) {
e.printstackTrace( )
System.out.println("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.

StackOverfiowError: it is child of Error class


public class Stack{
public void a() {
SVstem.out.println("this is AAA");
b()
public void b() {
System.out.println("this is BBB");

public void c() {


System.out.println("this is CCC");
a()
public static void main(String[] args) {
Stack s=new Stack);
s.a()

I n this case server will run continuously running, till fill the stack memory

How to create Custome Exception in Java?


B y Using throw new keywords

public class Amount {


int balance=100;
static int min_balance=250
public void balanceCheck () throws InsufficientBalaceException
if(balance>min_balance) {
System.out.println("please allow him/her")
else {
throw new InsufficientBalaceException( "balance is in-
sufficient");

public static void main(String[ ] args) {


Amount a=new Amount ();
try (
a.balanceCheck ();
catch (Insufficient8alaceException e)
e.printstackTrace());

public class InsufficientBalaceException extends Exception


public Insufficient8alaceException (String message) {
super(message);

Difference b/w thow, throws and Throwable?


with throw we can create our custome exception
w i t h 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()
i t is a Object class method, the garbage collector before calling un-usable objects it'll
call the finalizel) 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.

F o r 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;

I f you are not provided serialVesion UID will get not serializable exception
Static and transient variable's are not serailized

Clonable:

tis markerInterface
Which will use for to write the Clone();
Clonel) is copy of Object
When you are writing clonel), 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;
SObject is unusable Object
So, the garbage collector will call the unusable Object
I f we want call the externally the garbage collector, we need to use

System.gcl0
Garbage collector before collecting unusable Objects it will call the Object class
finalizel);
Access Modifiers:

Public, default{No access modifier), private, protected


Public:
w e 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):

w e can create default class, method and variable


w e can default data with in the package only, we can't access outside of the package

private:
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 com.AcessModifier;
public class A
protected int acsess id=10;
protected void shop() {
System.out.println("A class shop method");

public static void main(String[] args) {


A a=new A();
System.out.println(a. acsess_id);
a.shop()

package com.AcessModifier;
public class B
public static void main(String[] args)
A a=new A();
System.out.println (a.acsess_id);
a.shop()

package com. Tests


import com. AcessModi fier . A;
public class C extends A{
public static void main(String[] args) {
Ca=new C()%
System.out.printIn(a.acsess_id);
a.shop)

package com. Test


import com.AcessModifier.A;
public class D{
publicAstatic void main(String[] args)
a=new A();
XXXX error
a.shop() ;
SYstem.ut .println(a.acsess id); XXXXX error

Collection:
interface
Iterable class

implements
Collection extends

List Queue

PriorityQueue HashSet

ArrayList
LinkedHash Set
Deque

LinkedList ***

Vector SortedSet
Array Deque

Stack TreeSet

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 double
Arraylist implements to RandomAccess interface
Get method of arraylist directly gets the element on specific index
U s e 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 implementsto Random access
It is more preferable to add and remove the elements
Linkedlistis Asynchronous

Vector:

I t is working like Arraylist


I t ' 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 50%.

Stack:

It is First-In and Last-out


F o r adding element we need to use push()0
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, linked Hashset, 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:

i t doesn't maintain insertion order


i t allows to store one null value
for storing element internally uses Hashmap
i t implements to set interface

LiskedHashset:

>it maintain insertion order


i t allows one null
f o r storing elements internally it will use Linked Hash Map

Treeset:

i t follows sorting order


doesn't allow null values
internally uses TreeMap

Comparable Comparato
i t 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
CompareTol) Comparel)
>Java.lang java.util

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_ids
this.product_name = product_name;
this.cost = cost;

public static void main(String[] args) {


BirlaProducts bp=new BirlaProducts (1, "birlaIT", 200) ;
BirlaProducts bp1=new BirlaProducts(2, "ultra", 35e);
BirlaProducts bp2=new BirlaProducts(3, "pantaloons", 100);
ArrayList<BirlaProducts> l=new Arraylist<BirlaProducts2 ();
1.add(bp);
1.add(bp1);
1.add (bp2);
Collections.sort(1)
System.out.println(1);
@Override
public int compareTo(BirlaProducts o) {1
eturn this .product_name.compare To(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;

this.price price;
public int getProduct id() {
return product id;

public String getProdcut name( )


return prodcut_name;

public int getPrice() {


return price;

public void
static main(String[] args) (
Pidilite pi=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 ArrayListPidilite2();
al.add(p1);
al.add(p2);
al.add(p3);
al.add(p4);
Collections.sort (al, new
BasedOnPrice 0);
for (Pidilite p:al)
System.out.println(p-getPrice());

System.out.println();
Collections.sort (al,new BasedOnName() );
for (Pidilite p:al)
System.out.println(p.getProdcut_name());

public class BasedOnPrice implements Comparator<Pidilite>{


@Override
public int compare(Pidilite o1, Pidilite o2) {
return o1.price o2.price;
public class BasedonName implements Comparator<Pidilite>{
@Override
public int compare(Pidilite 01, Pidilite o2) {
return o1.prodcut_name.compareTo(o2.prodcut_name);

MAP::

Map Interface
intertace>>

ccinterface>
oTedMao

Hashtable HashmapP intertace>


avigabileMap

-implements TreeMap
extends LinkedHashMap

M a p is a interface
i t is combination of key, value pair
w e 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
i f you provide the duplicate key's it will override
i t allows one null key & many null values
n o t 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
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:
i f 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:
i t ' s similar like Hashmap, butitfollows insertion order

weakHashMap:
in map, garbage collector can't collect un-usable objects,
but in weakHash Map 8garbage 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 ConcurrentHas hMap<Integer, String2()


map.put(1, "Teja");
map.put(2, Teja")E.
map.put(1, "Chakry");
map.put(4, "Kranthi");
map.put(2, "Shiva");
map.put(S, "Chakry");
map.put (7, "sai")
IteratorcEntry«Integer, String>> en=map.entrySet().iterator ();
while(en. hasNext ()) t
Entry Integer, String> entry=en.next ();
SVstem.out.printIn(entry getkey ()+" "+entry.getvalue())
//or
for(Entry<Integer, String> ent:map.entryset ()) {
System.out.printIn(ent -getKey()+" "+ent.getvalue ());

HashTable:
i t is a legacy class
i t 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
i t not synchronized
but threadsafe
because, on each bucket at time 1 read thread and 1 write thread can be act
i s 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()
ifit is set, copyOnwriteArrayset()

Arraylist<Integer> al-new Arraylist<Integer2();


al.add(2);
al.add(5);
al.add(3)
al.add(10);
al.add(7)
object[] obj=al.toArray () ;// convert to array

for (0bjectt data:obj) {


System.out.println(data):
List<0bject> 1-Arrays.aslist(obj) ;// convert to Arraylist
for(0bject data:1)
System.out.println(data);

HashMap<Integer, String> map=new HashMap<Integer, String>();


Collections.synchronizedMap(map);//converting hashmap into synchronized
Collections.sort (al);//sorted
Collections.reverse(al);// reverse

collections.min(al);// find min number

Collections.max(al);// find max number

1/Unmodifieblelist
List Integer> 1=Collections.unmodifiablelist (list) ;
1.add(12); for(Integer i:1)(
System.out.println(i);

i f you don't want to modify the list data, then you can go with Collection.unmodifablelist()
s t i l l if you are trying to modify the list data you will get UnsupportedOperationException

You might also like