Ads

Java Notes and Interview questions(Java 8 included)

 main method:(public static void main(String[] args):

  • JVM always focus on Main method

  • Execution starts from main method

  • We can Overload but cant override the main method

  • Overloading like String[],int[],String args…Basically main method is static method so it cant be overriden in subclass..Static method only belongs to class rather than instance of the class.

Data Types:

Primitive data types: int,float,double,long

Wrapper classes: Integer,Long,Double,Float

Constructor:

  • is a block of code which initialises the newly created object

  • is a block of code which gets executed when object is created

  • classname===constructor name

  • no return type,non static

  • cant be abstract,static,final

  • Types:

    • Default

    • Parameterised

    • Non parameterised

  • Default: When not mentioned,java will provide the default one

  • Parameterised: Can have Arguments like String, Integer,Float,Object,any Classes

    • Can be overloaded(Based on parameters choosing the behaviour called Constructor overloading) multple constructors with same name but with different arguments types or order)

    • Cant be overridden (Since constructors are not inherited, they cannot be overridden.)

    • super keyword can be used in inheritance

  • Loops&conditional statements:

    • if Loop-if condition true,if block execute)

    • if else->if condition false else block execute

    • switch-->

    • for loop--initialisation,condition,increment/decre

    • while-->initialisation separate,condition,increment/decre last(Entry check)

    • do while--->execute first--->increament/decr--->condition*(Exit check)

  • Static:

    • Can be used in Block,Variable,Class,methods

    • no need to create object,can be refered like ClassName.variable or method name()

    • Static block:

      • gets executed when the class is loaded in the memory

    • Static variable:

      • Can be referred using instance of the class

    • Static class:

      • only possible in nested class

    • Static method:

      • Can be referred using instance of the class

Inheritance:

process of acquiring the properties of another class

  • Single Inheritance-->A extends B

  • MultiLevel-->A-->B,B-->C,C--->D

  • Multiple: Not possible ,can be achieve through Interface

  • Hierical-->A Extends B, A Extends C,A Extends D

Access Modifier

same class

same package

subclass

other package

Public

Y

Y

Y

Y

private

Y

N

N

N

Protected

Y

Y

Y

N

Polymorphism:

is the capability of a method to do different things based on the object that is acting upon it.

Types:

  • Static/compile/Early Binding(Method Overloading):

    • Same method name,Different Arguments or change in order of arguments

    • Done in the same class

  • Dynamic/Run time/Late Binding(Method OverRiding):

    • when not satisfied with parent class implementation ,we can modify it by overriding it

    • Happens in Another class

    • Same method name,same arguments or same order of arguments

    • Should return same return type or covariant Return

    • Should throw same exception or covariant Exception\

Aspects

Method overloading

Method Overriding

Method name

should be same

Should be same

arguments

should not be same,should have different data types or different orders

Same arguments

Return type

anything

same or covariant return

Exception

can be anything

Same or covariant Exception

Access modifier

can be anything

should be equal or higher

Private methods

Can be overloaded

Cant be overridden

Abstraction:

  • hiding the implementation details.

  • If class having one abstract method,then entire class should abstract class

  • in this case,cant create object

  • if a child class doesnt implements all methods of parent class,then child class also declared as abstract class

Interface:

  • Always public static final by default

  • dont have implentation

  • cant create object, can be referred to the class by implements keyword

  • One interface can extends other interfaces

  • Used to achieve multiple inheritance and absolute abstraction

Marker Interface:

  • Dont have any methods or body(kind of empty interface)

  • Ex: Serialisable,CLonable interfaces

Encapsulation:

Process of binding data and methods together into a single unit.

Java Strings:

String is immutable,because once declared cant be changed or updated.whereas String builder,String buffer are the mutable object.

implements Charsequence,comparable,serialisable interfaces.

whereas String builder,string buffer not implements comparable interfaces

Literal:(String pool)

String a=”Sangar”

a=”kumar”;

String b=”Sangar”;

