Mca Java Module Ii
Mca Java Module Ii
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;
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;
GUARDING
EXPRESSION LABELLED SYNCHRONIZATION STATEMENT
STATEMENT STATEMENT STATEMENT
CONTROL
STATEMENT
CONTINUE
3 2 1 1 2
Fragmentation of memory (Java heap space)
Arrays
1. Homogeneous
2. Contiguous
3. Related data items
Creating an Array
It means
num[0]
num[1]
num[2]
num[3]
num[4]
or
Num1[0]
1
Num1[1]
2
Num1[2]
3
Num1[3]
4
Num1[4]
5
int num=new int [5];
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
int a2 []=new int [ ] {1, 2, 3, 4, 5}; a2 gets unnamed array with initialize
a4=a3;
a4[0]=20; {20, 2, 3, 4, 5}
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);
}
}
x [0]
X[0][0] X[0][1]
x [0]
X[1][0] X[1][1] X[1][2] X[1][3]
Declaration+creation+initialization
int mat[][]={{10},{10,10},{10, 10, 10}};
X[0][0]
X[1][0] X[1][1]
PROGRAM 4
PROGRAM 5
PROGRAM 6
}
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)
String str;
str.length(); 9
String str1=”hello”;
String str2=”BCA”;
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);
ch3[i++]=’ ‘;
ch3[i]=’\0’;
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”};
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.
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”
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.
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:
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
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
}
toString(): this method provides the name and the description of an occurred
exception.
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
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.”);
}
}
}
}
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.
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
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...");
}
}
PROGRAM 9