Thursday, 5 October 2017

MVC and MVVM

MVP design pattern is a set of guidelines that if followed, decouples the code for reusability and testability. It divides the application components based on its role, called separation of concern.


Model: It is responsible for handling the data part of the application.
View: It is responsible for laying out the views with specific data on the screen.
Presenter: It is a bridge that connects a Model and a View. It also acts as an instructor to the View.


MVP lays few ground rules for the above mentioned components, as listed below:
A View’s sole responsibility is to draw UI as instructed by the Presenter. It is a dumb part of the application.
View delegates all the user interactions to its Presenter.
The View never communicates with Model directly.
The Presenter is responsible for delegating View’s requirements to Model and instructing View with actions for specific events.
Model is responsible for fetching the data from server, database and file system.


3.5. Comparison to Model View Controller
In the Model View Presenter pattern, the views more separated from the model. The presenter communicates between model and view. This makes it easier to create unit tests Generally there is a one to one mapping between view and Presenter, but it is also possible to use multiple presenters for complex views.

In the Model View Controller pattern the controllers are behavior based and can share multiple views. View can communicate directly with the model.

MVVM

Also know as model view binder

The view binds to observable variables and actions exposed by the view model typically using the data binding framework.

The view is responsible for handling for example:

Menus

Permissions

Event listeners

Showing dialogs, Toasts, Snackbars

Working with Android View and Widget

Starting activities

All functionality which is related to the Android Context

4.2. The view model
The view model contains the data required for the view. It is an abstraction of the view and exposes public properties and commands. It uses observable data to notify the view about changes. It also allows to pass events to the model. It is also a value converter from the raw model data to presentation-friendly properties)

The view model has the following responsibilities:

Exposing data

Exposing state (progress, offline, empty, error, etc)

Handling visibility

Input validation

Executing calls to the model

Executing methods in the view

The view model should only know about the application context. the application context can:

Start a service

Bind to a service

Send a broadcast

Register a broadcast receiver

Load resource values

It cannot:

Show a dialog

Start an activity

Inflate a layout

4.3. The model
Contains a data provider and the code to fetch and update the data. The data can be retrieved from different sources, for example:

REST API

Realm db

SQLite db

Handles broadcast

Shared Preferences

Firebase

etc.

Basically the same as the model in the MVP.

4.4. Differences to MVP
MVVM uses data binding and is therefore a more event driven architecture. MVP typically has a one to one mapping between the presenter and the view, while MVVM can map many views to one view model In MVVM the view model has no reference to the view, while in MVP the view knows the presenter.

More info
https://blog.mindorks.com/essential-guide-for-designing-your-android-app-architecture-mvp-part-1-74efaf1cda40

Tuesday, 29 August 2017

Multithreading

Introduction

MultiTaasking   Executing multiple tasks simultaneously .Example is class and student(Student Does multile tasks in class)

2 categories we have
1)Process based
2)Thread based

Process based

Execuing several tasks simultaneously where each task is seperate independent process
Example: Typing java pgm and listening to music from same system and same time download file from internet
This is applicable to OS level

Thread based

This is at programatic level
1)Execuing several tasks simultaneously where each task is seperate independent part of te same program
Advantage is to increase performance by decreasing response time of the system

Whether it is process based or thread based main obective of muli tasking is to reduce response time of the system aand to improve
performance

Main important application areas of multi threading are
1)To develop multimedia graphics
2)To develop animations
3)To develop video games
4)Internally servers use multi threading concept
5)When cmp with old languages developing multi threaded applications in java is very easy because java provides in built support for mutithreading with rich API[Thread , Runnable , Thread group....]


What is a thread

Seperate flow of execution


ways
Extending thread class
Implementing interface

Extending thread class
1)Code with in run method is called job of thread


Case 1 Thread scheduler

Thread scheduler part of JVM
Responsible to schedule execution of threaded
There is no guarantee for exact o/p but we can provide several possible o/p's

Case 2
Difference b/w t.start and t.run
t.start then seperate thread will be created  to do  job
t.run then it will be executed as a method call by main thread ,no new thread is created here

Case 3 why we have to call start method
It is  heart of multi threading as it performs all the mandatory activities like registering to thread scheduler..etc

Can we overload run method of thread clas??
yes we can but , Thread class start method always calls no arg run method other overloaded method we have to call explicitly


Class myThread extends Thread
{



}
If we start this thread then blank o/p as super class Thread run method is empty
Note

If we are not overriding run method then thread class run method will be executed which has empty implementation, hence we won't get any obj

Overriding of start method

Class myThread extends Thread
{


public void start()
{

S.o.p("start");
}

public void run()
{
s.o.p("ryn");
}

}



Class Test{
p s vm()
{
myThread t = new myThread
t.start();
S.O.P("main thread");

}


}

