[go: up one dir, main page]

0% found this document useful (0 votes)
29 views33 pages

Mca Java Module Ii

The document discusses different data types in Java including primitive and non-primitive types. It describes numeric types like integer, floating point, and non-numeric types. It also covers arrays, classes, interfaces and variable scope in Java.

Uploaded by

Aditya Kumar
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)
29 views33 pages

Mca Java Module Ii

The document discusses different data types in Java including primitive and non-primitive types. It describes numeric types like integer, floating point, and non-numeric types. It also covers arrays, classes, interfaces and variable scope in Java.

Uploaded by

Aditya Kumar
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/ 33

DATA TYPES IN JAVA

Every variable in Java has a data type. Data types specify the size and type of
the values that are stored in a variable. Data types can be categorized as:

1. Primitive or Intrinsic
a. Numeric
i. Integer: Java does not support the concept of unsigned
integer. All the Java integer values are signed i.e. both
positive and negative.
1. Byte (1 byte) stores values in the range -128 to 127
a. byte num1=34;
2. Short (2 bytes) stores values in the range -32768 to
32767
a. short num2=2345;
3. Int (4 bytes) stores values in the range -2147483648
to 2147483647
a. int num3=789;
4. Long (8 bytes) stores value in the range -
9223372036854775808 to 9223372036854775807
a. long num4=123456;
ii. Floating point
1. Float (4 bytes) float f=23.45; //single precision
2. Double (8 bytes) double d=23.45f . double d=
45.123456789;//double precision
3. Floating point data type support a special value
known as NaN (Not-a-Number). NaN is used to
represent the result of dividing zero by zero, where
no actual number is generated.
b. Non-numeric
i. Character (2 bytes) char c=’t’;
ii. Boolean (1 bit) boolean b=true;

Declaration of variables: char c; float f;

Giving value to variable:

a) Assignment statement float f=23.45, int s=89;


b) Taking input through command line argument or using Scanner class
or using any Input Stream class.

2. Non-Primitive or Derived data type


a. Arrays (homogeneous data type)
b. Classes (abstract data type)
c. Interfaces (used for multiple inheritance. Similar to class but holds
only list of method declarations. No objects can be created for
interface but reference can be created. )
class <class-name> implements <interface-name>
{
}
class Test
{
int a;
char b;
}
class TestMain
{
public static void main( String [] args)
{
Test obj1 =new Test();
Test obj2;
obj1.a=45;
obj2=obj1;
System.out.println (“obj1.a=”+obj1.a); 45
System.out.println (“obj2.a=”+obj2.a); 45
}
}

obj1 int a=45

obj2 char b

class Test
{
int a;
char b;
}
class Hello
{
void display()
{
System.out.println(" This is display method of Hello class.");
}
}
public class TestMain
{
public static void main( String [] args)
{
Test obj1, obj2,obj3,obj4;
obj1=new Test();
obj2=new Test();
obj3=obj1;
obj4=obj2;
System.out.println(" Printing the reference obj1: "+obj1);
System.out.println(" Printing the reference obj2: "+obj2);
System.out.println(" Printing the reference obj3: "+obj3);
System.out.println(" Printing the reference obj4: "+obj4);

/*Hello h1,h2;
h1=new Hello();
h1.display();*/
obj1.a=45;
obj1.b='A';
obj2.a=60;
obj1.b='Z';
System.out.println ("obj1.a= " +obj1.a);
System.out.println ("obj2.a= " +obj2.a);
System.out.println ("obj3.a= " +obj3.a);
System.out.println ("obj4.a= " +obj4.a);

}
}

SCOPE OF VARIABLE
In Java variables can be classified as the following:

