You are on page 1of 14

Interface:

It is blueprint of a class and 100% pure abstract class

Definition: Any service requirement specification or any contract between client and service provider or
100% pure abstract class is nothing but Interface.

Whenever we are implementing an interface for each and every method of the interface, we have to
provide implementation. Otherwise we have to declare class as abstract then next level child class is
responsible to provide implementation.

Every interface method is always public and abstract whether we are declaring or not. Hence we are
implementing interface method compulsory we should declare as public otherwise we will get compile
time error.

By default interface methods are public and abstract.

Interface interf{

Public void m1();


Public void m2;
}

abstract class ServiceProvider implements Interf


{

Public void m1(){


}

class SubServiceProvider extends ServiceProvider{

public void m2(){

A class can extend only one class at a time.


An Interface can extend any number of interfaces simultaneously.
We can achieve multiple inheritance using interface only in Java

Interface A{
}
Interface B{
}

Interface C extends A,B{


}
A class can implement any number of interfaces simultaneously

Every method present in interface are public and abstract always

To make interface methods available to every implementation of class


Implementation class is responsible to provide implementation so it is always public

Marker Interface:
If an interface doesn’t contain any methods and by implementing that interface if our objects
will get some ability such type of interfaces are called marker interfaces

Ex: Serilizable interface. Cloneable interface ,Random Access, SingleThread Model etc.

These are marked for some ability.

By implementing Serilizable interface our objects can be saved to the file and can travel across the
network.
BY Implementing Cloneable, interface our objects are in position to produce exactly duplicate cloned
objects.

Without having any method, how the objects will get ability in marker interfaces?

Internally JVM is responsible to provide require ability .

Why JVM is providing required ability in marker interface?

To reduce complexity of programming and to make java language as simple

Is it possible to create our own marker interface?

We can create our own marker intereface.


Java abstract VS interface
Abstract
Abstract class can have abstract and non-abstract methods
Abstract class doesn’t support multiple inheritances
Abstract class can have final, non-final, static and non-static variables

Interface
Interface can have only abstract methods. Since Java 8, it can have default and static
Methods also
Interface supports multiple inheritances
Interface has only static and final variables

Abstract classes cannot be instantiated, means we can't create an object to Abstract


class. We can create Subclasses to Abstract classes.

You can never instantiate an interface in java. You can, however, refer to an object that
implements an interface by the type of the interface. For example,

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)


{
A test = new B();
//A test = new A(); // wont compile
}

// Anonymous class
interface ProgrammerInterview {
public void read();
}

class Website {
ProgrammerInterview p = new ProgrammerInterview () {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
What is the difference between using == and .equals on a string?

Main difference between .equals() method and == operator is that one is method and other is
operator.
We can use == operators for reference comparison (address comparison) and .equals() method
for content comparison. In simple words, == checks if both objects point to the same memory
location whereas .equals() evaluates to the comparison of values in the objects.

What does it means to say that a String is immutable?

It means that once created, String object's char[] (its' containing value) is declared final and,
therefore, it can not be changed during runtime.

What is Mutable and Immutable Objects in Java?

 Mutable object:  You can change the states and fields after the object is created. For
examples: StringBuilder, java.util.Date and etc.

Immutable object – You cannot change anything after the object is created. For examples:
String, boxed primitive objects like Integer, Long and etc.

Ex:

class Mutable{

private int value;

public Mutable(int value) {


this.value = value;
}

//getter and setter for value


}

class Immutable {
private final int value;

public Immutable(int value) {


this.value = value;
}
//only getter
}

What is String .intern() ?

Java String intern () method is used for getting the string from the memory if it is already
present. This method ensures that all the same strings share the same memory.

For example, creating a string “hello” 10 times using intern() method would ensure that there
will be only one instance of “Hello” in the memory and all the 10 references point to the same
instance.

String s1=new String("hello");  

String s2="hello";  

String s3=s1.intern();//returns string from pool, now it will be same as s2  

System.out.println(s1==s2);//false because reference is different  

System.out.println(s2==s3);//true because reference is same  

What is the hashCode() and equals() used for?

Can you list 8 primitive types in java

Why would you not call abstract method in constructor?

What is the difference between iterator and enumeration in java?

Both are interfaces


Both allows you to traverse the Collections elements .
Enumeration

Using Enumeration, You can’t do any modifications to collection while traversing it.


Enumeration is introduced in JDK 1.0
Enumeration is used to traverse the legacy classes like Vector, Stack and HashTable.
Methods:  hasMoreElements() and nextElement()
Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified
while iterating
Enumeration is not safe and secured due to it’s fail-safe nature.

Iterator

Using Iterator, you can remove an element of the collection while traversing it.
Iterator is introduced from JDK 1.2
Iterator is used to iterate most of the classes in the collection framework
like ArrayList, HashSet, HashMap, LinkedList etc.
Methods: hasNext(), next() and remove()
Iterator is a fail-fast in nature. i.e. it throws ConcurrentModificationException  if a collection
is modified while iterating other than it’s own remove() method.
Iterator is safer and secured than Enumeration.

Do you agree we use composition over inheritance?

What are these final, finally and finalize keywords?

Final : It is a keyword Final class can't be inherited, final method can't be overridden and final
variable value can't be changed.
Finally  is a code block and is used to place important code, it will be executed whether
exception is handled or not.
Finalize is a method used to perform clean up processing just before object is garbage
collected.

What is garbage collector? How does it work?

Once an object is no longer referenced and therefore is not reachable by the application code,
the garbage collector removes it and reclaims the unused memory.

Autoboxing and Unboxing:

The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing and opposite operation is known as unboxing. This is the new feature of Java5

Ex: Auto boxing


