Java

OOPs CONCEPTS

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:

  • 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 .

CLASS:

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

INHERITANCE:

  • 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();
d.bark();
d.eat();
}}

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

https://tejaswikblog.wordpress.com/2017/07/20/javadifference-between-abstract-class-interface/

ABSTRACTION:

  • 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:

  • 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){
this.name=name
}
}

package com.teju;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setName(“Tejaswi”);
System.out.println(s.getName());
}
}

POLYMORPHISM:

  • 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){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

  • 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){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

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() {
counter++;
System.out.println(“ImplementsRunnable : Counter : ” + counter);
}
}

class ExtendsThread extends Thread {

private int counter = 0;

public void run() {
counter++;
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);
t1.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t2 = new Thread(rc);
t2.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t3 = new Thread(rc);
t3.start();

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

 

Output:

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:

….
static{
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{
//Statements
//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,
ArrayIndexOutOfBoundsException

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”);

if(str.equals(str1))
System.out.println(“true”);
else
System.out.println(“false”);
if(str==str1)
System.out.println(“true”);
else
System.out.println(“false”);

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();

if(“PRODUCT_NAME”.equals(key)){

//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

i.e

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

C[1],V[1]

C[3],V[3]

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

Map—>M[0]—–>coloumn–>C[0],V[0]

M[1]———————->C[1],V[1]

 

 

 

 

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();
synchronized(map){
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() + “: “);
System.out.println(me.getValue());
}
}
}
}

 

 

Java:Difference between Abstract class & Interface

Posted on Updated on

  • A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
  • The interface in java is a mechanism to achieve abstraction and multiple inheritance in Java.
  • An Abstract class can have both abstract and non abstract methods where as interface has only abstract methods
  • Abstract class does not support multiple inheritance.
  • Abstract class can have protected,public and public abstract methods,static,final or static final variables.
  • Interface can have only public abstract methods and static final (constant)variables by default.

Lets take an example-

abstract class Bank{    
abstract int getRateOfInterest(); 
// Concrete method
Public void getEmi(){  
System.out.println(“EMI”); 
}  
}    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 8;}    
}    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);    
b=new PNB();  
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);    
}}    

In the above example the abstract class has an abstract method which is implemented by an other class which extends it and it even has a concrete method.

Now let us see an example of Interface-

interface Bank{  
float rateOfInterest();  
}  
class SBI implements Bank{  
public float rateOfInterest(){return 9.15f;}  
}  
class PNB implements Bank{  
public float rateOfInterest(){return 9.7f;}  
}  
class TestInterface2{  
public static void main(String[] args){  
Bank b=new SBI();  
System.out.println(“ROI: “+b.rateOfInterest());  
}} 

->In this example you can see that the class which implements the interface has the implementation of the abstract method inside the interface.

Abstracted class achieves partial Abstraction where as Interface achieves 100% Abstraction.

Multiple Inheritance in Interface:

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

 

 multiple inheritance in java

Example of multiple Inheritance:

 

interface Printable{  
void print();  
}  
interface Showable{  
void show();  
}  
class A7 implements Printable,Showable{  
public void print(){System.out.println(“Hello”);}  
public void show(){System.out.println(“Welcome”);}  
  public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}  
In the above example u can see a class implements 2 interfaces.