Friday 28 June 2013

: StringBuffer and StringBuilder:

 StringBuffer and StringBuilder

The StringBuilder class was introduced with JDK 5.0. Essentially, a StringBuffer is a thread-safe version of StringBuilder. If you are only adding/removing characters from a single-thread, the StringBuilder implementation will be faster. If you are using multiple threads to add and remove characters, use StringBuffer

Difference between String and StringBuffer/StringBuilder in Java

Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.
By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.
So suppose you declare a String object:
String myString = “Hello”;
Next, you want to append “Guest” to the same String. What do you do?
myString = myString + ” Guest”;
When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.
Now isn’t that a performance issue?
Yes, it definitely is.
Then how do you make your string operations efficient?
By using StringBuffer or StringBuilder.
How would that help?
Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
Finally, whats the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.
Incase you do not know – Here’s how you use StringBuilder
A simple Example to demonstrate that String object is Immutable
Incase you still have any doubts regarding String or StringBuilder then do leave a comment. I’ll be more than eager to help you out.
Note: StringBuilder was introduced in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use StringBuffer)

================================================================================================================================================


Differences between String, StringBuffer and StringBuilder in Java

String in Java

Before looking difference between String and StringBuffer or StringBuilder let’s see some fundamental properties of String Class in Java

string and stringbuffer, string vs stringbuffer vs stringbuilder1) String is immutable in Java:  String is by design immutable in Java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads  without any extra synchronization.

2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Anyway comparing object with equality operator is bad practice in Java and you should always use equals method to check equality.

3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.

4) Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in String because same character array is shared between source String and SubString which can prevent source String from being garbage collected. See How SubString works in Java for more details.

5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. See  how to correctly override equals method in Java  to learn more about best practices on equals method. Another worth noting point is that equals method must be consistent with compareTo() method for String because SortedSet and SortedMap e.g. TreeMap uses compareTo method to compare String in Java.

7) toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation.

8) String is represented using UTF-16 format in Java.

9) In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.


Problem with String in Java

difference between String and StringBuffer and StringBuilder, string vs stringbuffer One of its biggest strength Immutability is also biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.


Differences between String and StringBuffer in Java

Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular Java interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.

Difference between StringBuilder and StringBuffer in Java

StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilder vs String.

Summary

In summary here are list of difference between StringBuffer, String and StringBuilder in Java :

1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
4) Use String if you require immutability, use Stringbuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety.

That's all on famous String vs StringBuffer or StringBuffer vs StringBuilder discussion. All these differences helps to avoid common coding mistake of using String in place of StringBuffer in many places. from Java 5 onwards either use + operator of StringBuilder for concatenating String in Java. 

================================================================================================================================================

The StringBuffer and StringBuilder classes are used when there is a necessity to make alot of modifications to Strings of characters.
Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out leaving behind alot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

Example:

public class Test{

    public static void main(String args[]){
       StringBuffer sBuffer = new StringBuffer(" test");
       sBuffer.append(" String Buffer");
       System.ou.println(sBuffer);  
   }
}
This would produce following result:
test String Buffer

StringBuffer Methods:

Here is the list of important methods supported by StringBuffer class:
SNMethods with Description
1public StringBuffer append(String s)
Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings etc.
2public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked the method.
3public delete(int start, int end)
Deletes the string starting from start index until end index.
4public insert(int offset, int i)
This method inserts an string s at the position mentioned by offset.
5replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with characters in the specified String.
Here is the list of other methods (Except set methods ) which are very similar to String class:
SNMethods with Description
1int capacity()
Returns the current capacity of the String buffer.
2char charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
3void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum.
4void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this string buffer into the destination character array dst.
5int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
6int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
7int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
8int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
9int length()
Returns the length (character count) of this string buffer.
10void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch.
11void setLength(int newLength)
Sets the length of this String buffer.
12CharSequence subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
13String substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.The substring begins at the specified index and extends to the end of the StringBuffer.
14String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.
15String toString()
Converts to a string representing the data in this string buffer.