o/p start
main thread

Above o/p is produced by only main thread
Start method will be executed as a method call.Since run method is not called no new thread is created

It is not recomended to override start method 

If we write super.start in start method then
New thread will be ceated and run method will be called
o/p is 
child thread o/p is run
main thread executes start and main thread
Two threads will be running parellely;

Thread life cycle

New/born state  --- mythread t = new mythread();
ready /runnable --- t.start();
If thread scheduler allocates processor then thread will enter in to running state
if in running state if thread calls yield method then it will go back to runnable/ready state
Dead state if run method completes

Note:
Try to restart the same thread then we get illegal state exception

Defining a thread by implementing a runnable interface

Class myRunnable implements runnable
{

public void run()
{
for(int i =0;i<10;i++)
{

s.o.p("child thread");
}

}

}

class threaddemo
{

p smv()
{

myRunnable r = new myRunnable();
Thread t1 = new Thread(r);
t.start();

}
}

o/p both threads will be executed simultaneously


myRunnable r = new myRunnable();
Thread t1 = new Thread();
Thread t2 = new Thread(r);
t1.start();////new thread will be created and thread class run method will be called
t1.run();//new thread will not be created and run will be called as normal method call
t2.start();//new thread will be created and runnable run method will be called
t2.run();//new thread will not be created and run of runnable will be called as normal method call
r.start();//cannot find symbol method start in class myrunnble
r.run();//my runnable run method willbe executed



Note
Recomended approach is implements runnable to create a thread


Constructors in thread class
1)Thread t = new Thread();
2)Thread t = new Thread(runnable r);
3)Thread t = new Thread(String name);
4)Thread t = new Thread(Runnable r , String name);
5)Thread t = new Thread(ThreadGroup g , String name);
6)Thread t = new Thread(ThreadGroup g , Runnable r);
7)Thread t = new Thread(ThreadGroup g , Runnable r , String name);
8)Thread t = new Thread(ThreadGroup g ,Runnable r , String name , long stacksize);

Durga's approach to defin a thread(not recomended to use)

myThread t = new myThread();
Thread t1 =  new thread(t);
t1.start();
here myThread run method will be called



Thread Priority
1)Every thread has priority 
2)Priority is always 1 -- 10
3)1 is min priority and 10 is max 


Default priority for every thread is inheritated from parent thread
Default priority of main thread is 5


Prevent a thread execution

1)yield()
2)join()
3)sleep();

yield()
when ever we call Thread.yield then it pauses its execution and gives a chance to other threads of same priority 

The Thread which is yieled , when it will get chance once again??
It depends on thread scheduler and we can't expect exactly


Complete prototype of yield method?
It is public staatic native void yield();

note
Some platforms won't provide proper support for yield method

Tuesday, 22 August 2017

Inner Class

Without existing one type of oject if there is no chance of existing another type of object then go for inner classses
Example university and department
University consists of several depts and hence dept is inner class of university
Example 2 : engine is inner class of car
Example 3:
Map is a group of key value pairs and each key value pair is called an Entry
With out existing map object there is no chance of existing entry object hence interface Entry is defined
inside Map interface

interface Map{
interface Entry{
}
}

Note :
1)With out existing outer class object there is no chance of existing inner class object
2)Relation b/w outer and inner class is has-A relation

Types
1)Normal or regular inner classes
2)Method local inner classes
3)Anonymous inner clases
4)Static nested class

Normal or regular inner classes
If we are declaring any named class directly inside a class with out static modifier such type of inner class is normal or regular inner class

When wee compile outer.java following files are generated
outer$inner.class and outer.class


Class outer{

class inner
{

}
psvm()
{

S.O.p("hello");
}


}


If we run outer class we get hello as output
If we run inner class java outer$inner no such method error main

Note:

staic memebers not allowed in inner class including main method

lass outer{

class inner
{

psvm()
{

S.O.p("hello");
}

}



}


Above we get compile time error as staic memebers not allowed in inner class including main method

Accessing inner class code from static area of outer class

Class outer{

class inner
{

public void m1()
{

S.O.p("hello");
}

}
psvm()
{


//To call m1 we need inner class obj and before that create outer class object
outer o = new outer();
outer.inner i = o.new inner();
i.m1();



}


}

accessing inner class code from instance area of outer class 

Class outer{

class inner
{

public void m1()
{

S.O.p("hello");
}

}

public void m2()
{

S.O.p("hello m2");
//calling m1;
inner i = new inner();
i.m1();
}
psvm()
{

//call m2
outer o = new outer();
o.m2;


}


}

Accessing inner class method From outside outer class

class outer{

class inner
{

m1()
{
S.O.P("hello inner");
}

}



}

Class Test{

psvm()
{

// want to access m1

outer o = new outer();
outer.inner i = o.new inner();
i.m1();

}

}


