0% found this document useful (0 votes)
84 views19 pages

List of Five Checked and Unchecked Exceptions

Class - a blueprint for creating objects that specifies attributes and behaviors of the object. Object - an instance of a class that reserves memory at runtime and can be manipulated. Method - a behavior or action that can be performed by an object. Methods are defined inside classes. Inheritance - a mechanism where one class acquires properties and behaviors of another class. Polymorphism - the ability of an object to take on multiple forms. Allows methods to have different implementations in child classes. Abstraction - hiding unnecessary details and only showing functionality to the user. Encapsulation - binding together the data and functions that manipulate the data, and keeping both safe from

Uploaded by

Vamsi Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views19 pages

List of Five Checked and Unchecked Exceptions

Class - a blueprint for creating objects that specifies attributes and behaviors of the object. Object - an instance of a class that reserves memory at runtime and can be manipulated. Method - a behavior or action that can be performed by an object. Methods are defined inside classes. Inheritance - a mechanism where one class acquires properties and behaviors of another class. Polymorphism - the ability of an object to take on multiple forms. Allows methods to have different implementations in child classes. Abstraction - hiding unnecessary details and only showing functionality to the user. Encapsulation - binding together the data and functions that manipulate the data, and keeping both safe from

Uploaded by

Vamsi Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1.

List of Five checked and Unchecked Exceptions


Checked Exceptions:-

 ClassNotFoundException
 InterruptedException
 InstantiationException
 IOException
 SQLException
 IllegalAccessException
 FileNotFoundException

ClassNotFound Exception:

Java ClassNotFoundException occurs when the application tries to load a


class but Classloader is not able to find it in the classpath.

EX: package com.journaldev.exceptions;


public class DataTest {
public static void main(String[] args) {
try {
Class.forName("com.journaldev.MyInvisibleClass");
ClassLoader.getSystemClassLoader().loadClass("com.journaldev.MyInvisibleClas
s");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}

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 is an exception. It is of type java.lang.Exception.

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

It occurs when classpath is not updated with required JAR files.

Ex:public class MainClass


{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}

NoClassDefFoundError

It is an error. It is of type java.lang.Error.

It occurs when java runtime system doesn’t find a class definition, which is present at compile time, but missing at run time.

It is thrown by the Java Runtime System.

It occurs when required class definition is missing at runtime.


EX:

class A
{
// some code
}

public class B
{
public static void main(String[] args)
{
A a = new A();
}
}
3)ArrayList and Vector in Java

1) ArrayList is not synchronized.

2) ArrayList increments 50% of current array size if the number of elements exceeds from
its capacity.

3) ArrayList is not a legacy class. It is introduced in JDK 1.2.

4) ArrayList is fast because it is non-synchronized.

5) ArrayList uses the Iterator interface to traverse the elements.

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 a legacy class.

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 :

For operations like search, insert and delete.


It takes constant time for these operations on average.
HashSet is faster than TreeSet.
HashSet is Implemented using a hash table.

EX:
import java.util.HashSet;
class HashSetDemo {
public static void main(String[] args)
{

// Create a HashSet
HashSet<String> hset = new HashSet<String>();

// add elements to HashSet


hset.add("geeks");
hset.add("for");
hset.add("practice");
hset.add("contribute");

// Duplicate removed
hset.add("geeks");

// Displaying HashSet elements


System.out.println("HashSet contains: ");
for (String temp : hset) {
System.out.println(temp);
}
}
}

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 {

public static void main(String[] args)


{
// Create a TreeSet
TreeSet<String> tset = new TreeSet<String>();

// add elements to HashSet


tset.add("geeks");
tset.add("for");
tset.add("practice");
tset.add("contribute");

// Duplicate removed
tset.add("geeks");

// Displaying TreeSet elements


System.out.println("TreeSet contains: ");
for (String temp : tset) {
System.out.println(temp);
}
}
}

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.

// A sample Java program to demonstrate working of

// Arrays.sort().

// It by default sorts in ascending order.

import java.util.Arrays;

public class GFG {

public static void main(String[] args)

int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };

Arrays.sort(arr);

System.out.printf("Modified arr[] : %s",

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.*;

public class GFG {

public static void main(String[] args)

// Create a list of strings

ArrayList<String> al = new ArrayList<String>();

al.add("Geeks For Geeks");

al.add("Friends");

al.add("Dear");

al.add("Is");

al.add("Superb");

/* Collections.sort method is sorting the

elements of ArrayList in ascending order. */

Collections.sort(al);

// Let us print the sorted list

System.out.println("List after the use of"

+ " Collection.sort() :\n" + 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()

// A sample Java program to sort an array

// in descending order using Arrays.sort().

import java.util.Arrays;

import java.util.Collections;

public class GFG {

public static void main(String[] args)

// Note that we have Integer here instead of

// int[] as Collections.reverseOrder doesn't

// work for primitive types.

Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };

// Sorts arr[] in descending order

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

// Java program to demonstrate working of Collections.sort()

// to descending order.

import java.util.*;

public class GFG {

public static void main(String[] args)

// Create a list of strings

ArrayList<String> al = new ArrayList<String>();

al.add("Geeks For Geeks");

al.add("Friends");

al.add("Dear");

al.add("Is");

al.add("Superb");
/* Collections.sort method is sorting the

elements of ArrayList in ascending order. */

Collections.sort(al, Collections.reverseOrder());

// Let us print the sorted list

System.out.println("List after the use of"

+ " Collection.sort() :\n" + al);

 Output:
 List after the use of Collection.sort() :
 [Superb, Is, Geeks For Geeks, Friends, Dear]
 How to sort only a subarray?
Example:

// A sample Java program to sort a subarray

// using Arrays.sort().

import java.util.Arrays;

public class GFG {

public static void main(String[] args)

// Our arr contains 8 elements


int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };

// Sort subarray from index 1 to 4, i.e.,

// only sort subarray {7, 6, 45, 21} and

// keep other elements as it is.

Arrays.sort(arr, 1, 5);

System.out.printf("Modified arr[] : %s",

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

7)what are date operations


A) The class Date represents a specific instant in time, with millisecond
precision. The Date class of java.util package implements Serializable,
Cloneable and Comparable interface. It provides constructors and
methods to deal with date and time with java.
Constructors
 Date() : Creates date object representing current date and time.
 Date(long milliseconds) : Creates a date object for the given
milliseconds since January 1, 1970, 00:00:00 GMT.
 Date(int year, int month, int date)
 Date(int year, int month, int date, int hrs, int min)
 Date(int year, int month, int date, int hrs, int min, int sec)
 Date(String s)
Note : The last 4 constructors of the Date class are Deprecated.

// Java program to demonstrate constuctors of Date


import java.util.*;

public class Main

public static void main(String[] args)

Date d1 = new Date();

System.out.println("Current date is " + d1);

Date d2 = new Date(2323223232L);

System.out.println("Date represented is "+ d2 );

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

 boolean after(Date date) : Tests if current date is after


the given date.
 boolean before(Date date) : Tests if current date is
before the given date.
 int compareTo(Date date) : Compares current date with
given date. Returns 0 if the argument Date is equal to the
Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after
the Date argument.
 long getTime() : Returns the number of milliseconds
since January 1, 1970, 00:00:00 GMT represented by this
Date object.
 void setTime(long time) : Changes the current date and
time to given time.
// Program to demonstrate methods of Date class

import java.util.*;

public class Main

public static void main(String[] args)

// Creating date

Date d1 = new Date(2000, 11, 21);

Date d2 = new Date(); // Current date

Date d3 = new Date(2010, 1, 3);

boolean a = d3.after(d1);

System.out.println("Date d3 comes after " +

"date d2: " + a);

boolean b = d3.before(d2);

System.out.println("Date d3 comes before "+

"date d2: " + b);

int c = d1.compareTo(d2);

System.out.println(c);

System.out.println("Miliseconds from Jan 1 "+

"1970 to date d1 is " + d1.getTime());

System.out.println("Before setting "+d2);


d2.setTime(204587433443L);

System.out.println("After setting "+d2);

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

You might also like