sysout(a)

sysout(b);

Output:

Kumar

Explanation:

Here in String pool both values are getting stored.but when we call it pointer only pointing to new value, existing value is still in String pool.

And if two variables having same value, it refers the existing value, not assigning separate memory to assign this variable

More efficient because for identical Strings, existing objects are being refer same reference.

New keyword to create String: (Heap memory)

String m=new String(“Ayya”);

String n=new String(“Ayya”);

in this way,it creates separate memory in heap memory even though both values are same

Difference:

a==m output:false (this actually compares the memory value)

a.equals(m)output:True (this actulally compares the actual string value)

String methods:

s.charAt(5);----------->C

s.indexOf(“Sangar”);---->4

s.indexOf(“SAngar”,5);---------->5

if no index------------>it returns -1

s.length()---->used to find length

s.trim()----------->removes space

s.replace(“Sa”,”sa”);

s.replaceAll(“Sang”,”snsns”);--------------->can use regular expressions to replace particular characters

s.toLowerCase();

s.toUpperCase();

s.subString(1,3);

s.subString(3);

s.contains(“sangar”);

s.equals(“sangar”);

s.equalsIgnoreCase(“SAggasf”);

s.isEmpty();

s.concat(“Rahul”,”Sekara”);

String.valueOf(2); --->it returns in String “2” ,similarly we can pass objects,or any data type to string

String.join(“/”,”22”,”33”);--->22/33--->not like concat

String Buffer:

is a mutable object. synchronised/thread safe(multiple thread cant be access simultaneuously)

(current capacity * 2) + 2

StringBuffer s=new StringBuffer(“SAngar”);

s.append(“kumar”)

s.reverse();

s.replace(0,3,”ayyan”);

s.capactiy()--->gives the capactiy of string

s.delete(2,5);

s.insert(3,”Sangar”);

StringBuilder:

Same as String Buffer.But non synchronised,not thread safe

Exception handling:

Unexpected event or undesirable event,which occurs during the exectuction of the program,which disrupts the normal flow of the prohrams instructions.

Error:

Which cant handled by our code(like laptop running out of memory)

Object---->Throwable(class):---->Exception and Error--->Checked,Unchecked Exceptions

Error--->Virtual machine Error,Assertion Error

Exception:--->Arithmetic Exception, ClassCastException, NullPointer Exception, ArrayIndex Outof Bound Exception

Exception handling:

  • Try catch Block

    • Try-->Catch--->Finally

    • Catch-->Executes only if Try block throws an exception. Handling code will be written

    • Try--->writing code which going to throw exception,

    • Finally-->Always excutes even catch block not executes or even try has continue or break statements or return statements..it should always followed by try catch block.it also have exception.it breaks only if finaly blokc has System.exit()

    • try-->catch,Try--->Finally,Try--->Catch-->Finally

    • Try block may have n number of Catch blocks

    • Catch blocks will catch the excepetions should be in generic exception type.For ex:Null pointer,then Arithmetic,then Exception

  • throw:

    • throw new Sangar(“SAngar manually created Exception Bro”);

  • throws

    • it actually suppresses the exception

    • has to metnioned in method level and can suppress many exceptions or we can simply give Exception in method level because all excpetions comes under this parent Exception class.

Collection:

group of individual objects.

Iterable(Interface)--->Collection--->List,set,Queue,Map

List(I)--->implemented by ArrayList,LinkedList,Stack,Vector

Set(i)--->SortedSet--->Navigable Set-->HashSet,LinkedSet,TreeSet

Map--->SoretedMap--->Navigable Map--->HashMap,LinkedHashMap,TreeMap