 int a=50;  
  Integer a2=new Integer(a);//Boxing  
  Integer a3=5;//Boxing  
  System.out.println(a2+" "+a3);  

Ex: Unboxing
Integer i=new Integer(50);
int a=i;
System.out.println(a);

Array vs ArrayList in Java

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We
cannot change length of array once created in Java but ArrayList can be changed.

We cannot store primitives in ArrayList, it can only store objects. But array can contain both
primitives and objects in Java. Since Java 5, primitives are automatically converted in objects
which are known as auto-boxing.

HashSet VS TreeSet:

 HashSet gives better performance (faster) than Tree set for the operations like add, remove, contains,
size etc. 
HashSet does not maintain any order of elements while TreeSet elements are sorted in ascending order
by default.
HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException,
Why, because TreeSet uses compareTo() method to compare keys and compareTo() will
throw java.lang.NullPointerException.
HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java.

What are the access modifiers you know? What does each one do?
..
private variables, methods, constructors or inner classes are only visible to its' containing class
and its' methods.
protected can be used on variables, methods and constructors therefore allowing access only
to subclasses and classes that are inside the same package as protected members' class.
Default (no keyword is used) this modifier can be applied to classes, variables, constructors and
methods and allows access from classes and methods inside the same package.
public modifier is widely-used on classes, variables, constructors and methods to grant access
from any class and method anywhere.
Polymorphism in java is a concept by which we can perform a single action by different
ways.
Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime
polymorphism (dynamic binding). Method overloading is an example of static polymorphism,
while method overriding is an example of dynamic polymorphism.

Inheritance
can be defined as the process where one class acquires the properties (methods and fields) of
another. 
Inheritance uses the keyword extends to inherit the properties of a class.

What is the difference between DOM and SAX parser in Java?


Answer: DOM parser loads the whole XML into memory to create a tree-based DOM model.
This helps it quickly locate nodes and make a change in the structure of XML. SAX parser is an
event based parser and does not load the whole XML into memory.

For this reason, DOM is quicker than SAX but it needs more memory and is not fitting to parse
large XML files.

Security to save password and email in server over the network from mobile

Make email and password hashed

Once any string become hashed cant be retrieved .

To retrieve original string we need to do 2^160 attacks required if we use SH1


To retrieve original string we need to do 2^128 attacks required if we use MD5

We can hash the password by using MessageDigest class


And gives instane MessageDigest.getInstance(“SH1”)
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String hashKey = new String(Base64.encode(md.digest(), 0))

https://stackoverflow.com/questions/2948156/algorithm-complexity-security-md5-or-sha1
https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords
OAuth is a token based authorization method which uses an access token for interaction between user
and API. OAuth requires several steps and requests against the API to get your access token.

Security Tips for Android application :

Security is a major concern while developing mobile applications in today’s era. Here, I list down most
common things that developers should take care to protect the application.

Do not store private or sensitive data on SDCard. To store file on internal storage, use following methods
with private mode (Context.MODE_PRIVATE) openFileOutput & openFileInput. If you wants to store
data in sdcard then encrypt it. You will find many encryption libraries.

Restrict WebView to access local data. HTML5 and related technologies have become popular to
develop Mobile Web App or Hybrid app. For Hybrid uses WebView to display content from locally store
HTML or fetch HTML and other content from the server. Major security concerns for WebView are
setAllowFileAccess() and setAllowContentAccess() methods.

Restrict ContentProvider using exported flag set as false. It’s not the case that every time we develop
ContentProvider for data exchange between applications but ContentProvider can be developed for
single application or private.
<provider android:exported=”false” android:name=”ContentProvider”
android:authorities=”com.example.contentprovider” />

Do not pass sensitive information through Broadcast & Intent. Use LocalBroadcastManager for
broadcast data within process / app. LocalBroadcastManager is available in Support Library V4.
Don’t print sensitive information in LogCat. Information like web service URL, Username, password,
request, etc.

Don’t process malicious Intents. Before process Intent received in onReceive method of
BroadcastReceiver, validate callers package name, action and other information.
Protect your Service with Permission,To Use exposed flag as false When Service is developed for your
app only.

Remove unnecessary Log before publishing app.

Make sure that debug mode is false before publish APK.

For cross app functionality, validate calling application before response.

Encrypt sensitive data even if you store in internal storage.

Properly verify server certificate TLS/SSL for HTTPS web call.


Use NDK whenever you feel that information is not safe in Java code because It can decompile easily.
(i.e. Constant).

Use ProGuard that optimizes, shrinks and obfuscates your code.


Remove unwanted <user-permission> from AndroidManifest.xml

Loading classes.dex outside of application is major security risk. DexClassLoader allowed developer to
load classes.dex on demand.

Hope you take care of these security tips while developing an application. Your first and foremost
concern should always be the security of an application. To deliver best to the user and assure them of a
secure app developed is your responsibility as an Android developer. Develop the best, receive the best
response, get genuine and loyal users.

Strong passwords
Password strength checkers
Data encryption and Encryption keys protection
HTTPS
Using SSL security protocol over an ordinary HTTP connection helps to reduce the risk because
it implies that data would be encrypted.

Overloading vs Overriding in Java


https://beginnersbook.com/2014/01/difference-between-method-overloading-and-
overriding-in-java/
Overloading happens at compile-time while Overriding happens at runtime:
Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
Performance: Overloading gives better performance compared to overriding. The reason is that
the binding of overridden methods is being done at runtime.
Argument list should be different while doing method overloading. Argument list should be
same in method Overriding.
Return type of method does not matter in case of method overloading, it can be same or
different. However in case of method overriding the overriding method can have more specific
return type (refer this).
The most basic difference is that overloading is being done in the same class while for
overriding base and child classes are required. Overriding is all about giving a specific
implementation to the inherited method of parent class.
Synchrous vs ASynhronus

Synchrous means set of instructions which will get executed in sequence. There is an order here.

In asynchronous you can execute multiple things in parallel.

Threading is one fundamental way to perform asynchronous operations in Java. Thread, Runnable,
Executors are options available to perform asynchronous operations in Java.

In Java synchronized is the modifier applicable for blocks and methods. We can’t declare classes and
variables as synchronized.

If a method or block declared as synchronized then at a time only one thread can allowed to operate on
the given object.

The main advantage of synchronized keyword is we can resolve data inconsistency problems. But the


main disadvantage of synchronized keyword is it increases waiting time of thread and effects
performance of the system. Hence, if there is no specific requirement it is never recommended to use
synchronized keyword

Java Generics

http://www.waytoeasylearn.com/2016/08/generics-tutorial.html

http://www.waytoeasylearn.com/2016/06/core-java-tutorial-index.html

Android Notes from Professiona Text Book. Refer following pages

Page No 8,16,22,132,149,199 ,200,235,239,246,252


Code review tools

https://code.tutsplus.com/tutorials/ensure-high-quality-android-code-with-static-analysis-tools--cms-
28787 FindBugs checkstyle
Collections

HashMap : (Java 1.2)

It provides the basic implementation of Map interface of Java. It stores the data in
(Key,Value) pairs

HashMap is known as HashMap because it uses a technique Hashing.

Hashing is a technique of converting a large String to small String that represents same
String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap
internally. It internally uses link list to store key-value pairs.

public class HashMap extends AbstractMap implements


Map, Cloneable, Serializable

HashMap is unsynchronized i.e. multiple threads can access it simultaneously

Hashmap vs Hashtable

1. HashMap is not synchronized. It is not-thread safe and can’t be shared between many
threads without proper synchronization code whereas Hashtable is synchronized. It is
thread-safe and can be shared with many threads.

2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow
any null key or value.

3. HashMap is generally preferred over HashTable if thread synchronization is not needed

Why HashTable doesn’t allow null and HashMap does?

To successfully store and retrieve objects from a HashTable, the objects used as keys must
implement the hashCode method and the equals method. Since null is not an object, it can’t
implement these methods. HashMap is an advanced version and improvement on the
Hashtable. HashMap was created later.
https://www.geeksforgeeks.org/differences-between-hashmap-and-hashtable-in-java/

https://www.geeksforgeeks.org/hashmap-treemap-java/

https://www.geeksforgeeks.org/java-util-hashmap-in-java/

You might also like