Posted on

  • OOPs is object oriented programming using classes and objects.It simplifies the development of software by using few simple concepts.
  • Let us see each one of them in detail


  • Object is an entity that has state and behavior
  • whenever an object is created memory is allocated in the RAM i.e stack and heap memory.Stack has the name of the object and the methods and all variables of class for which object is created is stored in the heap .


  • It is a logical entity with collection of objects.
  • It has methods,objects,constructor,data members etc.


  • As the name indicates it is the concept of inheriting the properties.
  • We have 2 types of inheritance Single and Multiple

Single inheritance:

Let us take an example to understand single inheritance

class Animal{
void eat(){System.out.println(“eating…”);}
class Dog extends Animal{
void bark(){System.out.println(“barking…”);}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();

In the above example object d is created for the class Dog still it can access the methods of both class Dog and Animal because Dog extends Animal i.e it inherits the properties(methods) of Animal class.

Multiple inheritance:

Multiple inheritance is not supported in java .Let us undertand this with an example

class A{
void msg(){System.out.println(“Hello”);}
class B{
void msg(){System.out.println(“Welcome”);}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?

For the above program you get compile time error as it does not know which method it is supposed to access

Multiple inheritance in java is achieved using the concept of interface in java.This can be better understood by my previous post



  • Abstraction is a process of hiding the implementation details and showing only functionality to the user.

    Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don’t know the internal processing about the message delivery.

    Abstraction lets you focus on what the object does instead of how it does it.

    Ways to achieve Abstaction

    There are two ways to achieve abstraction in java

    1. Abstract class (0 to 100%)
    2. Interface (100%)
  • Detailed explanation of an Absratc class and interface is mentioned in my previous posts  https://tejaswikblog.wordpress.com/2017/07/20/javadifference-between-abstract-class-interface/