Note
1)From normal inner class we can access both static or non static members of outer class
2)With in inner clas this always refers current inner class object if we want to refer current outer class object
we have to use Outer Class name ".this"
3)Mofifiers for outer class
public , default , final , abstract ,strictfp
4)Modifiers for inner class
public , default , final , abstract ,strictfp ,private , protected , static

Nesting of inner classes

Inside inner class we can declare another inner class i,e nesting of inner classes is possible

Example
Class A
{


 Class B
 {
   Class C
   {
public void m1()
{
S.O.P("hello");
}
   }
 }
}
Class Test{


P S V M()
{

A a = new A();
A.B b = a.new B();
A.B.C c = b.new C();

c.m1();

}

Method local inner classes

Main purpose of Method local inner class is to define method specific repeatedilty required functionality
Method local inner classes are best suitable to meet nested method requirements
Scope of method local inner classes is with in method only
These are rarely used

Note
1)Nested methods not alloewed in java
2)We can eclare method local inner class inside both instance and static methods
3)If we declare method local inner class in the instance method of outer class then we can access both instnce and static variables of outer class from the method local inner class
4)If we declare method local inner class in the static method of outer class then we can access only static variables of outer class from the method local inner class
5)From Method local inner class we can't access local variables of method in which we declared inner class , if local variable declared as final then we can access

Example


Class Test{

int i = 10;
static int j = 30;
public void m1()
{

int k =10;
final int m = 40;

Class inner{

public void m2()
{
Line 1;

}

}


}



}

From lne 1 which variables we can access
Except k we can access i , j and m variables

If we declare m2 as static then it will be a ompile time error since we cannot declare static in inner classes

Note 

Only applicable modifiers for method local classes are final , abstract , strict fp



}


Anonymous inner classes

Sometimes we can declare inner class with out name these are anonymous inner class
Only one time use ,i.e instant use classes are anonymous inner class
Main purpose is one time usage
3 types are there

1)Anonymous inner class that extends a class
2)1)Anonymous inner class that implements an interface
3)1)Anonymous inner class that is defined inside arguments


1)Anonymous inner class that extends a class

only one time requirement or  then use this
Eample
Class PopCorn
{

public void taste()
{
S.O.P("salty");
}
}

Class Test{

P S V M()
{
PopCorn p = new PopCorn()
{

public void taste()
{
S.O.P("spicy");
}
};

p.taste();//spicy

PopCorn p1 = new PopCorn();
p1.taste();//salty

PopCorn p2 = new PopCorn()
{
public void taste()
{

S.O.P("Sweet");
}

};

p2.taste();//Sweet

}



}


Note:
1)PopCorn p = new PopCorn(); // we are creating popcorn object
2)PopCorn p = new PopCorn()
{


};//we are declaring a class that extends popcorn witout name(anonymous inner class)
For that child class we are creating an object with parent reference
3)2)PopCorn p = new PopCorn()
{

public void taste()
{
S.O.P("gg");
}

};

//we are declaring a class that extends popcorn with out name (anonymous inner class)
In that child class we are overriding taste method
For that child class we are creating an object with parent reference

Normal java class Vs Anonymous inner class

1)Both can extend only one class
2)Anonymous inner class can implement only one interface
3)Anonymous inner class can extend a class and implement interface but not both simultaneously
4)constructor cannot be written in anonymous inner class since these classes do not have any name
Note ;

Some times we can declare inner class with static modifier such type of inner classes are called static nested classes.Thesse ra enot strogly associated with outer classes
To access static nested class method outer class object is not required
If we want to create nested class obj outside of outer class then we can create as follows
OuterClassname.Nested n = new OuterClassname.Nested();
In static nested classes We can declare static methods including main method and hence we an invoke static nested class directly from command prompt
From static nested class we cannot access instance members of outer class


Normal inner class vs static nested class
1)Neste class not closely associated with outer class , normal opposite
2)We cannot declare static members in normal inner class opp in nested
3)Can't declare main methid in normal inner classes , nested opp
4)From normal inner class we can access both static and non static members of outer class but in nested we can access only static members


Wednesday, 2 August 2017

OOP Concepts important points

1)Encapsulation = datahiding + Abstraction

2)IS A relation Ship is inheritance

3)In Inheritance Parent reference can hold child class object.But here only parent class methods will be accessible , Child class methods are not available

4)In Inheritance Child ref cannot hold parent object

5)Implementation will be only once and hence no ambiguity in case of multiple inheritance in interfaces

6)Cyclic inheritance is not allowed in java

7)Has - A is also known as Composition/Agreegation.Example is Car has a engine
No speific keyword  here , we use new operator
write once and use anywhere -- reusability