======================================================================================
 Difference between StringBuilder & StringBuffer
Hello Everyone,
I wanted to know the difference between StringBuilder & StringBuffer classes and thier practical use. So,I wrote 2 code snippets in which I spawn 3 threads simultaneously which make use of StringBuilder & StringBuffer objects. When I run the code, i expect all the 3 threads to run simultaneously in case of StringBuilder & in synchronized manner in case of StringBuffer. But in BOTH the cases, they run in synchronized manner. then what is the use of StringBuffer class?:confused: (In case of String objects, all the 3 threads run simultaneeously). I will share the code snippets for your reference. Please also correct me if I'm wrong in understanding the concept of multi-threading itself. And please, also correct the code.:):)
Thanks In Advance!

// StringBuilder...

public class MultiTread implements Runnable{
private StringBuilder name;
public MultiTread(StringBuilder string){
name=string;
}

public void run(){
for(int i=0; i<=10; i++){
System.out.println(name.append(i));
}
}
public static void main(String[] args){
Thread th = new Thread(new MultiTread(new StringBuilder("thread1:")));
Thread th1 = new Thread(new MultiTread(new StringBuilder("thread2:")));
Thread th2 = new Thread(new MultiTread(new StringBuilder("thread3:")));

th.start();
th1.start();
th2.start();
}
}

..................

//StringBuffer...

public class MultiTreadBuf implements Runnable{
private StringBuffer name;
public MultiTreadBuf(StringBuffer string){
name=string;
}

public void run(){
for(int i=0; i<=10; i++){
System.out.println(name.append(i));
}
}
public static void main(String[] args){
Thread th = new Thread(new MultiTreadBuf(new StringBuffer("thread1:")));
Thread th1 = new Thread(new MultiTreadBuf(new StringBuffer("thread2:")));
Thread th2 = new Thread(new MultiTreadBuf(new StringBuffer("thread3:")));

th.start();
th1.start();
th2.start();
}
}

........

//String....

public class MuiltiTreadStr implements Runnable{
private String name;
public MuiltiTreadStr(String string){
name=string;
}

public void run(){
for(int i=0; i<=10; i++){
System.out.println(name+i);
}
}
public static void main(String[] args){
System.out.println("main begins...");
Thread th = new Thread(new MuiltiTreadStr("thread1:"));
Thread th1 = new Thread(new MuiltiTreadStr("thread2:"));
Thread th2 = new Thread(new MuiltiTreadStr("thread3:"));
System.out.println("spawning 3 threads...");
th.start();
th1.start();
th2.start();
System.out.println("main ends...");
}
}
=========================================================================================================

StringBuilder vs StringBuffer


StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
  • StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.

  • StringBuilder has better performance than StringBuffer under most circumstances.

  • Use the new StringBuilder wherever possible.
Other than that, the two classes are remarkably similar with compatible API. It seems the author just copied StringBuffer.java to StringBuilder.java, removing all occurrences of "synchronized". Here is a little trace left in StringBuilder.readObject method:
?
1
2
3
4
5
/**
* readObject is called to restore the state of the
* StringBuffer from a stream.
*/
private void readObject(java.io.ObjectInputStream s)
Note the above javadoc still refers to StringBuffer where it should be StringBuilder.
2 interesting methods in StringBuilder or StringBuffer are reverse() and equals(Object):
  • reverse() method modifies the current this StringBuilder/StringBuffer, and also returns itself. More details in Reverse a String with StringBuilder or StringBuffer

  • equals(Object) method is not implemented (overridden) in StringBuilder/StringBuffer. So comparing 2 instances of the same content will return false. Also there is no equalsIgnoreCase() method on StringBuilder/StringBuffer. However, toString() is implemented to return a string representing the data in this StringBuilder/StringBuffer.
    
 ================================================================================================================================================

List Of Interview Questions:

  1. Can Java thread object invoke start method twice?
  2. Give the list of Java Object class methods.
  3. Can we call servlet destory() from service()?
  4. Can we override static method?
  5. Can you list serialization methods?
  6. What is the difference between super() and this()?
  7. How to prevent a method from being overridden?
  8. Can we create abstract classes without any abstract methods?
  9. How to destroy the session in servlets?
  10. Can we have static methods in interface?
  11. What is transient variable?
  12. Incase, there is a return at the end of try block, will execute finally block?
  13. What is abstract class or abstract method?
  14. What is default value of a boolean?
  15. When to use LinkedList or ArrayList?
  16. What is daemon thread?
  17. Does each thread in java uses seperate stack?
  18. What is the difference between Enumeration and Iterator?
  19. Find out switch statement output.
  20. Does system.exit() in try block executes finally block?
  21. What is fail-fast in java?
  22. What is final, finally and finalize?
  23. In java, are true and false keywords?
  24. What are the different session tracking methods?
  25. What is the purpose of garbage collection?
  26. What are the types of ResultSet?
  27. What is difference between wait and sleep methods in java?
  28. What is servlet context?
  29. What happens if one of the members in a class does not implement Serializable interface?
  30. What is race condition?
  31. How to get current time in milli seconds?
  32. How can you convert Map to List?
  33. What is strictfp keyword?
  34. What is System.out in Java?
  35. What is difference between ServletOuptputStream and PrintWriter?
  36. What is java static import?
  37. When to use String and StringBuffer?
  38. What is difference between StringBuffer and StringBuilder?
  39. What is wrapper class in java?
  40. Is Iterator a Class?
  41. What is java classpath?
  42. Can a class in java be private?
  43. Is null a keyword in java?
  44. What is the initial state of a thread when it is started?
  45. What is the super class for Exception and Error?
  46. What is Class.forName()?
  47. Can interface be final?
  48. What is the difference between exception and error?
  49. What is default value of a local variables?
  50. What is local class in java?
  51. Can we initialise uninitialized final variable?
  52. Can we declare abstract method as final?
  53. Can we have finally block without catch block?
  54. What is pass by value and pass by reference?
  55. Can we declare main method as private?
  56. What is the difference between preemptive scheduling and time slicing?
  57. Can non-static member classes (Local classes) have static members?
  58. What are the environment variables do we neet to set to run Java?
  59. Can you serialize static fields of a class?
  60. What is the difference between declaring a variable and defining a variable?
  61. Where can we use serialization?
  62. What modifiers are allowed for methods in an Interface?
  63. What is the purpose of Runtime and System class?
  64. Which one is faster? ArrayList or Vector? Why?
  65. What is the difference between static synchronized and synchronized methods?
  66. What is the order of catch blocks when catching more than one exception?
  67. What is the difference between the prefix and postfix forms of the increment(++) operator?
  68. What is hashCode?
  69. What is the difference between Hashtable and HashMap?
  70. What are the restrictions when overriding a method?
  71. What is the use of assert keyword?
  72. What is adapter class?
  73. What is difference between break, continue and return statements?
  74. What is the difference between while and do-while statements?
  75. When does the compiler provides the default constructor?
  76. String Sample Code Examples

MostImp Question :

28-06-2013

  1. Difference between overloading and overridin ?
  2. Difference between Vector and ArrayList ?
  3. Difference between Set and List ?
  4. How to make a class immutable in java?
  5. What is generic in java ?
  6. What about hashCode ? Detailed description of HashCode ?
  7. Types of statement in java ?
  8. How to load a class in java ? Define the complete Code ? Class.forName("sun.jdbc.odbc.JdbcOdbc");?Types of drivers in JDBC ?
  9. How to use callable Statement in java ?
  10. What id DI in Spring ?
  11. Types of Dependency Injection in Spring ?
  12. Why spring is lightWeight ?
  13. What is the Hibernate configuration file ?
  14. Hibernate ONE-TO-ONE mapping configuration ?

