List of Five Checked and Unchecked Exceptions
List of Five Checked and Unchecked Exceptions
ClassNotFoundException
InterruptedException
InstantiationException
IOException
SQLException
IllegalAccessException
FileNotFoundException
ClassNotFound Exception:
Unchecked Exception:
Unchecked exceptions are not checked at compile time.
It means if your program is throwing an unchecked exception and
even if you didn’t handle/declare that exception, the program won’t
give a compilation error.
Most of the times these exception occurs due to the bad data
provided by user during the user-program interaction.
ArithmeticException.
ClassCastException.
NullPointerException.
ArrayIndexOutOfBoundsException.
NegativeArraySizeException.
ArrayStoreException.
IllegalThreadStateException.
SecurityException, etc
EX:
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException
*/
int res=num1/num2;
System.out.println(res);
}}
2.ClassnotFound And No ClassDefFound Exception in java
ClassNotFoundException
It occurs when an application tries to load a class at run time which is not updated in the classpath.
It is thrown by the application itself. It is thrown by the methods like Class.forName(), loadClass() and findSystemClass().
NoClassDefFoundError
It occurs when java runtime system doesn’t find a class definition, which is present at compile time, but missing at run time.
class A
{
// some code
}
public class B
{
public static void main(String[] args)
{
A a = new A();
}
}
3)ArrayList and Vector in Java
2) ArrayList increments 50% of current array size if the number of elements exceeds from
its capacity.
EX:import java.util.*;
class TestArrayList21{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
al.add("James");
al.add("Andy");
//traversing elements using Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Sonoo
Michael
James
Andy
VECTOR:
Vector is synchronized.
Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.
Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or
non-runnable state until current thread releases the lock of the object.
EX:
import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Output:
umesh
irfan
kumar
4. Hashset and Treeset in java
HashSet :
EX:
import java.util.HashSet;
class HashSetDemo {
public static void main(String[] args)
{
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
// Duplicate removed
hset.add("geeks");
Output:
TreeSet contains:
contribute
for
geeks
practice
Treeset in java
TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet.
But TreeSet keeps sorted data.
Also, it supports operations like higher() (Returns least higher element), floor(),
ceiling(), etc.
These operations are also O(Log n) in TreeSet and not supported in HashSet.
TreeSet is implemented using a Self Balancing Binary Search Tree (Red-Black
Tree).
TreeSet is backed by TreeMap in Java.
EX:
import java.util.TreeSet;
class TreeSetDemo {
// Duplicate removed
tset.add("geeks");
Output:
TreeSet contains:
contribute
for
geeks
practice
5. Map,Hashmap,Treemap in Java
Map:
A map contains values on the basis of key, i.e. key and value pair. Each key and
value pair is known as an entry.
A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a
key.
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap
and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any
null key or value.
A Map can't be traversed, so you need to convert it into Set
using keySet() or entrySet() method.
Hashmap:
HashMap is the implementation of Map, but it doesn't maintain any order.
If you try to insert the duplicate key, it will replace the element of the
corresponding key.
It is easy to perform operations using the key index like updation, deletion, etc.
HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized.
It allows us to store the null elements as well, but there should be only one null
key.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for
value.
It inherits the AbstractMap class and implements the Map interface.
EX:
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes
TreeMap:
TreeMap is the implementation of Map and SortedMap.
It maintains ascending order.
Java TreeMap class is a red-black tree based implementation. It provides an
efficient means of storing key-value pairs in sorted order.
Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
Java TreeMap contains only unique elements.
Java TreeMap cannot have a null key but can have multiple null values.
Java TreeMap is non synchronized.
Java TreeMap maintains ascending order.
Ex:
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
100 Amit
101 Vijay
102 Ravi
103 Rahul
6)define Sorting in Java
A)There are two in-built methods to sort in Java.
1. Arrays.Sort() works for arrays which can be of primitive data type also.
// Arrays.sort().
import java.util.Arrays;
Arrays.sort(arr);
Arrays.toString(arr));
2. Output:
3. Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]
4. Collections.sort() works for objects Collections like ArrayList and LinkedList.
// Java program to demonstrate working of Collections.sort()
import java.util.*;
al.add("Friends");
al.add("Dear");
al.add("Is");
al.add("Superb");
Collections.sort(al);
5. Output:
6. List after the use of Collection.sort() :
7. [Dear, Friends, Geeks For Geeks, Is, Superb]
Which sorting algorithm does Java use in sort()?
Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge
sort for arrays of objects. In the latest versions of Java, Arrays.sort method and
Collection.sort() uses Timsort.
Which order of sorting is done by default?
It by default sorts in ascending order.
How to sort array or list in descending order?
It can be done with the help of Collections.reverseOrder().
Example:
For Arrays.sort()
import java.util.Arrays;
import java.util.Collections;
Arrays.sort(arr, Collections.reverseOrder());
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
Output:
Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]
For Collections.sort()
// to descending order.
import java.util.*;
al.add("Friends");
al.add("Dear");
al.add("Is");
al.add("Superb");
/* Collections.sort method is sorting the
Collections.sort(al, Collections.reverseOrder());
Output:
List after the use of Collection.sort() :
[Superb, Is, Geeks For Geeks, Friends, Dear]
How to sort only a subarray?
Example:
// using Arrays.sort().
import java.util.Arrays;
Arrays.sort(arr, 1, 5);
Arrays.toString(arr));
Output:
Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]
How to write my own sorting function in Java?
Please see Java programs for Quick Sort, Merge Sort, Insertion Sort, Selection Sort, Heap
Sort, Bubble Sort
Output:
Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970
Important Methods
import java.util.*;
// Creating date
boolean a = d3.after(d1);
boolean b = d3.before(d2);
int c = d1.compareTo(d2);
System.out.println(c);
Output:
Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is 60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976