8)Composition and aggregation  difference
Strong association is composition example univrsity and branches(csc,eee...)
University cannot exist with out branches
Weak association is aggregation example department and professor
Professor can exist with out department

9)When to use IS - A / HAS - A

Total functionality is needed in child class then go for IS- A

Example student needs all functionality of person

Part of functionality the go for has-A

test class example
Student may or may not need all details of all test

10)In overloading same method names but different argument types.method signature should be same


11)methodsignature = name+arguments

Compiler uses method signature to resolve method calls
with in a class two methods with same signature not allowed even return types are different

12)In method overloading compiler takes care of method resolving based on the reference type

13)Automatic promotion allowed in overloading
char -- byte-- short --int--long--float--double

14)m1('a')
Calling Method
public void(int i)
{
}

Yes m1('a')gets called

15)m1(Object o)
m1(String s)

Calling is
m1(null)
then m1(string s ) gets priority since it is child class 

16)m(String s)
m(StringBuffer sb)
calling
m(null)

Ambuguity hence compile time error.Compile error since both string and stringbuffer are at same level

17)m1(int i ,float j)
m1(float i ,int j)

calling
m1(10,10)
Ambiguous and hence compile time(check auto promotion 13 point)
m1(10.5f,10.5f)
No matching method found

Since float cannot be reduced to int

18)m1(int x)
m1(int... x)

calling
m1()
then m1(int... x)gets called
calling
m1(10,20)
var arg gets called
calling
m1(10)
then here m1(int x)gets called even both matches , since it is old

19)Overriding
Method name and arguments should be same here
Covariant return types allowed here like parent class can have object as return type then child class can have string as return type
Covariant concept not applicable for primitives
Example if parent class return type is double then child class cannot have int
Covariant concept Applicable only to objects
parent class abstract methods we should override in child class to provide implementation
parent class non abstract method can be declared as abstract in child class

20)In overloading
Return type can be differenr for the overloaded methods when numbrer of arguments different.
with in a class two methods with same signature not allowed even return types are different
Invalid Case

public void add()
 {
System.out.println("add");
 }

 public int add()
 {
System.out.println("1");
return 1;
 }

 valid case

  public void add()
 {
System.out.println("add");
 }

 public int add(int i)
 {
System.out.println("1");
return 1;
 }

21)
Exception Rule
If child class method throws any checked exception then compulary parent class should throw checked execption or its parent exception else Compile time error

22)We cannot override class level method to object level methods(Static to non static not to be done)
Vice versa also not possible
Both parent and child class have static methods then it is method hhiding not overriding
In method hiding mehod resolution is taken based on the compiler i,e based on reference not on the run time object
Example

public class ParentExample {

public static void testOne()
{
System.out.println("I'm parent test");
}

}


public class ChildExample extends ParentExample{


public static void testOne() {
// TODO Auto-generated method stub

System.out.println("I'm Child ");
}
}


public class MainClass {
public static void main(String[] args) {

ParentExample parentObj = new ChildExample();
parentObj.testOne();
/*ChildExample chidObj = new ChildExample();
chidObj.testOne();*/

}

}

O/P
I'm parent test

For the same thing if it is not method hiding and if it is just overriding then child class method will be called

23)Var - Args Overriding
We cannot override Vararg method with the normal method
class parent{
public void m1(int...x)
{
s.o.p("parent")

}

}

class child extends parent{
public void m1(int x)
{

s.o.p("child")
}


}

calling like this
parent p1 = new child();
p.m1();//parent method is called since above scenatio is overloading not overriding.In overloading refenrece type during compiling

24)Overriding not applicable to variables
variable resolution always takes place by compiler based on reference type
Even above concept is same with static variables

25)Difference b/w overloading and overriding

property     overloading override
Meth name must be same must be same
Argument types must be diff(atleast order) must be same(incl order)
Meth sig must be diff must be same
Return type no restriction must be same until 1.4
from 1.5 covariant allowed
private static final can be overloaded cannot be over ridden
Access modifiers no restrictions scope should not be decreased
but we can increase
 
throws clause no restriction if child class throws any checked exception compulsary parent class must throw same checked exception or its parent
MEthod resolution always takes care by compiler based on ref type always takes care by jvm based on runtime obj
compile time poly/early binding/static poly Run time poly/late binding/dynamic poly


26)Note
static and abstract cannot be declared together

27)Polymorphism
same name multiple forms
overloading comes under this
overriding also under this
usage of one parent to hold child objects is an example of poluorphism
example list l = new ArrayList
list l = new Linkedlist
list l = new stack
list l = new vector

parent class reference can be used to hold child object but by using this reference we can call only parent class methods and we cant call child specific methods
P --- > m1
C --->  m2
P obj = new C();
p.m2//we get compile time error in this case
p.m1()//this is valid
But by using child object reference we can call both parent and child class methods
C obj = new C();
obj.m1();
obj.m2();
Both are valid