ArrayList:(Insertion order maintained)

  • Asynchronise

  • maintaining insertion order

  • underlying data structure is Growing Array, resizable Array

  • implements Random access,Serialisable,Clonable interfaces

  • duplicate values ,null values allowed

  • homogenous objects can be inserted

  • Methods

    • List<String> s=new ArrayList<String>();

    • s.add(),s.addAll(anotherList),s.get(0),indexOf(30),lastIndexOf(20),clear(),remove(0),s.set(0,20),isEmpty(),getFirst(),getLast(),removeFirst(),removeLast(),addFirst(),addLast(),

  • Iteration:

    • ListIterator<String> listIterator=listed.listIterator();

    • while(listIterator.hasNext()){

    • sysout(listIterator.next();

    • }

    • it has hasPrevious()

    • Iterator<String> iterator=list.iterator();

    • while(iteraetor.hasNExt()){

    • }

Linked List:(Insertion order maintained)

only difference is this is not implementing random access interface so not for search operations,best for insertion

Methods:

link.add(),addAll(),remove(),remove(“SAngar”),removeFirst(),removeLast(),addFirst(),addLast(),pole(),poleLast(),removeFirstOccurance(),removeLastOccurance(),

Stack:

Methods:

st.push(),st.pop(),st.peek()

Vector:

Methods:

vec.addElement(),vec,removeElement()

Set:

Hashset:

  • Duplicate values not allowed(it will remove duplicates)

  • underlying data structure is hashTable

  • insertion order not maintained

  • only one null value allowed

  • Methods:

    • has.add(),addAll(),contains(),remove(),removeAll(),containsAll(),isEmpty(),clear()

LinkedHashSet:

  • Duplicate values not allowed(it will remove duplicates)

  • underlying data structure is hashTable+LinkedList

  • insertion order maintained

  • not implements Random Access interface

TreeSet:

  • Duplicate Values not allowed

  • not heterogenius

  • Null not allowed

  • underlying data structure is Binary Search

  • natural sorting order

  • Methods:

    • add(),headSet(“sangar”,true),tailSet(“sangar”,true),subSet(“Sangar”,”kumar”),comparator(),first(),last(),descendingSet(),higher(),lower(),pollFirst(),pollLast()

    • Iteration:

      • Iterator<String> iter=tree.iterator();

      • Iterator<String> descIT=tree.descendingIterator();

  • Important:

    • TreeSet<StringBuffer> tree=new TreeSet<StringBuffer>();

    • String buffer,String builder not implements comparable interface so we can't use this

Map:

HashMap:

  • Key Value pair

  • using technique called hashing

  • Duplicate key not allowed(latest value of duplicate key will be updated)

  • Duplicate Values are allowed

  • One null key allowed

  • values can be null

  • cant predict the retrivel order

  • Methods:

    • put(),containsKey(),containsValue(),keySet(),Set<Entry<String,String>> set=map.entrySet(),get(),values(),

LinkedHashmap:

insertion order maintained

TreeMap:

Duplicate Keys are not allowed

Null insertion throws nullpointerexception

Final,Finally,Finalise:

Final:

Once class declared as Final,it cant be inherited

Once method declared as Final,it cant be overridden

Once Variable declared as Final,it cant be modified

Finally:

Always followed by try catch block and always executes

Finalize:

is a method which is called by the garbage collector before object getting destroyed.it is used to perform the clean up activities.


User Defined Exception:

public class myException extends Exception{

public String myMessage(){

return “This is not a valid one Bro”;

}

//in Class

public class Practise{

public static void main(String[] args){

try{

if(1<3){

throw new myException();

}

}catch(myException e){

sytsout(e.myMessage());

}

}

}

}

JAVA 8

Annonymous inner class:

1.Using class:

public class Dum{
public void sangar(){

}

}

public class Main{

public static void main(String[] args){

Dum dum=new Dum(){

@ override

public void sangar(){

sysout(“SAngar”);

}

dum.sangar()

}

}

}

2.Using Abstract

public abstract class Dum{
public abstract void sangar();

}

public class MainRunner{

main(){

Dum dum=new Dume(){

@ override

public void sangar(){

sysout(“SAngar”);

}

3.Using Interface

public interface Dum{

void sangar();

public class main(){

main(){

Dum dum=new Dum(){

@O verride

public void sangar(){

sysout(“SAngar bro”);

4.Using method reference:

public interface SS{

void sangar();

public class Runner{
public void sangar(SS ss){

ss.sangar();

main(){

Runner run=new Runner();

run.sangar(new SS(){

@ override

public void sangar(){

sysout(“Sangar”);

}

Functional interface:(SAM-Single Abstract method):

  • If interface has only one abstract method that is called funtional interface

  • functional interface can have static methods, default methods

  • And possibly we can call object methods inside functional interface..

  • One Functional interface can extend another functional interface

Default methods:

  • enables you to add new functionalities to exsiting functional interface

  • interface can have any number of default methods

  • Can be overridden

Static Methods:

  • Can be called only by InterfaceName.methodName()

  • Cant' overridden

Lambda Expressions:

  • functional interface is required

  • Syntax is like below

public interface Sangar{

String adding(String s);

public class Anto{

main(){

Sangar sang=(name)->{return name.toLowerCase();};

or

Sangar sang=(String name)->{return name.toLowerCase();};

or

Sangar sang=name->name.toLowerCase();

sysout(sang.adding(“Ayyappan gunaseknararSADASFASF”));

Built in Functional interfaces:

Function(I):-->Function<I,R>--->Function<String,Integer>

  • Receives one input--->processing then gives one output

  • Method:

    • apply()

    • Syntax:

      • Function<String,Integer> fn=(name)->name.length();

      • Sysout(fn.appluy(“Sangar”));------------->output:6

  • Chaining:

    • andThen()--->first output is input to second

    • compose()-->second output is input to first

Predicate(I):--->Always returns Boolean value

  • Receives one input,returns boolean value

  • Method

    • test()

    • Syntax:

    • Predicate<String> pr=(name)->name.contains(“Yes”);

    • sysout(pr.test(“AyyappanYEs”));------->output:true

  • Chaning:(AND,OR,NEGATE)

    • Predicate<String>pr=(name)->name.contains(“Yes”);

    • Predicate<String>prs=(name)->name.contains(“No”);

    • pr.and(prs).test(“AYyappansYes”);------------>both should match---------->false

    • pr.or(prs).test(“AyyappanYes”);------------->any one should match----------->true

    • pr.negate().test(“SangarYes”);------------->opposite------->outpout:--->false

Consumer(I)--->Not return anything,accepts one input

  • Receives one input,but not return anything(only actionable things are given inside

  • Methods:

    • accept()

    • syntax

      • Consumer<String>sangar=(name)->Sysout(name);

      • sangar.accept(“SAngardhadha”);

Supplier(I):

  • No inputs being passed,but gives output

  • Methods:

    • get()

    • Syntax:

    • Supplier<Object> ss=()->{

    • Calendar cal=Calendar.getInstance();

    • return cal.getTime().toString();

    • };

    • sysout(cal.get());

ForeachFunction:

like loop for each.

Syntax:

List<String> list=Arrays.asList(“Sang”,”sfas”,”asfjn”);

Consumer<String>ss=(name)->Sysout(name);

list.forEach(ss)

BiFunction(I,I,R):

  • takes two inputs returns one output

  • Method:

    • apply()

    • Syntax:

      • BiFunction<STring,String,String> bi=(name,name2)->name.concat(name2);

      • sysout(bi.apply(“Sangar”,”Sangar”);

BiPredicate:

  • takes Two inputs,always returns boolean

    • method:

      • test()

      • syntax:

        • BiPredicate<String,String> s=(name1,name2)->name1.equalsIgnoreCase(name2);

        • sysout(s.test(“sangar”,”gar”));

BiConsumer:

  • takes input,no outputs

others:

IntPredicate,IntFunction,IntConsumer,IntSuppiler

Method Reference with Lambda:(Static method)

ContainingClass::static method name

  • Arguments are important here(Interface method arguments should be match with static method arguments

Syntax:

public interface SS{

public void sum(int num1,int num2);}

public class Dum{

public static Integer adding(int num1,int num2){

return num1+num2;}

main(){

SS ss=Dum::adding

ss.sum(300,400);

Method Reference with Lambda:(Instance method)

containingObject::instancemethodname

public interface SS{

void adding(int num1,int num2);

}

public class DS{

public String add(int num1,int num2){

return num1+num2;

}

main(){

SS ss=new DS::add

ss.adding(20,30);

Method Reference with Lambda:(Arbitraty method)

containingtyope::methodName

Function<String,String> f=String::toLowerCase;

sysout(f.apply(“Ayyappan”))

Function<String,Integer> fs=String::length;

sysout(fs.apply(“:SAngar”);

Method Reference with Lambda:(Constructor)

Classname::new

List<String> list=Arrays.asList(“SAngar”,”SAngar”,”ayyappan”);

Function<List<String>,Set<String>> fn=HashSet::new;

//Lambda

Function<List<String>,Set<String>>=(list)->{ return HashSet<String>(list);};

sysout(fn.apply(list))

other Example:

File[] file=new File(“C/sdajn/”).listFiles(new FileFilter(){

@ override

public boolean accept(File path){

return path.isHidden();

}});

or

File[] file=new File(“ccmkm”).listFiles(File:isHidden);

Use of Comparable,Comparator interfaces:

Comparable:

pojo class should implement Camparable interface and comparaTo method should have the implementation.

Now simply perform,Collections.sort(list); it will sort the List based upon implementation in CompareTo method.

Syntax:

public class StudentPojo implements Comparable<StudentPojo> {

@O verride

public Integer compareTo(StudentPojo o){

if(this.getPrice<o.getPrice()){

return -1

else if(this.getPrice>o.getPrice()) return 1

else return 0

public class{ main(){

Collections.sort(aslist);

Comparator:

lass implements the Comparator interface

class Sangar implements Comparator<StudentPojo>{

@ override

public void compare(Student o1,Student o2){

return Integer.compare(o1.getprice(),o2.getPrice())

}

then,

Collections.sort(asList,new Sangar ());

Streams():

A sequence of elements from a source that supports aggregate operations(data processing operations)

Streams() vs Collections()

Streams are lazily constructed,internally iterated

Collections are externally iterated,eagerly constructed

Characteristics:

  • most stream functions returns another stream,so it is easy to form chain or pipeline

  • Internal iterations

Intermediate Operations:

Examples:filter,map,sorted

these functions returns another stream

Terminary operations:

Examples:collect(),Count(),foreach()

it actually ends the function.that means this not returns any stream

incase if we want to apply multiple filters to the List we can use streams api.

Sample Structure is

List<String> list=list.stream().filter(dish->dish.isVegetarian()==false).sorted(Compartor.comparing(Dish::getPrice))

.map(dish->dish.getName()).collect(Collectors.toList());

filter--->Predicate

sorted--->Comparator

map--->Retrive

Collect--->store as

Distinct function:(Remove duplicates)

List<String> list=Arrays.asList(“SAngar”,”Ayyappan”,”SAngar”);

List<String> listed=list.stream().distinct().collect(Collectors.toList());

listed.forEach(name->sysout(name));

direct print:

list.stream().distinct().forEach(System.out::println);

Filter using Predicate:

List<Dish> vegDishes=dishList.stream().filter(name->name.isVegetarian()==true).collect(Collectors.toList());

vegDishes.forEach(name-->sysyout(name.getName()));

Limit Functions:(upto that limit)

countries.stream().limit(2).forEach(System.out::println);

Skip function:(From that limit)

counties.stream().skip(2).forEach(System.out::println);

Map function(normal Retrieve):

dishList.stream().filter(dish->dish.isVegetarian()).sorted(name->name.getPrice()).map(dish-->dish.getName()).collect(Collectors.toList());

Flat Map:

The flatMap method is used when you need to transform each element of the stream into a stream of elements and then flatten those streams into a single stream. It’s especially useful when dealing with nested structures, like lists of lists.

Syntax:

List<Masala> asLists=Arrays.asList(masala1,masala2);

asLists.stream().map(Dish::getItems).flatMap(List::stream).forEach(system.out::println);

Anymatch:

List<String> anyMatch=Arrays.asList("India","kumar","Ayya[ppan","India");

sysout(anyMatch().stream().anyMatch(name->name.equalsIgnoreCase(“India”)));----->true

All Match:

List<String> anyMatch=Arrays.asList("India","kumar","Ayya[ppan","India");

sysout(anyMatch().stream().allMatch(name->name.contains(“pp”)));----->false

None Match:

List<String> anyMatch=Arrays.asList("India","kumar","Ayya[ppan","India");

sysout(anyMatch().stream().noneMatch(name->name.contains(“ooma”)));----->false

FindFirst&findAny:

List<String> anyMatch=Arrays.asList("India","kumar","Ayya[ppan","India");

Optional<String> ob=anyMatch.stream().findFirst()

sysout(ob.isEmpty());

sysout(ob.get())

Optional<String> ob=anyMatch.stream().findAny();

sysout(ob.get())

Optional<String> ob=anyMatch.parallelStream().findAny();

sysout(ob.get())

Optional Classs:

to handle null pointer exception we can use optional class.

it dont return null value,it return empty

Methods:

  • String s=”nsag”

    • Optional.of(s)

    • if s=null

    • Optional.ofNullable(s)

  • ob.isEmpty();,ob.isPresent();,

  • Syntaxt: for Person pojo class

  • Optional<Car> car;

  • constructor(){

  • this.car=Optional.ofNullable(car);

  • getInsuranceName(Person person){

  • Optional.ofNullable(person).flatmap(Person::getCAr).flatMap(Car::getInsurance).map(Insurance::getINsuranceName).orElse(“Unknown“)

  • Functions in the optional class:

    • empty,of,ofNullable,filter,map,flatmap,get,ifPresent,ispresent,isempty,orElse,orelseGet,orelsethrow

  • Optional<Object>s=Optional.empty()

    • asserttrue(s.isEmpty())

  • s.isPresent()

  • Optional.ofNullable(“SAngar”).orElseGet(()->“Sangar”)

  • Optional.ofNullable(“SAngar”).ifPresent(name->name.length());

  • Optional.ofNullable(“SAngar”).ifPresent(name->name.get())

  • Optional.ofNullable(“SAngar”).orElseThrow(()->new Illegalargumentexception())

Reduce Function:(return type is optional class)

used to perform sum,multiply

List<Integer> list=Arrays.asList(20,30,40,50,60,70);

int result=list.stream().reduce(0,(total,sum)->total+sum)

Integer reduce2 = asListPerson.stream(). reduce(0,(total,sum)->total+ Integer.parseInt(sum.getCar().get().getInsurance().get().getId()),Integer::sum); System.out.println(reduce2);\

Combiner:

at the end we have to mention like Integer::sum (also called identifier,if we didnt mention this it gives compile time error says we cant assign optional to int)

Collectors:

list.Stream().collect(Collectors.toList()).foreach(System.out::println);

list.Stream().collect(Collectors.toSet()).foreach(System.out::println);

list.Stream().collect(Collectors.toCollection(HashSet::new).foreach(System.out::println);

list.Stream().collect(Collectors.toUnmodifiableList().foreach(System.out::println);---------->this list cant be modifiable

toMap:

Map<Integer, Integer> collect = asLists.stream().collect(Collectors.toMap(name->name, value->value+20,(key1,key2)->key1));

or we can give like

Map<Integer, Integer> collect = asLists.stream().collect(Collectors.toMap(Function.identity(), value->value+20,(key1,key2)->key1));

Comments

Popular posts from this blog

Rest Assured Api Automation

Appium Notes

Jenkins Notes