1. Instance variable: they are declared inside a class and whenever a new
object is created a fresh copy of these instance variables are created.
They can take different values for each object. The area where the
variable is usable is called its scope.
class Test
{private int a, b;
char x,y;
static int d;
static void display()
{}
}
class TestMain
{
public static void main (String []args)
{
Test obj1=new Test();
//obj1.a=15;
Test.d=12;
Test.display();
int f=Math.sqrt(16);
}
}
2. Class variable or static variable: class variables are global to a class and
are created with the keyword static. Only one copy of any class variable
is created and it belongs to the entire set of objects for that class i.e. it is
shared by all objects. The default initial value is 0.
3. Local variable: variables declared and used inside methods are called as
local variables. They can also be declared within the program blocks
defined by a pair of starting and closing braces. Their scope is within the
domain of declaration.
void display()
{ int a=2,b=8;
{
int a=5, b=0; SOP(a); SOP(b);
char d=’s’;
}

}
class Test
{
private int a, b;
char x,y;
static int d;
void display1()
{
int x=24;
x++;
d++;
System.out.println(x);
System.out.println("printing d from display1 " +d);
}
static void display2()
{
System.out.println("this is the static method of Test");
}
}
public class TestMain
{
public static void main (String []args)
{
Test obj1=new Test();
Test obj2=new Test();
//obj1.a=15;
obj1.display1();
obj2.display1();
obj1.display1();
System.out.println(" printing d from main " +Test.d);
Test.d=12;
System.out.println(Test.d);
Test.display2();
int a=45;
}
}

JAVA STATEMENTS
Java statements are collection of Java instructions. A statement is an
executable combination of tokens and they end with a ; (semi-colon).
Statements are usually executed in sequence in which they occur.
1. Empty statements: these statements do nothing during program
development and they are just space holder.
2. Labelled Statement: the statements begin with a label. The name of
label has some restrictions, as they must not be keywords; they must
not be already declared local variables or previously used local labels. In
Java these are used for arguments of the Jump statements.

class LoopCheck{
public static void main(String [] args)
{
LOOP1: for (int i=1; i<=50;i++)
{
SOP(“ “);
if (i>=10)
break;
for ( int j=1; j<50;j++)
{
SOP(“*”);
if (j==i)
continue LOOP1;
}
}
}
}
Identifier : expression;

3. Expression Statement: mostly the statement in Java are expressions.


Java supports 7 types of expressions:
a. Assignment int a=9; int f=a+g+j;
b. Pre-increment x=++a;
c. Pre-decrement x=--a;
d. Post-increment x=a++;
e. Post-decrement x=a--;
f. Method call int/float/char/String var=obj1.method1();
g. Allocation expression Test obj1 =new Test(); int a[]=new int [2];
4. Synchronization statements: are used for handling the issues with multi-
threading.
5. Guarding statements: are used for safe handling of the code that may
cause exceptions (such as divide by zero etc.) or errors in the program.
These statements are used with keywords try, throw, catch and finally.
6. Compound Statement: this allows grouping of any number of data
definitions, declarations, and other statements into one statement.
7. Control statements
a. Selection statement: these select one of the several control flows.
IF, IF-ELSE, SWITCH
b. Iteration statements: these specify how and when looping takes
place. FOR, WHILE, DO-WHILE
c. Jump statements: these statements pass control to the beginning
or end of the current block. BREAK, CONTINUE, RETURN

JAVA STATEMENTS COMPOUND


EMPTY/NULL STATEMENT
STATEMENT

GUARDING
EXPRESSION LABELLED SYNCHRONIZATION STATEMENT
STATEMENT STATEMENT STATEMENT

CONTROL
STATEMENT

SELECTION ITERATION JUMP STATEMENTS


STATEMENTS STATEMENTS

CONTINUE

IF IF- SWITCH FOR WHILE RETURN


DO
ELSE
BREAK
Dynamic Memory Management
1. Operator new: this operator is used for dynamic memory allocation. But
the operator does not work with the primitive data types. In Java the call
of new operator is done only to allocate memory for derived data like
array and class. While allocating memory dynamically it may so happen
that the memory is exhausted and the allocation fails, in that case a null
reference is returned. If the programmer try to use the null reference in
the program then NullPointerException is raised and this may crash the
program.
2. Garbage collection: In Java the programmer need not deallocate the
memory explicitly since the automatic garbage collection system runs
concurrently on a separate thread. It actually steps in after some interval
of time and deallocates the unused memory and do compaction of the
fragmented memory space on the heap. It calls the finalize ( ) method
for the particular object, which needs to be destroyed. Modern adaptive
garbage collectors use mark-an –sweep algorithm. Here every object is
examined and all objects, which are presently being used, are marked.
Finally the JVM garbage collector frees up all the unmarked objects.