28)When v should go for parent reference to hold child 
If we do not know run time object then go for parent reference
Arraylist can hold any type of objects 
while retriving if we are not aware then use parent rference
In array list get method always returns object type

If mehod returns arraylist/linkedlist/stack then declare method return type as List as it is parent 

29)OOPS
Encapsulation -- security
Polymorphism -- flexibility
Inheritance  -- reusability
Above are 3 pillars of oops

30)Coupling
Degeree of dependency between components is called coupling and if dependency is less then it i loosely coupling if it is more then tightly coupling
Enhancement becomes difficult in tight coupling
Reusability is not posssible here .it is supressed
Maintanability is tough

31)Cohesion
For every component we difine its own responsibility then it is called cohesion
High cohesion is good programmig practice
Seperate presentation -- view
controller --- operation
model --dada objects
Then this is high cohesion

32)Object type casting
Parent class can hold child class object
example Object o = new String("aaa");
Interface ref can be used to hold implemented class object

Object o = new String("aaa");
StringBuffer sb = (StringBuffer)o;//It is valid till compile time

33)Type casting Rule

A b = (C)d;
A and C is class or interface name
b and d  is name of ref variable
Converting d object to c type and assigning to A type reference variable

Conditions to checked
Check relation between C and d .there should be some relation then no compile time error

String s = new String("nnn");
stringBuffer sb = (StringBuffer)s;
then we get compile time error since no relation b/w string na d string buffer
Inconvertible type name of compile time error

Cond 2 ) C must be derived or same tye as A

Example 
Object o = new String("aaa");
StringBuffer sb = (StringBuffer)o;//It is valid till compile time
//we get run time error as class cast excption

Example 
Object o = new String("aaa");
StringBuffer sb = (String)o;//Compile time error , incomatible types

Cond 3)underly object tye of d must be same or derived class of C
Runtime object type of 'd' must be either same or derived type of c else we will get runtime exception saying class cast exception

Object o = new String("aaa");
Object o = (String)o;
Valid as all conditions are met


34)We are not creating new object in type casting ,for existing object we are creating new reference.


Note
A<---B<---C
B b = new C();
same as (B)C
A a = new C();
same as (A)((B)c)

35)When ever we are executing a java class follwwing sequence of steps will be executed as the part of atatic control flow
1)Identification of static members from top to bottom[1 to 6]
2)Execution of static variables assignments and static blocks from top to bottom[7 to 12]
3)Execuion of main method[13 to 15]
Example
 class based{
 1..only identification static in i = 10;7..
 static{

2..only identification m1();8..
 S.O.P("First static block")10..

 }
 3..p s v main()
 {

 m1();13..
 S.O.P("main method");15..
 }
 4..p s v m1()
 {

 s.o.p(j)9.. 14..

 }

 5..static{9..

 s.o.p("second static block");11..


 }

 6..static int j = 20;12..

 }

O/P
0
First static block
second static block
20
main method

36)Read Indirectly Write Only(RIWO)
With in static block if we read any variable then it is direct read
If we read through method and call method in static block then it is indirect method

If a variable is just identified by the JVM and not assigned any value then it is in RIWO.In tis case direct read is not allowed we get compile time error
i.e illegal forword reference


static blocks are executed at the time of class loading hence at the time of class loading if we want to perform any activity we have to define that inside static block
example 1) loading native libraries at the time of class loading

37)Without writing main method it is possible to print some statements to console through static block

Without static block and with out main peint some thing
Example one
class test{
static int x = m1();
public static int m1()
{

s.o.p("hello print")
System.exit(0);
return 10;
}


}

Example 2

Class Test
{

static test t = new Test();
{//this is an instance block and it is executed when the object is created


s.o.p("hello");
System.exit(0);

}

Example 3
class Test{

static Test t = new Test();
//when ever we create an object constructor gets invoked
Test()
{
S.O.P("hello");
System.Exit(0);


}


}


}


38)Instance Control Flow

Creating object followng steps
1)Identification of instance members from top to bottom
2)Execution of instance variable assignments and instance blocks from top to bottom
3)Execution of constructor

when ever we are running a java class first static control flow is executed  , if we are creating obj in static conrol then above steps will be
executed as a part of instance control flow

39)Note
Static control flow is one time activity which will be performed at time of class loading but
Instance control flow is not one time activity and it will be performed for every object creation.

40)Object creation is the most costly operation if there is no specific requirement then it is not recomended to create object

41)Instance control flow in parent to child relation ship(When we run child class)
1)Identification of instance members from parent to child
2)execution od instance variable assignments and instance blocks in parent class
3)execution of parent constructor
4)execution of instance variable assignments and instance blocks in child class
5)execution of child constructor

42)From static area we cant access instance members directly bcoz while executing static area JVM may not identify instance members

Class Test{

int x = 10;

P Sv m()
{

S.O.P(x);//we get compile time error non static var cannot be accessed from static context
Test t = new Test();
S.o.p(t.x)//valid we get 10 as o/p
}
}

43)ways to create an object in java
1)By using new operator
2)By using newInstance() method
3)By isng factory method
4)By using Clone() method
5)By using deserialisation

44)We use constructors to initialise object not create

Diff b/w constructor and instance block

1)For every object creation we need to do some operation other than initialisation then we should go for instance block

2)Incrementing count value for every object creation is an example of instance block

3)Constructor and instance block have their own diff purposes and replacing one concept with another concept may not work always

4)Both constructor and instance block will be executed for every object creation but instance block execution is first followed by constructor next.

45)Count number of objects created in class

public class CountObject {
public CountObject() {
// TODO Auto-generated constructor stub
}
public CountObject(int i) {
// TODO Auto-generated constructor stub
this(20.5);
}
public CountObject(double d) {
// TODO Auto-generated constructor stub
System.out.println(d);
}

static int counter;
{
 
counter++;
}
public static void main(String[] args) {
CountObject t1 = new CountObject();
CountObject t2 = new CountObject(2);
CountObject t3 = new CountObject(10.5);
System.out.println(counter);
}
}

O/P : 3

46)Rules of writing constructors

1)Name of class and constructor should be same

2)Automatically called when ever we create object and hence return type concept not applicable here even void also

3)Class Test
{

void Test()  // no compile time error since compiler tkes it as a method
{
}

}

Method name same as constructor is legal but not good programming practise

4)Modifiers for constructor are public , pvt , protected, default

47)Default Constructor

1)Compiler is responsible to generate default constructor

2)It will generate if and only if we are not wriring constructor

3)It is always no arg constructor

4)Access modifir of default constructor is always same as class modifier(This rule is applicable only for public and default)

5)It contains only one line i.e super();

6)If we do not write super() or this() as first line in constructor then compiler will do this job i.e it will add super();

48)Case 1:

Super() or this() should be placed in first line of constructor if we are trying to place any where else we will get compile time error

Case 2:
Class Test{

Test()
{

super();
this();//compile time error since this is in second line and hence super() and this() both cannot be used
}

}

Case 3:
We can use super() or this() only inside constructor , if we are trying to use outside of constructor we will get compile time error

49)Super(), this()

1)use only in constructors
2)use in first line only
3)use any one but not both
4)these are construtor calls to call super class and current class constructors
5)super and this are keywords to refer super class and current class instance members
6)super and this cannot be used in static context
7)Super(), this() used only once in constructor
8)Super, this can be any number of times

50)
Overloaded Constructors
With in a class we can declare multiple constructors and all these constructors having same name but different type of arguments hence all these constructors are considered as overloaded constructors
Hence overloading concept applicable for constructors

For constructors inheritance and overriding concepts are not applicable but overloading concept is applicable.
Every class in java including abstract class contain constructors but interface do not contain

Since constructors are mainly used for initialization and as interface do not contain instance variables there is no need of constructor

51)Case 1:
Recursive method call is a runtime exception saying stack overflow error but in our program if there is chance of recursive constructor invocation then
code wont compile and we will get compile time error

Recursive contructor invocation
If only possibility is there then comiler immediately throws error

When ever we are writing any argument constructor it is  recomended to write no arg constructor.
Special care while writing child class constructor if parent has arg constructor and child has no constructor then by default compiler will provide
default constructor and it will implicity call super and it will not find no arg constructor in parent

valid compiler will provide default constructor for both the classes
Class p{
}
Class c extends Parent{



}

Valid compiler will provide default no arg constructor to child which will implicity call super class constructor 

Class p{

p()
{
super();
}

}
Class c extends Parent{



}


Invalid becoz compiler will provide default no arg constructor to child which will implicitily call super and hence it will not find matching constructor

Class p{

p(int i )
{
super();
}

}
Class c extends Parent{



}

52)Note :If parent class constructor throws some checked exception then child class contructor  must throw same checked exception or its parent

Class P
{

P()throws IOException
{



}

}


Class C extends P{

}

We compile time error since child class constructor will call parent class constructor (Calling method should handle exception);
Compiler default no arg constructor will contain super

How to handle above case


Class P
{

P()throws IOException
{



}

}


Class C extends P{

try{
super();
}
catch(IOException)
{
}



}

Invalid sinece first statement should be super

Class P
{

P()throws IOException
{



}

}


Class C extends P{


super() throws IOException;




}



Valid above one

