Category Archives: Vs

Java: Arrays vs Collections


In Java, Arrays and Collections both are to deal with a group of objects but there are lots of differences in terms of data structure or performing operations.

Here are some most common differences:

Difference between Arrays & Collections

Arrays Collections
Arrays is having fixed-length.. Collections are growable in nature i.e increase or decrease.
Arrays are not recommended in terms of memory concerns. Collections use different data structures and recommended to use with respect to memory.
Arrays are used with respect to performance. Collections are not recommended to use with respect to performance.
Arrays can store only homogeneous (same type) of data. Collections can hold both homogeneous and heterogeneous elements.
Arrays do not have a single API. Collections having big list of methods.
Arrays can work with primitives and object types. Collections can hold only objects but not with primitive. If you pass as primitive internally convert to object.
See Also: Array & Arrays Class Examples See Also: Collection Framework and Examples

Java: ArrayList Vs Vector Class


java.util.ArrayList and java.util.Vector both implements List interface and maintains insertion order. It’s having many differences as below:

ArrayList vs Vector

ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increases 50% of the current array size if the number of elements exceeds its capacity. Vector increase 100% means doubles the array size when the total number of elements exceeds its capacity.
ArrayList is not a legacy class. It is introduced in JDK 1.2. Vector is a legacy class.
ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in the runnable or non-runnable state until the current thread releases the lock of the object.
ArrayList uses the Iterator interface to traverse the elements. A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
See Also:ArrayList Class See Also:Java: Vector Class

ArrayList Example: traversing by the iterator