List Of Interview Questions:

  1. Can Java thread object invoke start method twice?
  2. Give the list of Java Object class methods.
  3. Can we call servlet destory() from service()?
  4. Can we override static method?
  5. Can you list serialization methods?
  6. What is the difference between super() and this()?
  7. How to prevent a method from being overridden?
  8. Can we create abstract classes without any abstract methods?
  9. How to destroy the session in servlets?
  10. Can we have static methods in interface?
  11. What is transient variable?
  12. Incase, there is a return at the end of try block, will execute finally block?
  13. What is abstract class or abstract method?
  14. What is default value of a boolean?
  15. When to use LinkedList or ArrayList?
  16. What is daemon thread?
  17. Does each thread in java uses seperate stack?
  18. What is the difference between Enumeration and Iterator?
  19. Find out switch statement output.
  20. Does system.exit() in try block executes finally block?
  21. What is fail-fast in java?
  22. What is final, finally and finalize?
  23. In java, are true and false keywords?
  24. What are the different session tracking methods?
  25. What is the purpose of garbage collection?
  26. What are the types of ResultSet?
  27. What is difference between wait and sleep methods in java?
  28. What is servlet context?
  29. What happens if one of the members in a class does not implement Serializable interface?
  30. What is race condition?
  31. How to get current time in milli seconds?
  32. How can you convert Map to List?
  33. What is strictfp keyword?
  34. What is System.out in Java?
  35. What is difference between ServletOuptputStream and PrintWriter?
  36. What is java static import?
  37. When to use String and StringBuffer?
  38. What is difference between StringBuffer and StringBuilder?
  39. What is wrapper class in java?
  40. Is Iterator a Class?
  41. What is java classpath?
  42. Can a class in java be private?
  43. Is null a keyword in java?
  44. What is the initial state of a thread when it is started?
  45. What is the super class for Exception and Error?
  46. What is Class.forName()?
  47. Can interface be final?
  48. What is the difference between exception and error?
  49. What is default value of a local variables?
  50. What is local class in java?
  51. Can we initialise uninitialized final variable?
  52. Can we declare abstract method as final?
  53. Can we have finally block without catch block?
  54. What is pass by value and pass by reference?
  55. Can we declare main method as private?
  56. What is the difference between preemptive scheduling and time slicing?
  57. Can non-static member classes (Local classes) have static members?
  58. What are the environment variables do we neet to set to run Java?
  59. Can you serialize static fields of a class?
  60. What is the difference between declaring a variable and defining a variable?
  61. Where can we use serialization?
  62. What modifiers are allowed for methods in an Interface?
  63. What is the purpose of Runtime and System class?
  64. Which one is faster? ArrayList or Vector? Why?
  65. What is the difference between static synchronized and synchronized methods?
  66. What is the order of catch blocks when catching more than one exception?
  67. What is the difference between the prefix and postfix forms of the increment(++) operator?
  68. What is hashCode?
  69. What is the difference between Hashtable and HashMap?
  70. What are the restrictions when overriding a method?
  71. What is the use of assert keyword?
  72. What is adapter class?
  73. What is difference between break, continue and return statements?
  74. What is the difference between while and do-while statements?
  75. When does the compiler provides the default constructor?
  76. List Of All Interview Programs:

    1. Find out duplicate number between 1 to N numbers.
    2. Find out middle index where sum of both ends are equal.
    3. Write a singleton class.
    4. Write a program to create deadlock between two threads.
    5. Write a program to reverse a string using recursive algorithm.
    6. Write a program to reverse a number.
    7. Write a program to convert decimal number to binary format.
    8. Write a program to find perfect number or not.
    9. Write a program to implement ArrayList.
    10. Write a program to find maximum repeated words from a file.
    11. Wrie a program to find out duplicate characters in a string.
    12. Write a program to find top two maximum numbers in a array.
    13. Write a program to sort a map by value.
    14. Write a program to find common elements between two arrays.
    15. How to swap two numbers without using temporary variable?
    16. Write a program to print fibonacci series.
    17. Write a program to find sum of each digit in the given number using recursion.
    18. Write a program to check the given number is a prime number or not?
    19. Write a program to find the given number is Armstrong number or not?
    20. Write a program to convert binary to decimal number.
    21. Write a program to check the given number is binary number or not?
    22. Write a program for Bubble Sort in java.
    23. Write a program for Insertion Sort in java.
    24. Write a program to implement hashcode and equals.
    25. How to get distinct elements from an array by avoiding duplicate elements?
    26. Write a program to get distinct word list from the given file.
    27. Write a program to get a line with max word count from the given file.
    28. Write a program to convert string to number without using Integer.parseInt() method.
    29. Write a program to find two lines with max characters in descending order.
    30. Write a program to find the sum of the first 1000 prime numbers.
  77. Java Search Algorithms

    Search algorithm is an algorithm for finding an item with specified properties among a collection of items. The items may be stored individually as records in a database or may be elements of a search space defined by a mathematical formula or procedure, such as the roots of an equation with integer variables or a combination of the two.
    You can find examples for different types of search algorithms here.

    Java Search Algorithms Examples

    1. Write a program to implement Linear search or Sequential search algorithm.
    2. Implement Binary search in java using divide and conquer technique.
    3. Implement Binary search in java using recursive algorithm.

Overload Vs Overriding.

Overload Vs Overriding.

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.
Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

Overloading is defining functions that have similar signatures, yet have different parameters. 

Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that function.

Overriding
Overloading
Methods name and signatures must be same.
Having same method name with different
Signatures.
Overriding is the concept of runtime polymorphism
Overloading is the concept of compile time polymorphism
When a function of base class is re-defined in the derived class called as Overriding
Two functions having same name and return type, but with different type and/or number of arguments is called as Overloading
It needs inheritance.
It doesn't need inheritance.
Method should have same data type.
Method can have different data types
Method should be public.
Method can be different access specifies

Example

Overriding

public class MyBaseClass
{
    public virtual void MyMethod()
    {
        Console.Write("My BaseClass Method");

    }
}
public class MyDerivedClass : MyBaseClass
{
    public override void MyMethod()
    {
        Console.Write("My DerivedClass Method");

    }
}

Overloading 

int add(int a, int b)
int add(float a , float b)

Introduction

Q: Method Overloading ?
Ans:
Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or anoter one in base class and another in derived class.

class Person
{
private String firstName;
private String lastName;
Person()
{
this.firstName = "";
this.lastName = "";
}
Person(String FirstName)
{
this.firstName = FirstName;
this.lastName = "";
}
Person(String FirstName, String LastName)
{
this.firstName = FirstName;
this.lastName = LastName;
}
} Calling Overloaded Methods.
Person(); // as a constructor and call method without parameter
Person(userFirstName); // as a constructor and call method with one parameter(like User's first Name)
Person(userFirstName,userLastName); // as a constructor and call method with one parameter(like User's first Name)
When to use Method Overloading?
Generally, you should consider overloading a method when you have required same reason that take different signatures, but conceptually do the same thing.
-----------------------------------------------------------------------------------------
Q: Method Overriding?
Ans:
Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class.

Overriding methods
Overriding method definitions
In a derived class, if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the base class, this new definition replaces the old definition of the method.
Explanation
A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding.
Step 1 In this example we will define a base class called Circle
class Circle
{

//declaring the instance variable
protected double radius;
public Circle(double radius)
{
      this.radius = radius;
}
// other method definitions here
public double getArea()
{
      return Math.PI*radius*radius;
}//this method returns the area of the circle

}// end of class circle
When the getArea method is invoked from an instance of the Circle class, the method returns the area of the circle.
Step 2 The next step is to define a subclass to override the getArea() method in the Circle class. The derived class will be the Cylinder class. The getArea() method in the Circle class computes the area of a circle, while the getArea method in the Cylinder class computes the surface area of a cylinder.
The Cylinder class is defined below.
class Cylinder extends Circle
{

//declaring the instance variable
protected double length;
public Cylinder(double radius, double length)
{
     super(radius);
     this.length = length;
}
// other method definitions here

public double getArea()
{
     // method overriden here
     return 2*super.getArea()+2*Math.PI*radius*length;
}//this method returns the cylinder surface area
}// end of class Cylinder