  • Encapsulation is the process of hiding data in single unit by making all the data members private and  use setter and getter methods to set and get the data in it.
  • The Java Bean class is the example of fully encapsulated class.
  • Let us understand this with a simple example

package com.teju;
public class Student{
private String name;

public String getName(){
return name;
public void setName(String name){

package com.teju;
class Test{
public static void main(String[] args){
Student s=new Student();


  • Polymorphism is concept of having a method in multiple forms
  • We have 2 types Static and dyanamic polymorphism
  • Static is compile time polymorphism i.e overloading a method

Method overloading:

  • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.There are two ways to overload the method in java
    1. By changing number of arguments
    2. By changing the data type
  • Let us see an example for method overloading by changing the number of arguments

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
class TestOverloading1{
public static void main(String[] args){

  • Example for method overloading by changing the data type

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
class TestOverloading2{
public static void main(String[] args){

Method overriding:

  • If the subclass method is with the same signature as in the parent class it is known as overriding the method in java.
  • The overriding method must have same name and same parameters as in the parent class
  • Let us see an example for method overriding

class Bank{
int getRateOfInterest(){return 0;}

class SBI extends Bank{
int getRateOfInterest(){return 8;}

class ICICI extends Bank{
int getRateOfInterest(){return 7;}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}

class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println(“SBI Rate of Interest: “+s.getRateOfInterest());
System.out.println(“ICICI Rate of Interest: “+i.getRateOfInterest());
System.out.println(“AXIS Rate of Interest: “+a.getRateOfInterest());

In the above example you can see that getRateOfInterest is overridden according to our requirement.












Difference b/w “Implements Runnable” & “Extends Thread”

Posted on Updated on

  • Instantiating a thread can be done either by implementing Runnable or extending Thread class,Let us see the major differences between both of them
  • As java does not support multiple inheritance you can extend only one class in java so once you extended Thread class you lost your chance and can not extend or inherit another class in java.
  • Extending a class is generally meant for adding new functionality or modifying or improving behaviors. If we are not making any modification on Thread than it is better to use Runnable interface instead.
  •  In “implements Runnable” , we are creating a different Runnable class for a specific behavior, It gives us the freedom to reuse the specific behavior whenever required.
  • “extends Thread”  contains both thread and specific behavior code. Hence once thread completes execution , it can not be restart again.
  • “implements Runnable” makes the code loosely-coupled and easier to read .
    Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
  • “extends Thread”  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.

Let us take an Example

class ImplementsRunnable implements Runnable {

private int counter = 0;

public void run() {
System.out.println(“ImplementsRunnable : Counter : ” + counter);

class ExtendsThread extends Thread {

private int counter = 0;

public void run() {
System.out.println(“ExtendsThread : Counter : ” + counter);

public class ThreadVsRunnable {

public static void main(String args[]) throws Exception {
//Multiple threads share the same object.
ImplementsRunnable rc = new ImplementsRunnable();
Thread t1 = new Thread(rc);
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t2 = new Thread(rc);
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t3 = new Thread(rc);

//Creating new instance for every thread access.
ExtendsThread tc1 = new ExtendsThread();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
ExtendsThread tc2 = new ExtendsThread();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
ExtendsThread tc3 = new ExtendsThread();



ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1

–>In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.

–>Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.

–>Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.


Difference b/w throw & throws

Posted on Updated on

  • Throw keyword is used to throw an exception.In order to throw user defined exceptions, throw keyword is being used.
  • You can also throw an already defined exception like Arithmetic and IO exception etc.
  • The throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw.
  • If a method is using throws clause along with few exceptions then this implicitly tells other methods that – “ If you call me, you must handle these exceptions that I throw”.

Example for throw:

try {
throw new Exception(“Error!!”);
} catch (Exception exp) {
System.out.println(“Error: “+exp.getMessage());

By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions. PFB the examples.

for e.g.

throw new ArithmeticException(“An integer should not be divided by zero!!”)
throw new IOException(“Connection failed!!”)

Exmple for throws:

public void sample() throws IOException{
//if (Error)
IOException e = new IOException();
throw e;
//More Statements

By using Throws keyword in java you can throw more than one exception.

for e.g

throws IOException, ArithmeticException, NullPointerException,

Difference b/w Hashcode() & Equals()

Posted on Updated on

  • Both Hashcode() and Equals() are methods of an object class
  • Hashcode increases the performance. For example, to compare two long strings with many number of characters, writing a for loop and comparing each character takes a very long time. Java adopts hashcode technique to compare i.e both strings are converted into integer values (known as hashcode) by Java and then these two integer values are compared. If both integers (compared with ==) are equal, then the two strings contain the same characters in the same order.
  • Equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false.

Let us take an example

String str = “abc”;
String str1 = new String(“abc”);


First if statement will return True and the second if statement will return False.

equals method compares the value in the String where as == compares the hashcodes

As we have used a new keyword a new hashcode is generated for str1 i.e the hashcodes do not match and the result is false.

Note: If 2 objects have the same hashCode() result does not mean that they are equal, but if two objects are equal then they must return the same hashCode() result.



How to convert a list object to a Map and iterate through Map

Posted on Updated on

Let us consider we have a list object named usersList, now our requirement is to convert this list object into map and iterate through the map.

Each List object is nothing but a row in the database table

We can understand this better with an example

for (Map<String, Object> map : usersList) {

JSONObject jsonObject = new JSONObject();

for (Map.Entry<String, Object> entry : map.entrySet()) {

String key = entry.getKey();

Object value = entry.getValue();


//product name is name of the coloumn in the database

jsonObject.put(“productName”, value);


else if(“CONTRACT_STATUS”.equals(key)){

jsonObject.put(“contractStatus”, value);


Here the iteration through the list means iterating through reach row


List—>L[0]—->Row—>C[0],V[0]  (coloumn,Value)



Iterating through map takes place by iterating through each column of database and its corresponding value for that particular row in the list







Java:Difference between HashMap & Hashtable

Posted on Updated on

  • HashMap and Hashtable both classes implements java.util.Map interface, however there are differences in the way they work and their usage
  • HashMap is non-synchronized. This means if it’s used in multithread environment then more than one thread can access and process the HashMap simultaneously. Where as Hashtable is synchronized. It ensures that no more than one thread can access the Hashtable at a given moment of time. The thread which works on Hashtable acquires a lock on it to make the other threads wait till its work gets completed.
  • HashMap allows one null key and any number of null values,Where as Hashtable doesn’t allow null keys and null values.
  •  HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts the mappings based on the ascending order of keys ,Where as Hashtable doesn’t  maintain the mappings in any particular order.
  • Another major difference between these 2 classes is iterator of HashMap is a fail fast where as Hashtable’s iterator is not.

Let us understand what is fail fast

In Simple words fail-fast means: When calling iterator.next(), if any modification has been made between the moment the iterator was created and the moment next() is called, a ConcurrentModificationException is immediately thrown.

  • Finally the usage of these collections can be decided based on the need of user i.e if we need a thread safe operation Hashtable can be used and for non thread environment HashMap
  • However we can achieve synchronization using concurrent HashMap as well

Let us see an example on How to synchronize HashMap explicitly

We use Collections.synchronizedMap(hmap) it returns a thread-safe map backed up by the specified HashMap.

package tejaswi.com;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
public class HashMapSyncExample {
public static void main(String args[]) {
HashMap<Integer, String> hmap= new HashMap<Integer, String>();
hmap.put(2, “Anil”);
hmap.put(44, “Ajit”);
hmap.put(1, “Brad”);
hmap.put(4, “Sachin”);
hmap.put(88, “XYZ”);
Map map= Collections.synchronizedMap(hmap);
Set set = map.entrySet();
Iterator i = set.iterator();
// Display elements
//Iterator must be in the synchronized block
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + “: “);



CSS: Pseudo-classes Vs Pseudo-elements

Posted on

The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.

A pseudo-class always consists of a “colon” (:) followed by the name of the pseudo-class and optionally by a value between parentheses.

Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). Pseudo-class names are case-insensitive. Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document.

Example –

a:hover {


Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element’s content. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content).

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element.

This :: notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.

Example –

p::first-line {
    color: #ff0000;
    font-variant: small-caps;