53)Singleton classes
For any java class if we are allowed to create only one object such type of class is called single ton class
example runtime , businesselegate,service locator  etc
Advantage of singleton class
Improve performance
If several people have same requirement then it is not recomended to create seperate object for every requirement ,we have to create only one object and we can
reuse same object for every similar requirement so that performance and memory utilisations will be improved.This is the central idea of single ton classe

How to create our own single ton classes
We can create our own single ton classes for this we have to use private constructor and private static variable and public factory method
Approach 1:

Class Test{

private static Test t = new Test();
private Test()
{
}
public static Test getTest()
{
 return t;

}


}


Disadvantage of above method
Object gets created in the beginning and if we do not use then wastage of resource 

Approach 2:
Class Test{

private static Test t = null;
private Test()
{
}
public static Test getTest()
{
 if(t==null)
 t = new Tets();
 return t;

}


}

54)Class is not final but we are not allowed to create child classes how it is possible??
Declare every constructor as private


55)Only Inner classes in Java can be static, not Top level class.

Tuesday, 4 July 2017

Solution to producer and Consumer Problem

Using Wait and Notify


public class ProducerConsumer {
LinkedList<Integer> list = new LinkedList<>();
private static final int limit = 10;
private Object lock = new Object();

public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (lock) {
while (list.size() == limit) {
System.out.println("List is full, so Produce thread is waiting..");
lock.wait();
}
list.add(value++);
System.out.println("Producer thread is notify..");
lock.notifyAll();
}
}
}

public void consume() throws InterruptedException {
while (true) {
synchronized (lock) {
while (list.size() == 0) {
System.out.println("List is empty, so Consumer thread is waiting..");
lock.wait();
}
int val = list.remove(0);
System.out.println("Consumer thread notify..");
lock.notifyAll();
}

}
}