3 2 1 1 2
Fragmentation of memory (Java heap space)

Arrays
1. Homogeneous
2. Contiguous
3. Related data items

Creating an Array

1. Declaring the array

Type arrayname [ ]; int num[ ]; float f []; char ch [ ];

Type [ ] arrayname; int [ ] num; float [ ] f; char [ ] ch;

It means

int num[ ]; num point no where

2. Creating memory locations


Type arrayname [ ];
arrayname = new type [size];
int num[ ];
num= new int [10]; int num [ ]=new int [10]; declaration + creation
float f [] =new float [5];

In Java there are two types of character array


• null (\0) terminating (char ch[]=new char [5];)
• non- null (\0) terminating (String s=”hello”;

char ch [] =new char [10];


arrays can be accessed by their name and subscript value.
e.g. array-name[subscript] ch[3]
int num [ ]=new int [5];
num
points to the int array (object)

num[0]
num[1]
num[2]
num[3]
num[4]

3. Putting value into the memory locations

int Num1 []={1,2,3,4,5};

or

int Num1 []=new int [5];

Num1[0] =1; Num1[1]=2; Num1[2]=3; Num1[3]=4; Num1[4]=5;

Num1[0]
1
Num1[1]
2
Num1[2]
3
Num1[3]
4
Num1[4]
5
int num=new int [5];

for (int i=0;i<5;i++)


num[i]=i+2;

In Java all array store the allocated size in a variable named length. The length
can be obtained by using num.length.

PROGRAM 1
class Input1
{
public static void main(String [] args)
{
int a;
a=Integer.parseInt(args[0]); “23”
System.out.println(“input value is “+a);
}
}

C:Java\bin>javac Input1.java
C:Java\bin>java Input1 23

PROGRAM 2
public class ArrayInput
{
public static void main(String [] args)
{
int num[]=new int [10];
int i;int j=0;
for (i=0;i<num.length;i++)
{
if (j>=args.length)
{
System.out.println("Array size exceeded");
break;
}
num[i]=Integer.parseInt(args[j++]);
}
for (i=0;i<num.length;i++)
System.out.println(i+"th element is "+num[i]);
for (i=0;i<args.length;i++)
System.out.println(i+"th element is "+num[i]);
}
}
C:Java\bin>javac ArrayInput.java
C:Java\bin>java ArrayInput 23 56 78 1 0

Assigning array to another array


int a1[] =new int [5]; array is declared and created

int a2 []=new int [ ] {1, 2, 3, 4, 5}; a2 gets unnamed array with initialize

int a3 [ ]= {1, 2, 3, 4, 5}; array created with initialize list

int a4 [ ]; array declared but not allocated

a4=a3;

a4[0]=20; {20, 2, 3, 4, 5}

int a5 [ ]={4,1,3,9, 0, 2, 7};

int a6[]={1, ,2, 3, 4, 5};

int a7[]=new int [5]; a7=a6;

Library Methods for Arrays


There are some static methods available in java.util package’s Arrays class,
which are used for array manipulation.

1. binarySearch (Array, key): Search a sorted array for a key value passed
as parameter using binary search technique. If successful, then it
returns the key’s index and on failure returns a negative value.
Arrays.binarySearch (a5, 0);
2. equals (Array array1, Array array2): checks 3 things namely, a) whether
two arrays refer to same object, or b) both are null, or c) both have
same size and contents. Returns true on success of all these aforesaid
cases and false otherwise. Arrays.equals (a3,a4)
3. sort (Array): sorts a array. Arrays.sort (a5); {0, 1, 2, 3, 4, 7, 9}
Arrays.sort(a5, 1, 4); {4, 0, 1,3,9, 2, 7}
4. fill (Array, val): fills the array with specified value. Arrays.fill(a2,10)
Arrays.fill(a2,1,3,10) {1, 10, 10, 10, 5}
PROGRAM 3
import java.util.*;
public class ArrayTest
{
public static void main(String[] args)
{
int a1[] =new int [5];
int a2 []=new int [ ] {1, 2, 3, 4, 5};
System.out.println("reference of a1 "+a1);
System.out.println("reference of a2 "+a2);
int a3 [ ]= {1, 2, 3, 4, 5};
// System.out.println("a2=a3 "+Arrays.equals(a2,a3));
int a4 [ ];
a4=a3;
System.out.println("reference of a3 "+a3);
System.out.println("reference of a4 "+a4);
a4[0]=20;
int a5 [ ]={4,1,3,9, 0, 2, 7};
System.out.println("Printing values of a5 before
sorting");
for(int i=0;i<a5.length;i++)
System.out.print(" "+a5[i]);
Arrays.sort(a5);
System.out.println("\nPrinting values of a5 after
sorting");
for(int i=0;i<a5.length;i++)
System.out.print(" "+a5[i]);
System.out.println("\nreference of a5 "+a5);
int result=Arrays.binarySearch(a5,4);
System.out.println("The key was found by Binary
Search at index "+result);
int a6[ ]={1,2, 3, 4, 5};
int a7[ ]=new int [5];
System.out.println("reference of a6 "+a6);
System.out.println("reference of a7 "+a7);
//System.out.println("a6=a7 "+Arrays.equals(a6,a7));
System.out.println("reference of a7 "+a7);
a7=a6;
// System.out.println("a6=a7 "+Arrays.equals(a6,a7));
System.out.println("reference of a6 "+a6);
System.out.println("reference of a7 "+a7);
}
}

Two Dimensional Array


The representation of a 2-D array is like a matrix having specific number of
rows and columns.
As example: num1[0][0]
num1[0]
num1[0][1]
num1[0][2]
num1[1]
num1[1][0]
num1[1][1]
num1[1][2]
num1[2][0]
num1[2]
num1[2][1]
num1[2][2]

The above array can be created by writing the following:


int num1 [] []=new int [3] [3];
To declare, create and initialize the array num1 we can also write

The above array can be created by writing the following:


Int num2 [] []=new int [2] [3];

For initializing the array with data:


1. int num [][]={{0, 0, 0},{1, 1, 1}};
2. int num [][]={
{0, 0, 0},
{1, 1, 1}
};
3. for (int i=0; i<2; i++)
{
for (int j=0;j<3;j++)
{
num[i][j]=j;
}
}

4. for (int i=0; i<num.length; i++)


{
for (int j=0;j<num[i].length;j++)
{
num[i][j]=i+1;
}
}

Variable Size Array

int x[] []=new int [3][ ];


x[0]= new int [2];
x[1]=new int [4];
x[2]=new int [3];

x [0]
X[0][0] X[0][1]
x [0]
X[1][0] X[1][1] X[1][2] X[1][3]

x [2] X[2][0] X[2][1] X[2][2]

Declaration+creation+initialization
int mat[][]={{10},{10,10},{10, 10, 10}};

X[0][0]

X[1][0] X[1][1]

X[2][0] X[2][1] X[2][2]

int mat[] []= new int [3][];


for (int i= 0; i<mat.length;i++)
{
mat[i]= new int [i+1];
for (int j=0;j<mat[i].length;j++)
mat[i][j]=10;
}

PROGRAM 4

public class TwoDArray1


{
public static void main(String[] args)
{
int mat[] []= new int [3][];
for (int i= 0; i<mat.length;i++)
{
mat[i]= new int [i+1];
for (int j=0;j<mat[i].length;j++)
mat[i][j]=10;
}
for (int i= 0; i<mat.length;i++)
{
for (int j=0;j<mat[i].length;j++)
System.out.print(" "+mat[i][j]);
System.out.println();
}
}
}

PROGRAM 5

public class TwoDArrayInput1 {


public static void main(String args[])
{
int k=0;
int mat1[][]={{20},{20,20},{20, 20, 20}};
int mat2[] []= new int [3][];
for (int i= 0; i<mat2.length;i++)
{
mat2[i]= new int [i+1];
for (int j=0;j<mat2[i].length;j++)
{
if(k>=args.length)
{
System.out.println("ARGS size exceeded");
break;
}
mat2[i][j]=Integer.parseInt(args[k++]);
}
}
System.out.println("Printing mat1");
for (int i= 0; i<mat1.length;i++)
{
for (int j=0;j<mat1[i].length;j++)
{
System.out.print(" " +mat1[i][j]);
}
System.out.println();
}
System.out.println("Printing mat2");
for (int i= 0; i<mat2.length;i++)
{
for (int j=0;j<mat2[i].length;j++)
{
System.out.print(" " +mat2[i][j]);
}
System.out.println();
}
}
}

PROGRAM 6

public class TwoDArrayInput2


{
public static void main(String args[])
{
int x[] []=new int [3][ ];
int limit=0,k=0;
x[0]= new int [2];
x[1]=new int [4];
x[2]=new int [3];
for (int i=0;i<x.length;i++)
{
for (int j=0;j<x[i].length;j++)
{
if (k>=args.length)
{
System.out.println("ARGS size exhausted");
break;
}
x[i][j]=Integer.parseInt(args[k++]);
}

}
for (int i= 0; i<x.length;i++) //mat.length=3
{
for (int j=0;j<x[i].length;j++)
{
System.out.print(" "+x[i][j]);
}
System.out.println(" ");
}
}
}

C:\Java\bin>javac TwoDArrayInput.java
C:\Java\bin>java TwoDArrayInput 1 2 3 4 5 6 7 8 9 3 6 8 3

1 2

3 4 5 6

7 8 9

PROGRAM 7

import java.util.*;
public class TwoDArray2
{
public static void main(String[] args)
{
int x[] []= new int [3][];
x[0]= new int [2];
x[1]=new int [4];
x[2]=new int [3];
int k=0;
for (int i= 0; i<x.length;i++)
{
if (k>=args.length)
{
System.out.println("Array size exceeded");
break;
}
for (int j=0;j<x[i].length;j++)
x[i][j]=Integer.parseInt(args[k++]);
}
for (int i= 0; i<x.length;i++)
{
for (int j=0;j<x[i].length;j++)
System.out.print(" "+x[i][j]);
System.out.println();
}
}
}

STRINGS
1. Null terminating character array (character array)

char ch[ ] ={‘H’,’e’,’l’,’l’,’o’,’ ‘, ‘B’,’C’,’A’,’\0’}; ch.length

2. Non-null terminating character array (String)

String str=”Hello BCA”;

String str;

str=new String (”Hello BCA”);

str.length(); 9

String manipulation is very common in Java and they represent a sequence of


characters just like character array. But the strings are non-null terminating.
Although the character arrays have the capability to query about their length
but they are not good enough to support the range of operations we may like
to perform on strings.

String str1=”hello”;

String str2=”BCA”;

String str3=str1+” “+str2;

String str4=”hello”+” BCA”;

System.out.println (str1+” “+str2);

System.out.println (str3);

System.out.println (str4);
Why Strings better than array?
Program 1 with Strings

String str1=”hello”;
String str2=”BCA”;
String str3=str1+” “+str2;
System.out.println (str3);

Program 1 with character array

char ch1[] =new char [10]; //hello


ch1[0]=’h’; ch1[1]=’e’; ch1[2]=’l’; ch1[3]=’l’; ch1[4]=’o’; ch1[5]=’\0’;
char ch2[] =new char [10];// BCA
ch2[0]=’B’; ch2[1]=’C’; ch2[2]=’A’; ch2[3]=’\0’;
char ch3=new char [15]; hello BCA

for (int i=0;ch1[i]!=’\0’;i++)


ch3[i]=ch1[i];

ch3[i++]=’ ‘;

for (int j=0;ch2[j]!=’\0’;j++)


ch3[i++]=ch2[j];

ch3[i]=’\0’;

for (int i=0;ch3[i]!=’\0’;i++)


System.out.print(ch3[i]);

i=0 ch3[0]=ch1[0]=h;
i=1 ch3[1]=ch1[1]=e;
i=2 ch3[2]=ch1[2]=l;
i=3 ch3[3]=ch1[3]=l;
i=4 ch3[4]=ch1[4]=o;
i=5 ch[5]=’ ‘
i=6
i=6, j=0 ch3[6]=ch2[0]=B;
i=7, j=1 ch3[7]=ch2[1]=C;
i=8, j=2 ch3[8]=ch2[2]=A;
i=9, j=3 ch[9]=’\0’
Array of strings
String a [ ]=new String [5];

String a [ ]={“Hello”,”how”,”are”,”you”};

System.out.println (a[0]); Hello

System.out.println (a[1]); how

System.out.println (a[2]); are

System.out.println (a[3]); you

char c= a[2].CharAt(1); r

a[2].length(); 3

a.length; 4

String Methods
String str1=”hello”;

String str2=”BCA”;

All the string types of variables are actually objects of the String class. So these
objects can access all the methods of the String class. For example str1 and
str2 are objects of the String class.

1. toUpperCase() : String s1=str1.toUpperCase(); converts the String str1 to


its upper case.
2. toLowerCase():String s2=s1.toLowerCase();converts the String str1 to its
lower case.
3. length(): returns the length of a string. int a= s1.length(); 5
4. CharAt(int n): gives the n-th character of a string. char c=str1.CharAt(4);
o.

PROGRAM 8

class CharInput
{
public static void main(String args[])
{
char target[]=new char[10];
int i=0;
String str=args[0];
for (;i<str.length ( );i++)
target[i]=str.CharAt(i);
target[i]=’\0’;
for (i=0;i<target[i]!=’\0’;i++)
System.out.print(target[i]);
}
}

class CharInput
{
public static void main(String args[])
{
char target[]=new char[10];
int i=0;
if (args[0].length ( )<target.length)
{
for (;i< args[0].length ( );i++)
target[i]= args[0].CharAt(i);
target[i]=’\0’;
}
else
{
for (;i< target.length;i++)
target[i]= args[0].CharAt(i);
target[i]=’\0’;
}
for (i=0;i<target[i]!=’\0’;i++)
System.out.print(target[i]);
}
}

C:\Java\bin>javac CharInput.java
C:\Java\bin>java CharInput HELLOBCABBA
args[0]=”HELLO”

5. concat ( ): concatenates two strings.


String str1=”hello”; String str2=” world”; String str3=str1.concat(str2);
6. compareTo (): compares two strings and returns negative if str1<str2
and returns positive for str1>str2 and returns zero if str1=str2.
String str1=”HEllo”; String str2=”HELLO”; int c=str2.compareTo(str1);-32
7. trim(): removes the unnecessary spaces from the beginning of the string
and from the end of the string. String s=” hello “; String
s1=s.trim();
8. replace (char ch1, char ch2): replaces all appearances of the first
character with the second character.

String str1=”hello”; String str2=str1.replace(‘l’, ‘y’); “heyyo”

9. substring (int n): returns the substring of the current string from the n-
th location. String str=”hello”; String str2=str.substring(2);
10.substring (int n, int m): returns the substring of the current string from
the n-th character to the (m-1)-th character.
String str=”hello world”; String str2=str.substring(4, 9);
11. str1.equals(str2): returns true if both str1 and str2 are same.

String str1=”Hello”; String str2=”HELLO”; str1.equals(str2); false

12. str1.equalsIgnoreCase(str2): returns true if str1=str2 ignoring the case


of the characters.

String str1=”Hellw”; String str2=”HELLO”; str1.equalsIgnoreCase(str2); false

public class StringMethod


{
public static void main(String args[])
{
String str1="hello";
String str2=str1.toUpperCase(); //HELLO
//System.out.println("Printing str2-->");
//System.out.println(str2);
// System.out.println("Printing str1-->");
//System.out.println(str1);
//System.out.println(str2.toLowerCase());
String str3="Java";
String str4=" World";
String str5=str3.concat(str4);
//System.out.println("Printing str5-->");
//System.out.println(str5);
String str6="HELLO";
String str7="HEllo";
//System.out.println(str1.compareTo(str6));
int c=str6.compareTo(str1);
//System.out.println(c);
int a=str6.compareTo(str7);
//System.out.println(a);
String str8=" hello how are you ";
//System.out.println("Printing str8-->");
//System.out.println(str8);
//String s=str8.trim();
//System.out.println("Printing s-->");
// System.out.println(s);
String str9=str1.replace('l','y');
//System.out.println("Printing str9-->");
//System.out.println(str9);
//System.out.println("Printing str5-->");
//System.out.println(str5);
String str10=str5.substring(2);
//System.out.println("Printing str10-->");
//System.out.println(str10);
//String str11=str5.substring(2,8);
//System.out.println("Printing str11-->");
//System.out.println(str11);
boolean b=str2.equals(str6);
System.out.println(b);
System.out.println(str1.equals(str6));
System.out.println(str1.equalsIgnoreCase(str6));
}
}
Exception Handling

Errors are wrongs in the program that can produce wrong output in the
program and may even crash it. There can be following type of errors:
1. Syntax Error: they are detected and displayed at the time of compilation.
Common syntax errors are:
a. Missing semi colon (;)
b. Missing brackets in class or methods
c. Wrong keyword or identifier spelling
d. Missing double quotes in strings
e. If the path of the java is not well set in the computer then there
also can be errors.
2. Semantic or Logical errors: when the codes are not valid as per the
requirement of the problem.
3. Runtime error: sometimes even after successful compilation of the
program and creation of the .class file (byte code), the program cannot
execute properly. This is called a runtime error and an exception in java
is the condition caused by these runtime errors. When an exception
occurs then an exception object is generated and if the exception object
is not caught and handled properly then the interpreter will display error
messages. Exception handling is the task to try to catch the exception
object thrown by the error condition and then display appropriate
message and take corrective actions for the same. Steps for exception
handling are:

Inform that error Receive the error


Find the problem
has occurred info
Hit the Exception Throw the exception Catch the Exception

Take corrective
actions
Handle the Exception
Exception can be categorized as:
1. Checked Exception: these are extended from java.lang.Exception class.
These exceptions may occur regularly in a program and the compiler also
checks for these exceptions during compile time only. At the time of
compilation, the compiler checks whether a certain method is throwing
any of the checked exception or not. If not then the compiler throw the
UnreportedException. The examples are FileNotFoundException,
EndOfFileException
2. Unchecked Exception: all these exceptions are extended from
java.lang.RuntimeException class. These do not occur regularly in the
program and the compiler does not check for them. The examples are:
ArithmeticException, NullPointerException.
The most significant thing in both checked and unchecked exceptions are
absolutely similar as far as their nature is concerned but the difference lies in
handling them.

try BLOCK
Exception object creator
Statement that causes
an exception

catch BLOCK

Statement that Exception handler


handles the exception

Exception Handling Mechanism

Common Types of Exception in Java


**Names of Exceptions means they are class names
All these Exceptions below are descendants of Throwable class.

Exception Type Cause of Exception


ArithmeticException Caused by math error such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array index (try to access illegal array
subscript)
ArrayStoreException Caused when a program tries to store the wrong
type of data in an array
FileNotFoundException Caused by an attempt to access a non-existent file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings and
number fails.
IOException Caused by general input/output failures (such as
inability to read from a file)
StringIndexOutOfBoundsException Caused when the program attempts to access a non-
existent character position in a String.
StackOverFlowException Caused when the system runs out of the stack space
Blocks for Exception Handling in Java

1. Try Block: try is keyword; denotes an exception block where exception


can be generated.
2. Catch Block: catch is keyword; catches the exception to handle it for the
recovery.
3. Finally Block: finally is keyword; this is a block, where program control
enters after the try-catch block, irrespective of normal execution or an
exception is raised. finalize ( ); finally; final int a=34;
4. Throw expression: throw is a keyword; it is somewhat equivalent to
return statement and is used to create a new exception object and
throw it.
5. Throws Exception: throws is keyword; a function may decide to throw
the exception to the caller when the exception is raised while executing
the statements within the function.

General Syntax of try-catch block

try
{
Block of statements;
}
catch (Exception-Type-1 obj)
{
Exception handler block;
}
catch (Exception-Type-2 obj)
{
Exception handler block;
}
.
.
.
finally (optional)
{
Outside try block
}

Throwable class is available in java.lang package and Exception class is a


subclass of Throwable class.
printStackTrace ( ): this method is a member of Throwable class and it is used
to print several info in the console about the occurred exception. It includes
the name of the subclass of the Throwable class, package information and also
the position of the error.

getMessage() : it provides the only the description of an occurred exception.

toString(): this method provides the name and the description of an occurred
exception.

Exception handling programs


PROGRAM 1
class Error1
{
public static void main(String args [ ])
{
int a=10,b=5,c=5;
int x, y;
try
{
x=a/ (b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero error.”);
}
finally
{
y=a/(b+c);
System.out.println(“y= “+y);
}
}
}

PROGRAM 2
class Error2
{
public static void main(String args [ ])
{
int invalid=0, num, count=0;
for (int i=0;i<args.length;i++)
{
try
{
num=Integer.parseInt(args[i]);
}
catch(NumberFormatException e)
{
invalid++; 4
System.out.println(“Invalid Number: ”+args[i]);
continue;
}
count=count+1; 5
}
System.out.println(“Valid numbers count= “+count);
System.out.println(“Invalid numbers count= “+invalid);
}
}
C:\Java\bin>javac Error2.java
C:\Java\bin>java Error2 14 hello 15 BCA 67 98 how are 32

PROGRAM 3
class Error3
{
public static void main(String args [ ])
{
try
{
String str=null;
System.out.println( str.CharAt(0));
}
catch (NullPointerException e)
{
System.out.println(“Null Pointer exception happened”);
System.out.println(“String is not yet initialized.”);
}
}
}

PROGRAM 4

class Error4
{
public static void main(String args [ ])
{
String str=”Hello BCA students”;
try
{
char ch=str.CharAt(20);
System.out.println(“ the character is “+ch);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(“ Illegal string subscript access.”);
}
}
}

PROGRAM 5

Nested Try-catch block

class Error5
{
public static void main(String args [ ])
{
try
{
int a=2, b=4,c=2, x=7,z;
int p [ ]={2,5};
p[3]=4;
try
{
z= x/((b*b)-(4*a*c));
System.out.println(“value of z is: “+z);
}
catch (ArithmeticException e)
{
System.out.println(“Division by zero happened.”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index is out of limit.”);
}
}
}
}

Multiple Catch blocks

PROGRAM 6
class Error6
{
public static void main(String args [ ])
{
int a [ ]={5,10};
int b=5;
try
{
int x=a[2]/(b-a[1]);
}
catch (ArithemticException e)
{
System.out.println(“Division by zero.”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error.”);
}
catch (NumberFormatException e)
{
System.out.println(“Wrong data type”);
}
int y=a[1]/a[0];
System.out.println(“value of y= “+y);
}
}

Using throws
The throws keyword is used to declare that a method may generate and throw
one or more exceptions. If the exception is not handled then there will be
compilation failure.

void method1() throws type of exception


{
Exception handling code
}

PROGRAM 7
class Error7
{
public static void main(String args [ ]) throws IOException
{
boolean flag=false;
int num=0;
try
{
num=Integer.parseInt(args[0]);
flag=true;
}
catch (NumberFormatException e)
{
System.out.println(“incorrect form of data.”);
e.printStackTrace();
}
finally
{
if (flag)
System.out.println(“Input number is= “+num);
else
System.out.println(“Could not read”);
}
}
}

C:\Java\bin>javac Error7.java
C:\Java\bin>java Error7 hello

To create our own exception class and use that exception

PROGRAM 8
class MyException extends Exception
{
public MyException (String mesg)
{
super(mesg);
}
}
// class that uses custom exception InputException
public class TestMyException
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new MyException("Too small number.");
}
}
catch (MyException e)
{
System.out.println("Caught the exception");
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

To create an exception class and use a method to use that exception

PROGRAM 9

class InputException extends Exception


{
public InputException (String mesg)
{
super(mesg);
}
}
// class that uses custom exception InputException
public class TestException1
{
static void validateInput(int a) throws InputException
{
if(a>10|| a<1)
{
throw new InputException("The input is not valid");
}
else
{
System.out.println("The input is valid");
}
}
public static void main(String args[])
{
int num;
num=Integer.parseInt(args[0]);
try
{
validateInput(num);
}
catch (InputException e)
{
System.out.println("Caught the exception");
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

You might also like