import java.util.*;
class ArrayListExample{
 public static void main(String args[]){    

  //creating arraylist of String
  List al=new ArrayList();
 //adding objecta in arraylist
  al.add("Saurabh");
  al.add("Mahesh");
  al.add("Jonny");
  al.add("Anil");
  //traverse elements using Iterator
  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

Output

Saurabh
Mahesh
Jonny
Anil

Vector Example: Traversing by Enumerator

import java.util.*;
class VectorExample{
 public static void main(String args[]){
  Vector v=new Vector();//creating vector
  v.add("Umrao");//method of Collection
  v.addElement("Isha");//method of Vector
  v.addElement("Kush");
  //traverse elements using Enumeration
  Enumeration e=v.elements();
  while(e.hasMoreElements()){
   System.out.println(e.nextElement());
  }
 }
}

Output

Umrao
Isha
Kush

Java: String Vs StringBuffer Vs StringBuilder


String in Java

A String class represents an array of characters.

String Instance Creation
String instance can be created in two ways:

  • By assigning as Literals
    String title = "Facing Issues On IT";
  • By using the new keyword
    String title = new ("Facing Issues On IT");

Points to Remember for Java String

  • The string class is immutable in Java, so it’s easy to share it across different threads or functions.
  • When you create a String using double quotes, it first looks for the String with the same value in the JVM string pool, if match found it returns the reference else it creates the String object and then places it in the JVM String pool. This way JVM saves a lot of space by using the same String in different threads. But if a new operator is used, it will always explicitly creates a new String in the heap memory.
  • + operator overloading is used to concatenating two strings. Although internally it uses StringBuffer to perform this action.
  • String overrides equals() and hashCode() methods, two Strings are equal only if they have the same characters in the same order. Note that equals() method is case sensitive, so if you are not looking for case sensitive checks, you should use equalsIgnoreCase() method.
  • String value represents a string in the UTF-16 format.
  • String is a final/immutable class with all the fields as final except “private int hash”. This field contains the hashCode() function value and created only when the hashCode() method is called and then cached in this field. Furthermore, the hash is generated using the final fields of String class with some calculations, so every time hashCode() method is called, it will result in the same output. For the caller, it’s like calculations are happening every time but internally it’s cached in the hash field.

Why StringBuffer & StringBuilder?

The string class is immutable in java i.e whenever we do any manipulation in String like concatenation, substring, reverse, etc. always generate a new string and discard older String for garbage collection.

That’s the reason only Java introduced StringBuffer in JDK 1.4 and StringBuilder in JDK 1.5.

StringBuffer and StringBuilder are mutable objects and provide append(), insert(), delete() and substring() methods for String manipulation.

StringBuffer vs StringBuilder

Apart from similarities, Java StringBuffer and StringBuilder having differences:

  • StringBuffer is thread-safe because all of its methods are synchronized but the main disadvantage is performance.

Note: If you are working on a single-threaded environment go with StringBuilder and in a multithreaded environment use StringBuffer. In general scenarios for string manipulation, StringBuilder is better suited than StringBuffer because String buffer is synchronized.

String vs StringBuffer vs StringBuilder

String StringBuffer StringBuilder
Immutable Mutable Mutable
Legacy JDK 1.4 JDK 1.5
Thread Safe Thread Safe No Thread Safe
Synchronized Synchronized Not Synchronized
Performance slow in manipulation Performance slow in manipulation Performance faster in manipulation
String Concat (+) uses StringBuffer and StringBuilder internally NA NA
See Also: String Class Examples See Also: StringBuffer Examples See Also: StringBuilder Examples

Java: Abstract Class Vs Interface


Abstract class and interface in java used to provide abstraction but there are lots of differences:

Abstract Class Interface
Abstraction(0 to 100%) Abstraction(100%)
Abstract class implemented by keyword ‘extends Interface implemented by using keyword ‘implements
Abstract class also can not be instantiated but can be invoked if the main() method exists. Interface is completely abstract i.e can not create an instance of it.
Abstract class can have abstract and non-abstract methods. Interface methods are implicitly abstract and can not have an implementation(nobody)
Abstract class allowed final,non-final and static variables also. Interface allowed only final and static variables
Abstract class members are private, protected, etc. Interface members are public by default.
Abstract class can extend only one class but implements multiple java interfaces. Interface can extend other interfaces only.
Abstract class is fast compare to interface Interface is slow because it required extra indirection.
See Also: Java Abstract Class Examples See Also: Java Interface Examples

See Also:

Java: Method Overloading Vs Method Overriding


 

Method Overloading Method Overriding
Method Overloading is about the same function have different signatures. Method Overriding is about the same function, same signature but different classes connected through inheritance.
Method Overloading is a concept of compile-time polymorphism Method Overriding is a concept of run time polymorphism.
Method Overloading Example:

public class Employee
{
	public void print()
	{
	//some code here
	}
	public void print(String name)
	{
	//some code here
	}
	public void print(Employee employee)
	{
	//some code here
	}

}
Method Overriding Example:

public class Person
{
public void print(String name)
	{
	//some code here
	}
}
public class Employee extends Person
{
	@Override
	public void print(String name)
	{
	//some code here
	}

}
See Also: Java Method Overloading in Detail See Also: Java Method Overriding in Detail

See Also:

Java: Difference between HashMap and Hashtable


HashMap and Hashtable both implements Map interface and used to store data in key and value pairs. Both use hashing techniques to get unique keys.

Apart from some similarities, there are many differences between HashMap and Hashtable classes as follows:

java.util.HashMap java.util.HashTable
HashMap class introduced in JDK 1.2. Hashtable is a legacy class.
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
HashMap is traversed by Iterator. Hashtable is traversed by the Enumerator and Iterator.
Hashmap, Iterator is fail-fast. Hashtable, Enumerator is not fail-fast.
HashMap is not synchronized and not-thread safe. Hashtable is synchronized and thread safe.
HashMap can be synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can’t be unsynchronized.
HashMap class allows only one null key and multiple null values. Hashtable doesn’t allow any null key or value.
HashMap is fast. Hashtable is slow.

For more detail:

 

JDBC : Difference between executeQuery() Vs executeUpdate() Vs execute() method


executeQuery(), executeUpdate() and execute() are the methods of java.sql.Statement interface of JDBC API which are used to execute the SQL statements.

executeQuery() Vs executeUpdate() Vs execute()

executeQuery() executeUpdate() execute()
This method is use to execute the SQL statements which retrieve some data from database. This statement is used to execute SQL statements which update or modify database. This method can be use for any kind of SQL statements.
This method returns a ResultSet object which contains the result returned by query. This method returns an int value which represent number of rows affected by the query. This will be 0 for statement which are returning nothing. This method return a Boolean value. TRUE indicates that query returned a ResultSet object and FALSE indicate returned an int value or returned nothing.
This method is use to execute select query. This method is use to execute non select query. This method is use to execute select and non select queries.
Ex: SELECT Ex:
DML->INSERT , UPDATE and DELETEDDL-> CREATE, ALTER
Any Type of SQL statements.

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

Difference between Stored Procedure and functions


The differences between Stored procedures and Functions are given below:

See also :

Stored Procedure Function
Is used to perform business logic. Is used to perform calculation.
Must not have return type. Must have the return type.
May return zero or more values. May return only one values.
We can call function from procedure. Procedure can not be call from function.
Procedure supports input and output parameters Function supports only input parameters.
Exception handling using try/catch block can be used in stored procedures. Exception handling using try/catch can’t be used in user defined functions.

 

More on JDBC

Follow below links to know more posts on JDBC and solving JDBC issues :

JDBC: Difference between Statement, PreparedStatement and CallableSatement


JDBC API introduced statement, PreparedStatement and CallableStatemnet to execute different types of queries:

  1. Statement : Used to execute Normal SQL Queries.
  2. PreparedStatement: Used to execute dynamic or parameterized queries.
  3. CallableStatement: Used to execute StoredProcedure.

Statement Vs PreparedStatement Vs CallableStatement

Statement Prepared Statement Callable Statement
It is used to execute normal SQL queries. It is used to execute dynamic or parameterized SQL queries. It is used to execute Stored procedure or function.
It is proffered when particular query to be executed only once. It is proffered when particular query to be executed multiple times. It is proffered when stored procedure or functions to be executed.
You can no pass parameter to query by using this interface. You can pass parameter to query at run time by using this interface. You can pass three types of parameters by using this interface IN, OUT and IN OUT
This interface mainly used for DDL statements like CREATE, ALTER , DROP etc. This is used to be any kind of SQL queries which are used multiple times It is used with Stored Procedure and functions.
The performance of this interface is very low. The performance of this interface is better than query while using with multiple queries. Performance of this interface is very high because stored procedure execute on database end.
For More: Statement For More: Prepared Statement For More: Callable Interface

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :