Sunday, 22 April 2018

Why Java doesnot support multiple Inheritance?

When a class can extend more than one class then this capability is known as "multiple inheritance."

But java doesn't support multiple inheritance.
We are going to understand the reason behind java not supporting multiple inheritance.


Reason
The reason that Java's creators chose not to allow multiple inheritance is that it can become quite messy.
The problem is that if a class extended two other classes, and both super classes had, say, a doTask() method, which version of doTask() would the subclass inherit?
Ambiguity arises at this point.

This issue can lead to a scenario known as the "Deadly Diamond of Death," because of the shape of the class diagram that can be created in a multiple inheritance design.

The diamond is formed when classes B and C both extend A, and both B and C inherit a method from A. If class D extends both B and C, and both B and C have overridden the method in A, class D has, in theory, inherited two different implementations of the same method. Drawn as a class diagram, the shape of the four classes looks like a diamond.

Lets understand the same with the help of a diagram :
           
Why multiple inheritance not supported in java?

Wednesday, 14 March 2018

Can we call non-static method from static method in java?



Suppose we are writing a code where we intend to call any non-static method from within a method that is declared static

Since main() method is static so lets try to call any non static method or variable from within main method.

See the code snippet below where duplicateString  is being called within main method. 


Do you think this code snippet will compile and execute normally? 


package String_Programs;

public class DuplicateString {
      
       public void duplicateString(String str){
           System.out.print(str);
       }

       public static void main(String[] args) {
              duplicateString("This is This and That is This");

       }

}

OUTPUT:
Compile time error

In this case at you will get red underline under duplicateString called within main( ) method in eclipse. Bring your cursor on the method name and you will see this message - 'Cannot make a static reference to the non-static method duplicateString(String) from the type DuplicateString'



Calling non-static method from a static method directly is not allowed in java

How to solve the compile time error?

1. Declare the method to be called as static

You need to declare the duplicateString(String str) method static as shown below.
public static void duplicateString(String str)

Lets re-write our code again.



package String_Programs;

public class DuplicateString {
      
       public static void duplicateString(String str){
             
       }

       public static void main(String[] args) {
              duplicateString("This is This and That is This");

       }

}

OUTPUT:
This is This and That is This



2. Create the instance of the class and then call the method

We have shown an example in the below screenshot.


can we call non static method from static method in java by javaradar
















OUTPUT:

Friday, 2 February 2018

Abstract class Vs Interface in java

Abstract class and interface differ based on following parameters:


Methods

An abstract class can have both abstract methods and concrete methods.
An interface has all the methods as abstract. Methods in interface is 100% abstract.

Keyword used to declare

To declare abstract class use the keyword ‘abstract’. 
Example abstract class dummyClass{//abstract methods, methods}

To declare interface use the word ‘interface’. 
Example interface dummyInterface{//abstract method (s)}

Method declaration

In abstract class, to declare any method as abstract use of abstract keyword is mandatory.
In interface, to declare methods as abstract use of abstract keyword is optional. Methods in interface is by default abstract.

Inheritance Supported

Being a class, an abstract class cannot inherit multiple classes. It can only inherit one class.
An Interface can extend (or inherit) multiple interfaces.

What can be extended?

An abstract class can extend either normal class or abstract class.
Interface can extend only interface but not a class.

Variable type & Access modifier

An abstract class can have static, non-static, final or non-final variable with any access modifier.
An interface can only have public static final variable. In interface variable is constant.

Saturday, 13 January 2018

What are classes implementing Set interface?

We have three classes implementing set interface in java Collection framework hierarchy. Look at the diagram given below:

set interface java radar


From the diagram its clear that classes implementing set interface are:

1. Hashset

HashSet implements Set interface and extends AbstractSet class. It is part of java.util package.
HashSet contain unique elements only. If you add duplicate in it, previous value will be overwritten.
HashSet allows one null value only.
HashSet doesn’t maintain insertion order so when you retrieve elements from it they may be returned in random order. If you want to get element in order of insertion, use LinkedHashSet.

For more details about Treeset follow link Hashset in java


2. LinkedHashset

LinkedHashSet implements Set interface and extends HashSet class. It is part of java.util package.

LinkedHashSet is almost similar to HashSet except that it maintains the insertion order of the elements.

For more details about Treeset follow link LinkedHashset in java


3. Treeset

Treeset class implements set interface and extends AbstractSet class.
When storing element in treeset, it stores them in ascending order by default.

For more details about Treeset follow link Treeset in java

Tuesday, 9 January 2018

What are the classes implementing List interface?

We have three classes implementing list interface in java Collection framework hierarchy. Look at the diagram given below:

list interface java radar



From the diagram its clear that classes implementing list interface are:


1. ArrayList
  • Arraylist was added in Java 1.2 version.
  • Arraylist uses grow able array and thus can grow automatically.
  • Arraylist in java is not synchronized or thread safe.
  • As arraylist is non-synchronized so it is better performance wise as multiple threads can access the resources of arraylist at the same time simultaneously.
  • Arraylist's  iterator and list iterator are fail fast in nature.
  • Follow the link to read in detail about arraylist

Read: Why iterator on arraylist is fail fast in java?


2. LinkedList
  • Linkedlist was added in Java 1.2 version
  • Linkedlist in java is not synchronized
  • Linkedlist stores element in nodes which has capability to store element and its address.
  • Follow the link to read in detail about linkedlist

Read: Difference Arraylist vs Linkedlist


3. Vector
  • Vector is synchronized in nature. This is the major difference between array list and vector.
  • Vector is a legacy class and is not recommended to be used at present.
  • Follow the link to read in detail about vector


You may also like to read about:

Friday, 15 December 2017

Difference: Array vs Vector in java

Array and Vector differs based on the following parameters:

Basic:

Array in java is an object that contains data of homogeneous (similar) type.
example, int a[]={5,6,4,55}; //this array can only store int data type

Vector can store heterogeneous data types, if restriction is not put using generics concept. See the example below:

package string;

import java.util.Iterator;
import java.util.Vector;

public class splitDemo {

      public static void main(String[] args) {

            Vector v = new Vector();
            v.add(1);    //integer
            v.addElement("xyz");  //string
            v.add('s');  //char

            Iterator itr = v.iterator();
            while(itr.hasNext()){
                  System.out.println(itr.next());
            }
      }
}

OUTPUT:
1
xyz

In above example, you can see we have stored int, String and char objects in vector. 

Note: To make vector store homogeneous data type do the following:

Vector<String> v = new Vector<String>();

This will only allow storage of String object in vector.

Family:

Array does not belongs to Collection family. It is a primitive data type.

Vector implements List interface which is a part of collection hierarchy. Thus vector is a part of collection family.

Size:

Array needs to be assigned with the fixed size during initialization thus making it static in nature.

Vector resizes itself dynamically as per the need. Thus it is dynamic in nature.

Synchronized:

Array is non-synchronized in java.

Vector is synchronized in java.

Traversal:

Array can be traversed using for loop or enhanced for loop. It cannot use iterator or enumeration interface like vector or arraylist.

Vector can be traversed using iterator or enumeration interface

Declare/Instantiate/Initialization:

Array
Integer array
int a[]={5,6,4,55};

String array
String a[]={"Ajay","vijay","Rajesh","Mukesh"};

Similarly you can do for other data types like double, float, char, etc

Vector
Vector<String> vec=new Vector<String>();  //create vector
vec.add("Ajay");      //add element to vector
vec.add("vijay");




You may also like to read:

Wednesday, 13 December 2017

Difference: ArrayList vs CopyOnWriteArrayList in java

ArrayList and CopyOnWriteArrayList in java differ based on following parameters:

1. Inclusion in java

Arraylist was added in Java 1.2 version.

CopyOnWriteArrayList was added in Java 1.5 or Java 5.


2. Thread-safety

Arraylist in java is not synchronized thus is not at all thread safe.

CopyOnWriteArrayList is synchronized in nature. Thus it is thread safe and for the same reason only one thread can access the resources in this class at a time.


3. Performance

As arraylist is non-synchronized so it is better performance wise as multiple threads can access the resources of arraylist at the same time simultaneously.

Being synchronized means only one thread can have access to CopyOnWriteArrayList resources thus impacting its performance speed.


4. ConcurrentModificationException

Arraylist throws ConcurrentModificationException.

CopyOnWriteArrayList doesnot throw ConcurrentModificationException.


5. Fail fast or fail safe

 Arraylist's  iterator and list iterator are fail fast in nature.

CopyOnWriteArrayList iterator are fail safe in nature.



You may also like to read:


Tuesday, 12 December 2017

Which collection classes are synchronized or thread-safe?

Collection framework provides lots of classes to work with. Among them some are synchronized while other are non synchronized.

Recently one of my colleague was asked the same question in Deloitte interview. So you could also be asked the same in your next interview.

Lets come to the point.


All the synchronized collection classes are stated below:


1. Vector


Vector implements grow able array of objects. The elements in vector can be accessed using integer index just as we do in array.

Vector is synchronized so it should be used if thread-safety is concern of the developer. 
Due to synchronized nature, it does not allow multiple threads to access and modify its resources concurrently. If one thread has access to the vector then other thread wanting to access and operate on it must wait for its turn until the vector is released by the thread in action.

On other hand, this synchronized nature affects Vector’s performanceSo ArrayList is preferred over Vector if performance is to be considering factor.

To read about Vector in details. please follow the link Vector in java 

2. Hashtable

Hashtable extends Dictionary class and implements Map interface. Hashtable stores elements in key-value pair.

Hashtable is synchronized in nature.
Due to synchronized nature, it does not allow multiple threads to access and modify itself concurrently. 


Note: Both vector and hashtable are legacy classes and are not recommended for use.

3. CopyOnWriteArrayList

CopyOnWriteArrayList is a thread-safe variant of ArrayList which was included in java version 1.5 or java 5.
Here thread-safe indicates that this collection class is synchronized.



Advantage of synchronization:
If you don't want any resource to be shared simultaneously by multiple threads then mark the resource Synchronized. This makes sure that only one thread can access the resource at one instance and others has to wait for their turn in the queue.


Disadvantage of synchronization:
Because of being synchronized in nature these classes are slow in terms of performance. Reason is simple. Because of synchronization only single thread is able to access the class resource at a time. Other thread has to wait in queue till the first thread completes its task on the resource. Thus multitasking is not possible which in turn impacts speed.



You may also like to read:

Thursday, 2 November 2017

Can we keep more than one class in a single java source file?

We can have more than one class in a single java source file but with certain restriction.

Among multiple classes that you create in a single source file, only one can be public. Find an example given below,


package basic;

public class MultiplePublic {

      public static void main(String[] args) {
            //By java radar
            System.out.println("Executing main method");
            AnotherMultiplePublic amp = new AnotherMultiplePublic();
            amp.sampleMethod();
      }

}

class AnotherMultiplePublic {

      public void sampleMethod(){
            System.out.println("Print sample method");
      }

}

OUTPUT:
Executing main method

Print sample method


As shown above, write both classes in same source file with MultiplePublic class being public. As stated above if only one class is declared public then the code will run fine. So in this case the code will be executed without any glitches and produce output as stated under output header.

 Second Scenario:

Now, we will try to assign public access modifier to more than one class. Say two classes will have public modifier.

In this scenario, look at the below given screen-shot, to find out the result:

java radar examples
Multiple public class in same source file


See the red under line below AnotherMultiplePublic class in the screenshot above. Place the mouse cursor above it and you will see the error message:

                'The public type AnotherMultiplePublic must be defined in its own file'


Conclusion: That means in the same source file one cannot have more than one public class. 
Though there is no problem if you want to keep more than one class in same source file and you restrict the application of public modifier to only one class as we did in our first scenario.


Note for Readers: Please share your valuable thoughts on this post's question to help others.


You may also like to read:

Tuesday, 17 October 2017

Can we overload main() in java?


Yes, the main() method in java can be overloaded.

Given below is the sample code snippet where main() method has been overloaded twice. If you want you can experiment by overloading main() as per your choice and requirement.

To prove our point that main() can be overloaded, below code is sufficient. Have a look,

Source FileMainOverloading.java 

package basic;

public class MainOverloading {

      public static void main(String[] args) {
            System.out.println("Overloaded methods will not be executed here");

      }
     
      public static void main(int x){
            System.out.println("x="+ x);
            main(5,54);
      }
     
      public static void main(int a, int b){
            System.out.println("a="+ a);
            System.out.println("b="+ b);
      }

}


OUTPUT:
Overloaded methods will not be executed here 

---------------------------------------------------------------------------------------------------

In the above code snippet JVM searches for public static void main(String[] args) type signature as regular. And anything inside public static void main(String[] args)  will be executed first. So if you want your overloaded main() method to get executed, you need to call it from inside actual main() which is entry point for all java program. 

Given below is modified version of above code snippet. Here overloaded main() is executed. Have a look,
---------------------------------------------------------------------------------------------------

Source FileMainOverloading.java 

package basic;

public class MainOverloading {

      public static void main(String[] args) {
        main(1);       //calling overloaded main

      }
     
      public static void main(int x){
            System.out.println("x="x);
            main(5,54);
      }
     
      public static void main(int aint b){
            System.out.println("a="a);
            System.out.println("b="b);
      }

}


OUTPUT:
x=1    //output of main(int x)
a=5    //output of main(int aint b) 
b=54
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.