Java Tutorial
Java Tutorial
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.
Interface interf{
Interface A{
}
Interface B{
}
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.
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?
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
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
{
}
// 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.
It means that once created, String object's char[] (its' containing value) is declared final and,
therefore, it can not be changed during runtime.
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{
class Immutable {
private final int value;
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
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.
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.
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.
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: Unboxing
Integer i=new Integer(50);
int a=i;
System.out.println(a);
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.
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
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 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.
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.
Synchrous means set of instructions which will get executed in sequence. There is an order here.
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.
Java Generics
http://www.waytoeasylearn.com/2016/08/generics-tutorial.html
http://www.waytoeasylearn.com/2016/06/core-java-tutorial-index.html
https://code.tutsplus.com/tutorials/ensure-high-quality-android-code-with-static-analysis-tools--cms-
28787 FindBugs checkstyle
Collections
It provides the basic implementation of Map interface of Java. It stores the data in
(Key,Value) pairs
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.
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.
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/