When the overriden method (getArea) is invoked for an object of the Cylinder class, the new definition of the method is called and not the old definition from the superclass(Circle).



Example code
This is the code to instantiate the above two classes
Circle myCircle;
myCircle = new Circle(1.20);
Cylinder myCylinder;
myCylinder = new Cylinder(1.20,2.50);

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

In Java, what’s the difference between method overloading and method overriding?

 


The difference between overriding and overloading in Java is a common source of confusion – but it is fairly simple to understand. Let’s start the discussion by talking more about method overloading. Overloading in Java can occur when two or more methods in the same class share the same name or even if a child class shares a method with the same name as one of it’s parent classes. But, in order to actually have overloaded methods, the methods not only have to have the same name, but there are other conditions that must be satisfied – read below to see what those conditions are.

Suppose we have a class called TestClass which has 2 methods, and both methods have the same name – let’s say that name is “someMethod” – this would be considered to be method overloading if at least one of these 2 things is true:
1.) The number of parameters is different for the methods   
2.) The parameter types are different.  

How to NOT overload methods:

It’s important to understand that method overloading is NOT something you can accomplish by doing these 2 things:
1.  Changing the return type of the method   
2.  Changing the name of the method parameters, but 
    not changing the parameter types.  
Confused? Well, here are some very helpful examples of where overloading would be both valid and invalid:

Examples of Method Overloading in Java – both valid and invalid:

//compiler error - can't overload based on the   
//type returned -
//(one method returns int, the other returns a float):    

int changeDate(int Year) ;  
float changeDate (int Year);    

//compiler error - can't overload by changing just 
//the name of the parameter (from Month to Year):    

int changeDate(int Month) ;  
float changeDate(int Year);    

//valid case of overloading, since there is an   
//extra parameter in the first method:        

int changeDate(int Year, int Month) ;  
int changeDate(int Year);    

//also a valid case of overloading, since the   
//parameters are of different types:    

int changeDate(float Year) ;  
int changeDate(int Year);  
Subscribe to our newsletter for more free interview questions.

What about method overriding?

Overriding methods is completely different from overloading methods. If a derived class requires a different definition for an inherited method, then that method can be redefined in the derived class. This would be considered overriding. An overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method.
Let’s summarize the differences between overloading and overriding. When overloading, one must change either the type or the number of parameters for a method that belongs to the same class. But, overriding a method means that a method inherited from a base class is what’s being changed.
--------------------------------------------------------------------------------------------
Difference Between Method Overloading and Method Overriding
Method Overloading
Method Overriding
Definition
In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order. In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.
Meaning
Method Overloading means more than one method shares the same name in the class but having different signature. Method Overriding means method of base class is re-defined in the derived class having same signature.
Behavior
Method Overloading is to “add” or “extend” more to method’s behavior. Method Overriding is to “Change” existing behavior of method.
Overloading and Overriding is a kind of polymorphism.Polymorphism means “one name, many forms”.
Polymorphism
It is a compile time polymorphism. It is a run time polymorphism.
Inheritance It may or may not need inheritance in Method Overloading. It always requires inheritance in Method Overriding.
Signature In Method Overloading, methods must have different signature. In Method Overriding, methods must have same signature.
Relationship of Methods In Method Overloading, relationship is there between methods of same class. In Method Overriding, relationship is there between methods of super class and sub class.
Criteria
In Method Overloading, methods have same name different signatures but in the same class. In Method Overriding, methods have same name and same signature but in the different class.
No. of Classes
Method Overloading does not require more than one class for overloading. Method Overriding requires at least two classes for overriding.
Example
Class Add
{
   int sum(int a, int b)
   {
     return a + b;
   }
  int sum(int a)
  {
    return a + 10;
   }
}
Class A  // Super Class
{
  void display(int num)
  {
     print num ;
   }
}
//Class B inherits Class A
Class B //Sub Class
{
  void display(int num)
  {
     print num ;
   }
}



====================================================================================================

What is Method Overloading and Overriding in Java - Example Differences Tutorial

What is method overloading and overriding in Java
Method overloading and method overriding in Java is two important concept in Java which allows Java programmer to declare method with same name but different behavior. Method overloading and method overriding is based on polymorphism in Java. In case of method overloading, method with same name co-exists in same class but they must have different method signature, while in case of method overriding, method with same name is declared in derived class or sub class.Method overloading is resolved using static binding in Java at compile time while method overriding is resolved using dynamic binding in Java at runtime. In short When you overload a method in Java its method signature got changed while in case of overriding method signature remains same but a method can only be overridden in sub class. Since Java supports polymorphism and resolve object at run-time it is capable to call overridden method in Java. By the way difference between method overloading and overriding is also one of the popular Java design question and appear in almost all levels of  Java interviews.

What is method overloading and overriding in Java?

In this Java tutorial we will see how Java allows you to create two methods of same name by using method overloading and method overriding. We will also touch base on how methods are bonded or called by Compiler and Java Virtual Machine and finally we will answer of popular interview questions difference between method overloading and method overriding in Java. This article is in my series of Java article which discusses about Interview e.g. Difference between Synchronized Collection and Concurrent Collection or How to Stop Thread in Java. Please let me know if you have some other interview questions and you are looking answer or reason for that and here in Javarevisited we will try to find and discuss those interview questions.

How to overload a method in Java

What is method overridding and overloading in Java - Differences , Example If you have two methods with same name in one Java class with different method signature than its called overloaded method in Java. Generally overloaded method in Java has different set of arguments to perform something based on different number of input. You can also overload constructor in Java, which we will see in following example of method overloading in Java. Binding of overloading method occurs during compile time and overloaded calls resolved using static binding. To overload a Java method just changes its signature. Just remember in order to change signature you either need to change number of argument, type of argument or order of argument in Java if they are of different types. Since return type is not part of method signature simply changing return type will result in duplicate method and you will get compile time error in Java. In our example of Loan and PersonalLoan class, createLoan method is overloaded. Since you have two crateLoan() method with one takes one argument lender while other take two argument both lender and interestRate. Remember you can overload static method in Java, you can also overload private and final method in Java but you can not override them.

How to override a method in Java

In order to override a Java method, you need to create a child class which extends parent. Overridden method in Java also shares same name as original method in Java but can only be overridden in sub class. Original method has to be defined inside interface or base class, which can be abstract as well. When you override a method in Java its signature remains exactly same including return type. JVM resolves correct overridden method based upon object at run-time by using dynamic binding in Java. For example in our case when we call personalLoan.toString() method even though personalLoan object is of type Loan actual method called would be from PersonalLoan class because object referenced by personalLoan variable is of type PersonalLoan(). This is very useful technique to modify behavior of a function in Java based on different implementation. Equals, hashcode and compareTo methods are classic example of overridden methods in Java.
Another important point is that you can not override static method in Java because they are associated with Class rather than object and resolved and bonded during compile time and that’s the reason you cannot override main method in Java. Similar to static, private and final methods are also not overridden in Java. By the way, as part of overriding best practice, always use @Override annotation, while overriding method from an abstract class or interface.


Rules of Method Overriding in Java
Following are rules of method overriding in java which must be followed while overriding any method. as stated earlier private, static and final method can not be overridden.
  1. Method signature must be same including return type, number of method parameters, type of parameters and order of parameters
  2. Overriding method can not throw higher Exception than original or overridden method. means if original method throws IOException than overriding method can not throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
  3. Overriding method can not reduce accessibility of overridden method , means if original or overridden method is public than overriding method can not make it protected.

Difference between method overloading vs overriding in Java

Overloading vs Overriding in Java is one of the popular java interview questions at many companies and asked at different levels of programmers. Here are some of the silent difference between overloading and overriding in Java. Though more important is to understand how to use both overloading and overriding, these difference are good from interview perspective and gives some basic idea as well:
1) First and most important difference between method overloading and overriding is that, In case of method overloading in Java, Signature of method changes while in case of method overriding it remain same.
2) Second major difference between method overloading vs overriding in Java is that You can overload method in one class but overriding can only be done on subclass.
3) You can not override static, final and private method in Java but you can overload static, final or private method in Java.

4) Overloaded method in Java is bonded by static binding and overridden methods are subject to dynamic binding.
5) Private and final method can also be not overridden in Java.

Exceptions handling while overloading and overriding method in Java

While overriding a method it can only throw checked exception declared by by overridden method or any subclass of it, means if overridden method throws IOExcpetion than overriding method can throw sub classes of IOExcpetion e.g. FileNotFoundException but not wider exception e.g. Exception or Throwable. This restriction is only for checked Exception for RuntimeException you can throw any RuntimeException. Overloaded method in Java doesn’t have such restriction and you are free to modify throws clause as per your need.

Example of method overloading and overriding in Java

Here is an example of both method overloading and method overriding in Java. In order to explain the concept we have create two classes Loan and PersonalLoan. createLoan() method is overloaded as it has different version with different signature, while toString() method which is original declared in Object class is overridden in both Loan and PersonalLoan class.

public class OverloadingOverridingTest {
    public static void main(String[] args) {
        // Example of method overloading in Java
        Loan cheapLoan = Loan.createLoan("HSBC");
        Loan veryCheapLoan = Loan.createLoan("Citibank");
        // Example of method overriding in Java
        Loan personalLoan = new PersonalLoan();
        personalLoan.toString();
    }
}
public class Loan {
    private double interestRate;
    private String customer;
    private String lender;
    public static Loan createLoan(String lender) {
        Loan loan = new Loan();
        loan.lender = lender;
        return loan;
    }
    public static Loan createLoan(String lender, double interestRate) {
        Loan loan = new Loan();
        loan.lender = lender;
        loan.interestRate = interestRate;
        return loan;
    }
    @Override
    public String toString() {
        return "This is Loan by Citibank";
    }
}
public class PersonalLoan extends Loan {
    @Override
    public String toString() {
        return "This is Personal Loan by Citibank";
    }
}
Summary
1) In case of method overloading method signature gets changed while in case of overriding signature remains same.
2) Return type is not part of method signature in Java.
3) Overloaded method can be subject to compile time binding but overridden method can only be bind at run-time.
4) Both overloaded and overridden method has same name in Java.
5) Static method can not be overridden in Java.
6) Since private method is also not visible outside of class, it can not be overridden and method binding happens during compile time.
7) From Java5 onwards you can use annotation in Java to declare overridden method just like we did with @override. @override annotation allows compiler, IDE like NetBeans and Eclipse to cross verify or check if this method is really overrides super class method or not.

Update: One of my reader Rajeev makes an interesting comment about one change related to return type of overriding method from Java 5 onwards, which enable to use subtype of return type of overridden method. This is really useful, when original method returns a general type like java.lang.Object. If you are overriding clone() method in Java then you can use this feature to return actual type, instead of returning java.lang.Object and can save caller from type-casting cloned object.  Here is the actual comment from Rajeev:
Hi Javin,I visit your blog regularly and I found that you missed covariant return which is added in Java 5 in the case of method overriding. When a subclass wants to change the method implementation of an inherited method (an override), the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (super class) method. Let's look at a covariant return in action:
class Alpha {
    Alpha doStuff(char c) {
        return new Alpha();
    }
}
class Beta extends Alpha {
    Beta doStuff(char c) { // legal override in Java 1.5
        return new Beta();
    }
}
AS  I said one of the good example of this is overriding clone method and using return type as Actual type instead of java.lang.Object, which is suggested by Joshua Bloch in Effective Java as well. This in in-fact one of the Java best practices while implementing clone method in Java. By the way don't forget to follow these Java overloading best practices, when doing it in your project.