public static void main(String a[]) {
final ProducerConsumer producerConsumer = new ProducerConsumer();

Thread producerThread = new Thread(new Runnable() {

@Override
public void run() {
try {
producerConsumer.produce();
} catch (Exception e) {
e.printStackTrace();
}

}
});

Thread consumerThread = new Thread(new Runnable() {

@Override
public void run() {
try {
producerConsumer.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
});

producerThread.start();
consumerThread.start();
}
}

Using BlockingQueue


 
public class ProducerConsumerWithBlockingQueue {
private final int LIMIT = 10;
private BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<Integer>();
public void producer() throws InterruptedException{
int val = 0;
while (true) {
blockingQueue.put(val++);
}
}
public void consumer() throws InterruptedException {
while(true) { 
int val = blockingQueue.take();
}
}

}

What is Producer and consumer Problem in Java

In computing, the producer–consumer problem[1][2] (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer's job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.
The solution for the producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer. The solution can be reached by means of inter-process communication, typically using semaphores. An inadequate solution could result in a deadlock where both processes are waiting to be awakened. The problem can also be generalized to have multiple producers and consumers.


Java blocking Queue


Today we will look into Java BlockingQueue. java.util.concurrent.BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

Java BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
Java BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.

Java BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue because it’s handled by implementation classes of BlockingQueue.
Java provides several BlockingQueue implementations such as ArrayBlockingQueueLinkedBlockingQueuePriorityBlockingQueueSynchronousQueue etc.
While implementing producer consumer problem in BlockingQueue, we will use ArrayBlockingQueue implementation. Following are some important methods you should know.
  • put(E e): This method is used to insert elements to the queue. If the queue is full, it waits for the space to be available.
  • E take(): This method retrieves and remove the element from the head of the queue. If queue is empty it waits for the element to be available.

Interview Programs

Simple Android thread and handler example

onCreate()
{
//layout and progress bar we have
//thread creation
thread = new Thread(new Mythread())
thread.start();
handler = new Handler()
{
handleMessage(Message msg)
{

//set value to progress bar

}
};



}

class Mythread implements Runnable
{


run()
{
//create Message object

for(int i =0;i<10;i++)
{
Message msg = Message.obtain();
msg.arg1 = i;
handler.sendMesahe(mg);

}

}


}

Download an image and send it to UI android httpurlconnection

private void downloadImage(String urlStr) {
      progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
      final String url = urlStr;

      new Thread() {
         public void run() {
            InputStream in = null;

            Message msg = Message.obtain();
            msg.what = 1;

            try {
               in = openHttpConnection(url);
               bitmap = BitmapFactory.decodeStream(in);
               Bundle b = new Bundle();
               b.putParcelable("bitmap", bitmap);
               msg.setData(b);
               in.close();
            }catch (IOException e1) {
               e1.printStackTrace();
            }
            messageHandler.sendMessage(msg);
         }
      }.start();
   }

  private Handler messageHandler = new Handler() {
      public void handleMessage(Message msg) {
         super.handleMessage(msg);
         ImageView img = (ImageView) findViewById(R.id.imageView);
         img.setImageBitmap((Bitmap) (msg.getData().getParcelable("bitmap")));
         progressDialog.dismiss();
      }

   };

Fibonacci series


class FibExample{  
public static void main(String args[])  
{    
 int n1=0,n2=1,n3,i,count=10;    
 System.out.print(n1+" "+n2);//printing 0 and 1    
    
 for(i=2;i<count;i++)//loop starts from 2 because 0 and 1 are already printed    
 {    
  n3=n1+n2;    
  System.out.print(" "+n3);    
  n1=n2;    
  n2=n3;    
 }    
  
}}  

Find duplicates in array


public class DuplicateArray {


public static void main(String[] args) {
int sample [] = {1,2,3,4,5,2,3,4,2,2,2};
HashMap<Integer ,Integer> testMap = new HashMap<Integer,Integer>();
for(int  num : sample)
{
int i = 1;
if(!testMap.containsKey(num))
{
testMap.put(num, i);
}else
{
testMap.put(num, testMap.get(num)+1);
}
//System.out.println("print"+num);
}
for (HashMap.Entry<Integer, Integer> entry : testMap.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}

}
}

Reverse a String


public class ReverseString {

public static void main(String[] args) {

String test ="ABCD";
StringBuffer sb = new StringBuffer();
for(int i = test.length()-1 ;i>=0;i--)
{
sb.append(test.charAt(i));
}

System.out.println("print rev"+sb.toString());
}
}

Java Simple CallBack Example


public interface EventInterface {



public void notifyEventExample();

}

public class CallBack {

public EventInterface eI;
public CallBack(EventInterface eventInt)
{
this.eI = eventInt;
sendEvent();
}
public void sendEvent()
{
eI.notifyEventExample();
}
}



public class CallBackreceiver implements EventInterface {
public CallBackreceiver() { CallBack testCallBack = new CallBack(this); }
/* * public void testMethod() { testCallBack.sendEvent(); } */ public static void main(String args[]) {
CallBackreceiver receicer = new CallBackreceiver(); // receicer.testMethod();
}
public void notifyEventExample() { System.out.println("I'm Called"); }
}

Download an image from web service and load into an image view

@Override
    protected Bitmap doInBackground(String... params) {
     Bitmap bitmap = null;
     try {
         URL url = new URL(params[0]);
                bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
 } catch (IOException e) {
  Log.e(TAG, e.getMessage());
 }
        return bitmap;
    }
@Override
    protected void onPostExecute(Bitmap bitmap) {
  imageView.setImageBitmap(bitmap);
    }

Reverse a string with out using String Buffer and String builder

public static String reverse(String source){
        if(source == null || source.isEmpty()){
            return source;
        }       
        String reverse = "";
        for(int i = source.length() -1; i>=0; i--){
            reverse = reverse + source.charAt(i);
        }
      
        return reverse;
    }



Alternate thread printing odd and even




public class PrintOddEvenInSequence {


private boolean isOddPrinting = false;

private boolean isEvenPrinting = false;

private int oddNum = 0;
private int evenNum = 0;
public static void main (String args[]) {
final PrintOddEvenInSequence oddEvenInSequence = new PrintOddEvenInSequence();
Thread printOddNumThread = new Thread(new Runnable() {
public void run() {
oddEvenInSequence.printOddNumber();
}
});
printOddNumThread.start();
Thread printEvenNumThread = new Thread(new Runnable() {
public void run() {
oddEvenInSequence.printEvenNumber();
}
});
printEvenNumThread.start();
}
private void printOddNumber() {
synchronized (this) {
while (true) {
while (isEvenPrinting) {
try {
System.out.println("Waiting to print odd number");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isOddPrinting = true;
System.out.println(++oddNum);
isOddPrinting = false;
notify();
}
}
}
private void printEvenNumber() {
synchronized (this) {
while (true) {
while (isOddPrinting) {
try {
System.out.println("Waiting to print even number");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isEvenPrinting = true;
System.out.println(++evenNum);
isEvenPrinting = false;
notify();
}
}
}

}



Find number of repeating characters in a string



public class Testmain {

public static void main(String args[])throws Exception{
int  count = 0;
String s = "ABCDABD";
for(int i = 0;i<s.length();i++)
{
for(int j = i+1;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
{
count++;
System.out.println("repeated character is "+s.charAt(i));
}
}
}

System.out.println("count "+count);
}


}

Remove Specific character from string


 public static String removeCharInString (String string, char charToBeRemoved) {

        if (string == null)
             return "";

       
         StringBuilder strBuild = new StringBuilder ();

        for (int i = 0; i < string.length (); i++) {
            char chr = string.charAt (i);
            if (chr == charToBeRemoved)
                continue;
            strBuild.append (chr);
        }
        return strBuild.toString ();
    }
}

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...