0% found this document useful (0 votes)
2 views

JAVA_LJIET_Coding Questions

The document contains multiple Java programs demonstrating various object-oriented programming concepts. It includes examples of counting character occurrences in a string, creating fan and rectangle classes with methods for displaying properties, and implementing an abstract class hierarchy for vegetables and shapes. Additionally, it features a student class for calculating semester performance index (SPI) based on grades and credits, with both command-line and scanner input methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA_LJIET_Coding Questions

The document contains multiple Java programs demonstrating various object-oriented programming concepts. It includes examples of counting character occurrences in a string, creating fan and rectangle classes with methods for displaying properties, and implementing an abstract class hierarchy for vegetables and shapes. Additionally, it features a student class for calculating semester performance index (SPI) based on grades and credits, with both command-line and scanner input methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit-2, Question-2 Write a program to count occurrence of character in a

string.
class CountChar
{
public static void main(String[] args)
{
String S="javaisplatformindependent";
int l=S.length();
int count=0;
char c;
for(int i=0; i<l;i++)
{
c=S.charAt(i);
if(c=='a'||c=='A')
{
count++;
}
}
System.out.println("The Occurrence of 'a' is: "+count);
}
}

Output:-

The Occurrence of 'a' is: 3


Unit-3, Question-5 Design a class named Fan to represent a fan. The class
contains:
- Three constants named SLOW, MEDIUM and FAST with values 1, 2
and 3 to denote the fan speed.
- An int data field named speed that specifies the speed of the fan
(default SLOW).
- A boolean data field named f_on that specifies whether the fan is on
(default false).
- A double data field named radius that specifies the radius of the fan
(default 4).
- A data field named color that specifies the color of the fan (default
blue).
- A no-arg constructor that creates a default fan.
- A parameterized constructor initializes the fan objects to given values.
- A method named display() will display description for the fan. If the
fan is on, the display() method displays speed, color and radius. If the
fan is not on, the method returns fan color and radius along with the
message “fan is off”. Write a test program that creates two Fan objects.
One with default values and the other with medium speed, radius 6,
color brown, and turned on status true. Display the descriptions for two
created Fan objects.
class Fan
{
public static final int SLOW=1;
public static final int Medium=2;
public static final int Fast=3;
int speed;
boolean f_on;
double radius;
String colour;

Fan()
{
speed=SLOW;
f_on=false;
radius=4;
colour="blue";
}

Fan(int s, boolean status, double r,String c)


{
speed=s;
f_on=status;
radius=r;
colour=c;
}

void display()
{
if(f_on==true)
{
System.out.println("The Speed of the Fan is: "+speed);
System.out.println("The Radius of the Fan is: "+radius);
System.out.println("The Colour of the Fan is: "+colour);
}

else
{
System.out.println("The Fan is Off");
System.out.println("The Radius of the Fan is: "+radius);
System.out.println("The Colour of the Fan is: "+colour);
}
}
}

class FanMain
{

public static void main(String[] args)


{
Fan f1=new Fan();
f1.display();

Fan f2=new Fan(3,true,5,"Black");


f2.display();
}

Output:-

The Fan is Off


The Radius of the Fan is: 4.0
The Colour of the Fan is: blue
The Speed of the Fan is: 3
The Radius of the Fan is: 5.0
The Colour of the Fan is: Black
Unit-3, Question-6, Define the Rectangle class that contains:
Two double fields x and y that specify the center of the rectangle, the data
field width and height, A no-arg constructor that creates the default
rectangle with (0,0) for (x,y) and 1 for both width and height. 2 A
parameterized constructor creates a rectangle with the specified x,y,height
and width.
-A method getArea() that returns the area of the rectangle.
-A method getPerimeter() that returns the perimeter of the rectangle.
-A method contains(double x, double y) that returns true if the specified
point (x,y) is inside this rectangle.
Write a test program that creates two rectangle objects. One with default
values and other with user specified values. Test all the methods of the class
for both the objects.
class Rectangle
{
double centerX, centerY, height, width;
double x1,x2,x3,x4,y1,y2,y3,y4;

Rectangle()
{
centerX=0;
centerY=0;
height=1;
width=1;
}

Rectangle(double x,double y,double h,double w)


{
centerX=x;
centerY=y;
height=h;
width=w;
}

double getArea()
{
return (height*width);
}

double getPerimeter()
{
return (2*(height+width));
}

boolean contains(double x, double y)


{
x1=x3=(centerX-(width/2));
x2=x4=(centerX+(width/2));
y1=y2=(centerY+(height/2));
y3=y4=(centerY-(height/2));

if((x>x1 && x<x2) && (y<y1 && y>y3))


{
return true;
}

else
{
return false;
}
}
}

class RectangleTest
{

public static void main(String[] args)


{
Rectangle r1=new Rectangle();
System.out.println("The Area of the Rectangle is: "+r1.getArea());
System.out.println("The Perimeter of the Rectangle is: "+r1.getPerimeter());
System.out.println("The Point (2.5,2.5) is in Rectangle is: "+r1.contains(2,3));

Rectangle r2=new Rectangle(2.0,2.0,2.0,2.0);


System.out.println("The Area of the Rectangle is: "+r2.getArea());
System.out.println("The Perimeter of the Rectangle is: "+r2.getPerimeter());
System.out.println("The Point (2.5,2.5) is in Rectangle is:
"+r2.contains(2.5,2.5));
}

Output:-

The Area of the Rectangle is: 1.0


The Perimeter of the Rectangle is: 4.0
The Point (2.5,2.5) is in Rectangle is: false
The Area of the Rectangle is: 4.0
The Perimeter of the Rectangle is: 8.0
The Point (2.5,2.5) is in Rectangle is: true
Unit-3, Question-10, The abstract Vegetable class has three subclasses
named Potato, Brinjal and Tomato. Write an application that demonstrates
how to establish this class hierarchy. Declare one instance variable of type
String that indicates the color of a vegetable. Create and display instances
of these objects. Override the toString() method of Object to return a string
with the name of the vegetable and its color.
abstract class Vegetable
{
String vegColour;
abstract public String toString();
}

class Potato extends Vegetable


{
public String toString()
{
vegColour="Yellow";
return vegColour;
}
}

class Brinjal extends Vegetable


{
public String toString()
{
vegColour="Violet";
return vegColour;
}
}

class Tomato extends Vegetable


{
public String toString()
{
vegColour="Red";
return vegColour;
}
}
class VegetableMain
{

public static void main(String[] args)


{

Vegetable p=new Potato();


Vegetable b=new Brinjal();
Vegetable t=new Tomato();
System.out.println("The Colour of the Potato is: "+p.toString());
System.out.println("The Colour of the Brinjal is: "+b.toString());
System.out.println("The Colour of the Tomato is: "+t.toString());

Output:-

The Colour of the Potato is: Yellow


The Colour of the Brinjal is: Violet
The Colour of the Tomato is: Red
Unit-3, Question-16, Describe abstract class called Shape which has three
subclasses say Triangle,Rectangle,Circle. Define one method area() in the
abstract class and override this area() in these three subclasses to calculate
for specific object i.e. area() of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle.
abstract class Shape
{
double dim1;
double dim2;

Shape(double d1, double d2)


{
dim1=d1;
dim2=d2;
}
abstract double area();
}

class Rectangle extends Shape


{
Rectangle(double d1, double d2)
{
super(d1,d2);
}
double area()
{
return(dim1*dim2);
}
}

class Triangle extends Shape


{
Triangle(double d1, double d2)
{
super(d1,d2);
}
double area()
{
return(dim1*dim2)/2;
}
}

class Circle extends Shape


{
double pi=3.14;
Circle(double d1, double d2)
{
super(d1,d2);
}
double area()
{
return(pi*dim1*dim1);
}
}

class ShapeMain
{
public static void main(String[] args)
{
Shape s1;
Rectangle r1=new Rectangle(10.5,20.5);
Triangle t1=new Triangle(15.5,25.5);
Circle c1=new Circle(30,40);

s1=r1;
System.out.println("The Area of Rectangle is: "+s1.area());

s1=t1;
System.out.println("The Area of Triangle is: "+s1.area());

s1=c1;
System.out.println("The Area of Circle is: "+s1.area());
}
}

Output:-
The Area of Rectangle is: 215.25
The Area of Triangle is: 197.625
The Area of Circle is: 2826.0
Unit-3, Question-22, It is required to compute SPI (semester performance
index) of n students of your college for their registered subjects in a
semester.
Declare a class called student having following data members: id_no,
no_of_subjects_registered, subject_code, subject_credits, grade_obtained
and spi.
- Define constructor and calculate_spi methods.
- Define main to instantiate an array for objects of class student to process
data of n students to be given as command line arguments.

Without Using Scanner


/* Print GTU marksheet of current sem - for n no of students of your
class using array of Objects*/

class Student
{
String eNo;
String[] subNames=new String[4];
int[] subCodes=new int[4];
String[] obtGreades=new String[4];
int[] subCredits=new int[4];
Student(String eno,String[] sname,int[] scode,String[]
ogrd,int[] scs)
{
eNo=eno;
subNames=sname;
subCodes=scode;
obtGreades=ogrd;
subCredits=scs;
}
float calSPI()
{
float spi=0.0f;
float sum=0.0f;
int totalCredits=0;
String[]
greads={"AA","AB","BB","BC","CC","CD","DD","FF"};
int[] gValues={10,9,8,7,6,5,4,3};
for(int i=0;i<obtGreades.length;i++)
{
String gread=obtGreades[i];
int gv=0;

for(int j=0;j<greads.length;j++)
{
if(gread.equals(greads[j]))
{
gv=gValues[j];
break;
}
}
sum=sum+(gv*subCredits[i]);
totalCredits +=subCredits[i];
}
spi=sum/totalCredits;
return spi;
}
void displayMarksheet()
{
System.out.println("Enrollment NO"+eNo+"\n");
for(int i=0;i<subNames.length;i++)
{
System.out.println(subNames[i]+"-"+subCodes[i]+"-
"+subCredits[i]+"-"+obtGreades[i]+"\n");
}
System.out.println("-------------------------------
\n SPI="+calSPI());
}
}

class studentdemo
{
public static void main(String [] arg)
{
int ns=10;//IntegerparseInt(arg[0]);
Student[] studs=new Student[ns];
String en="16032016006";
String[] sns={"Java","CG","SP","ADA"};
int[] scode={21,22,23,24};
String[] sGds={"AA","AB","BB","BC"};
int[] scredits={8,6,5,6};
studs[0]=new
Student(en,sns,scode,sGds,scredits);
studs[0].displayMarksheet();
}
}

Using Scanner
import java.util.Scanner;
class Student
{
int id_no;
int no_of_subjects_registered;
int total_credit=0;
int sub_code[]=new int[10];
int sub_credit[]=new int[10];
int temp[]=new int[10];
int g_point[]=new int[10];
String grade_obtained;
String grade_obt[]=new String[10];
float spi=0;

Student(int id, int no_sub)


{
id_no=id;
no_of_subjects_registered=no_sub;
}

void get_subdata(int n,int s_code,int s_credit,String g_obt)


{
sub_code[n]=s_code;
sub_credit[n]=s_credit;
grade_obt[n]=g_obt;

if(grade_obt[n].equals("AA"))
{
g_point[n]=10;
}
else if(grade_obt[n].equals("AB"))
{
g_point[n]=9;
}
else if(grade_obt[n].equals("BB"))
{
g_point[n]=8;
}
else if(grade_obt[n].equals("BC"))
{
g_point[n]=7;
}
else if(grade_obt[n].equals("CC"))
{
g_point[n]=6;
}
else if(grade_obt[n].equals("CD"))
{
g_point[n]=5;
}
else if(grade_obt[n].equals("DD"))
{
g_point[n]=4;
}
else if(grade_obt[n].equals("FF"))
{
g_point[n]=0;
}
}

void student_details()
{
System.out.println("");
System.out.println("Student id:"+id_no);
System.out.println("");
System.out.println("No of Subjects:"+no_of_subjects_registered);
System.out.println("\tSub Code\tSub Credit\tGrade obtained");

for(int i=0;i<no_of_subjects_registered;i++)
{

System.out.println("\t"+sub_code[i]+"\t\t"+sub_credit[i]+"\t"+grade_obt[i]);
}

void count_spi()
{
int ans=0;
for(int i=0;i<no_of_subjects_registered;i++)
{
temp[i]=sub_credit[i]*g_point[i];
ans=ans+temp[i];
total_credit=sub_credit[i]+total_credit;
}

spi=ans/total_credit;
System.out.println(ans+""+total_credit);
System.out.println("Congratulations Your SPI is: "+spi);
System.out.println("");
System.out.println("");
}
}

class SPIMain
{

public static void main(String[] args)


{

int num=Integer.parseInt(args[0]);
Student s[]=new Student[num];
Scanner sc=new Scanner(System.in);

for(int i=0;i<num;i++)
{
int z=i+1;
System.out.println("");
System.out.println("Enter the Details for Student num:"+z);
System.out.println("");
System.out.println("Enter Student ID:");
int id=sc.nextInt();
System.out.println("Enter Number of Subjects:");
int sub=sc.nextInt();
s[i]=new Student(id,sub);

for(int j=0;j<sub;j++)
{
System.out.println("");
int y=j+1;
System.out.println("For Subject"+y);
System.out.println("");
System.out.println("Enter Subject Code:");
int s_cod=sc.nextInt();
System.out.println("Enter Subject Credit:");
int s_cre=sc.nextInt();
sc.nextLine();
System.out.println("Enter Grade:");
String s_gra=sc.nextLine();
s[i].get_subdata(j,s_cod,s_cre,s_gra);
}

s[i].student_details();
s[i].count_spi();
}
}

Output:-
Enter the Details for Student num:1

Enter Student ID:


007
Enter Number of Subjects:
4

For Subject1

Enter Subject Code:


160701
Enter Subject Credit:
5
Enter Grade:
BC

For Subject2
Enter Subject Code:
160702
Enter Subject Credit:
6
Enter Grade:
BB

For Subject3

Enter Subject Code:


160703
Enter Subject Credit:
6
Enter Grade:
AB

For Subject4

Enter Subject Code:


160704
Enter Subject Credit:
5
Enter Grade:
CC

Student id:7

No of Subjects:4
Sub Code Sub Credit Grade obtained
160701 5 BC
160702 6 BB
160703 6 AB
160704 5 CC
16722
Congratulations Your SPI is: 7.0

Enter the Details for Student num:2

Enter Student ID:


021
Enter Number of Subjects:
4

For Subject1

Enter Subject Code:


160701
Enter Subject Credit:
5
Enter Grade:
BB

For Subject2

Enter Subject Code:


160702
Enter Subject Credit:
6
Enter Grade:
AB

For Subject3

Enter Subject Code:


160703
Enter Subject Credit:
6
Enter Grade:
BB

For Subject4

Enter Subject Code:


160704
Enter Subject Credit:
5
Enter Grade:
BC

Student id:21

No of Subjects:4
Sub Code Sub Credit Grade obtained
160701 5 BB
160702 6 AB
160703 6 BB
160704 5 BC
17722
Congratulations Your SPI is: 8.0
Unit-3, Question-23 , . Write a program to define abstract class, with two
methods addition() and subtraction(). addition() is abstract method.
Implement the abstract method and call that method using a program(s).
abstract class Operation
{
int x,y;
Operation(int i,int j)
{
x=i;
y=j;
}
abstract void addition();
void subtraction()
{
int sub=x-y;
System.out.println("The Subtraction is: "+sub);
}

class OperationSub extends Operation


{
OperationSub(int i,int j)
{
super(i,j);
}

void addition()
{
int add=x+y;
System.out.println("The Addition is: "+add);
}
}

class OperationMain
{
public static void main(String[] args)
{
OperationSub obj=new OperationSub(50,30);
obj.addition();
obj.subtraction();
}
}

Output:-

The Addition is: 80


The Subtraction is: 20
Unit-4, Question-4, Write a program that illustrates interface inheritance.
Interface P is extended by P1 And P2. Interface P12 inherits from both P1
and P2.Each interface declares one constant and one method. Class Q
implements P12.Instantiate Q and invokes each of its methods. Each
method displays one of the constants.

interface P
{
public static final int p=10;
void method_p();
}

interface P1 extends P
{
public static final int p1=20;
void method_p1();
}

interface P2 extends P
{
public static final int p2=30;
void method_p2();
}

interface P12 extends P1,P2


{
public static final int p12=40;
void method_p12();
}

class Q implements P12


{
public void method_p()
{
System.out.println("The Value of p from Interface P: "+p);
}
public void method_p1()
{
System.out.println("The Value of p1 from Interface P1: "+p1);
}
public void method_p2()
{
System.out.println("The Value of p2 from Interface P2: "+p2);
}
public void method_p12()
{
System.out.println("The Value of p12 from Interface P12: "+p12);
}
}

class InterfaceMain
{

public static void main(String[] args)


{
Q obj_q=new Q();
obj_q.method_p();
obj_q.method_p1();
obj_q.method_p2();
obj_q.method_p12();

Output:-

The Value of p from Interface P: 10


The Value of p1 from Interface P1: 20
The Value of p2 from Interface P2: 30
The Value of p12 from Interface P12: 40
Unit-4, Question-6, The Transport interface declares a deliver() method.
The abstract class Animal is the superclass of the Tiger, Camel, Deer and
Donkey classes. The Transport interface is implemented by the Camel and
Donkey classes. Write a test program that initialize an array of four
Animal objects. If the object implements the Transport interface, the
deliver() method is invoked.

interface Transport
{
void deliver();
}

abstract class Animal


{
abstract void jungle();
}

class Tiger extends Animal


{
public void jungle()
{
System.out.println("This is the Tiger Method!!!");
}
}

class Camel extends Animal implements Transport


{
public void jungle()
{
System.out.println("This is the Camel Method!!!");
}
public void deliver()
{
System.out.println("Hey Camel! We need to Deliver you to your Owner!!!");
}
}

class Deer extends Animal


{
public void jungle()
{
System.out.println("This is the Deer Method!!!");
}
}

class Donkey extends Animal implements Transport


{
public void jungle()
{
System.out.println("This is the Donkey Method!!!");
}
public void deliver()
{
System.out.println("Hey Donkey! We also need to Deliver you to your
Owner!!!");
}
}
class AnimalMain
{
public static void main(String[] args)
{
Tiger t1=new Tiger();
t1.jungle();
Transport t2=new Camel();
t2.deliver();
Deer d2=new Deer();
d2.jungle();
Transport t3=new Donkey();
t3.deliver();

Output:-

This is the Tiger Method!!!


Hey Camel! We need to Deliver you to your Owner!!!
This is the Deer Method!!!
Hey Donkey! We also need to Deliver you to your Owner!!!
Unit-4, Question-9, Write a program to demonstrate combination of both
types of inheritance as shown in figure 1. i.e. hybrid inheritance.

interface A
{
void sum();
}

interface B
{
void sub();
}

class C implements A,B


{
int x=100,y=50;
public void sum()
{
int z=x+y;
System.out.println("The Addition is: "+z);
}
public void sub()
{
int z=x-y;
System.out.println("The Subtraction is: "+z);
}
}

class D extends C
{
void display()
{
sum();
sub();
}
}
class HybridEMain
{
public static void main(String[] args)
{
D obj_d=new D();
obj_d.display();
}

Output:-

The Addition is: 150


The Subtraction is: 50
Unit-4, Question-10, Write a program to demonstrate the multipath
inheritance for the classes having relations as shown in figure 2 A-> (B, C) -
>D.

interface A
{
int x=20;
int y=10;
}

interface B extends A
{
void sum();
}

interface C extends A
{
void sub();
}

class D implements B,C


{
public void sum()
{
int z=x+y;
System.out.println("The Addition is: "+z);
}
public void sub()
{
int z=x-y;
System.out.println("The Subtraction is: "+z);
}
}
class MultipathEMain
{

public static void main(String[] args)


{
D obj_d=new D();
obj_d.sum();
obj_d.sub();
}

Output:-

The Addition is: 30


The Subtraction is: 10
Unit-6, Question-3, Write an application that generates custom exception if
any value from its command line arguments is negative.
class CustomException extends Exception
{

public String toString()


{
return "You can not Enter Neative Value Here!";
}
}
class CustomNegativeException
{
public static void main(String[] args)
{
String s=args[0];
int i=Integer.parseInt(s);

try
{
if(i<0)
{
throw new CustomException();
}
else
{
System.out.println("The Number is:"+i);
}
}
catch(CustomException e)
{
System.out.println("The Error is:"+e);
}
}

Output:-

The Error is:You can not Enter Neative Value Here!


Unit-6, Question-5, Write a method for computing xy by doing repetitive
multiplication. x and y are of type integer and are to be given as command
line arguments. Raise and handle exception(s) for invalid values of x and y.
Also define method main. Use finally in above program and explain its
usage.

class RepeatativeMultiplication
{

public static void main(String[] args)


{
int x,y,z;
String s1=args[0], s2=args[1];
try
{
x=Integer.parseInt(s1);
y=Integer.parseInt(s2);
z=1;
for(int i=0; i<y;i++)
{
z=z*x;
}
System.out.println(x+"^"+y+":"+z);
}
catch(NumberFormatException e)
{
System.out.println("Number Format Exception:"+e);
}

finally
{
System.out.println("This will Execute Every Time!!!");
}
}

Output:-

5^10:9765625
This will Execute Every Time!!!
Unit-6, Question-6, Write a program to handle NoSuchMethodException,
ArrayIndexOutofBoundsException using try-catch-finally and throw.

Program-1: NoSuchMethodException

import java.lang.reflect.Method;
class NoSuchMethod
{
public static void main(String[] args)
{
Class c=java.lang.Math.class;
try
{
Class name[]=new Class[5];
Method m=c.getDeclaredMethod("Mymethod",name);
}
catch(NoSuchMethodException e)
{
e.printStackTrace();
}
}
}

Output:-

java.lang.NoSuchMethodException: java.lang.Math.Mymethod(null, null, null, null,


null)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at Programs.NoSuchMethod.main(NoSuchMethod.java:10)

Program-2:ArrayIndexOutOfBoundsException

class ArrayIndexOutOfBounds
{
public static void main(String[] args)
{
try
{
int a[]={10,20,30,40,50};
a[5]=60;
System.out.println(a[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
//System.out.println("The Error is:"+e);
}
finally
{
System.out.println("Whatever it is, I'll Execute Every Time!!!");
}
}
}

Output:-

Whatever it is, I'll Execute Every Time!!!


java.lang.ArrayIndexOutOfBoundsException: 5
at Programs.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:8)
Unit-6, Question-7, Write a program to handle InterruptedException,
IllegalArgumentException using try-cat-finally and throw.

Program-1: InterruptedException

class Interrupt implements Runnable


{
public void run()
{
System.out.println(Thread.currentThread().getName()+" started");
try
{
Thread.sleep(10000);
for(int i=0;i<10;i++)
{
if(Thread.interrupted())
{
System.out.println("Thread interrupted");
break;
}
}
}
catch(InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+" interrupted");
}
System.out.println(Thread.currentThread().getName()+" stopped");
}
}
class InterruptThread
{
public static void main(String[] args)
{
Interrupt obj1=new Interrupt();
Thread t1=new Thread(obj1, "Thread1");
Interrupt obj2=new Interrupt();
Thread t2=new Thread(obj2, "Thread2");
Interrupt obj3=new Interrupt();
Thread t3=new Thread(obj3, "Thread3");
try
{
t1.start();
Thread.sleep(1000);
t1.interrupt();
t2.start();
Thread.sleep(3000);
t2.interrupt();
t3.start();
Thread.sleep(2000);
t3.interrupt();
t3.join();
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
finally
{
System.out.println("Bye Bye All!!!");
}
}
}

Output:-

Thread1 started
Thread1 interrupted
Thread1 stopped
Thread2 started
Thread2 interrupted
Thread2 stopped
Thread3 started
Thread3 interrupted
Thread3 stopped
Bye Bye All!!!

Program-2: IllegalArgumentException

class IllegalArgument
{
public static void main(String[] args)
{
String A="I Love Java";
String B="Java";
String C=A.replaceAll(B, "$PHP");
System.out.println("C");
}
}

Output:-
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group
reference
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at Programs.IllegalArgument.main(IllegalArgument.java:8)
Unit-6, Question-8, Explain the importance of exception handling in java.
Which key words are used to handle exceptions? Write a program to
explain the use of these keywords.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
class ExceptionHandling
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream("src/Programs/DestinationFile.txt");
if(args[0]==null)
{
throw new ArrayIndexOutOfBoundsException();
}
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
return;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("The Error is:"+e);
return;
}
finally
{
System.out.println("I am Finally & I wil always Execute!!!");
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Output:-

I am Finally & I wil always Execute!!!


difficulty was that it would be at least a month before the squire could get a letter and
dennis could get his money; but if we couldnt keep our heads above water for a month
wed small chance of pushing our way in the world.
Unit-7, Question-10, Write an application that creates and starts three
threads. Each thread is instantiated from the same class. It executes a loop
with 10 iterations. Each iteration displays string "HELLO", sleeps for 300
milliseconds. The application waits for all the threads to complete &
displays the message "Good Bye..."
class ThreadCreate extends Thread
{
String name;
ThreadCreate(String threadName)
{
name=threadName;
}
public void run()
{
for(int i=0;i<10;i++)
{
try
{
System.out.println(name+": Hello!!!");
sleep(300);
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
}
}
}
class ThreadJoin
{
public static void main(String[] args)
{
ThreadCreate thread1=new ThreadCreate("Thread1");
ThreadCreate thread2=new ThreadCreate("Thread2");
ThreadCreate thread3=new ThreadCreate("Thread3");
thread1.start();
thread2.start();
thread3.start();
try
{
thread1.join();
thread2.join();
thread3.join();
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
System.out.println("Time to say GoodBye!!!");
}
}

Output:-

Thread2: Hello!!!
Thread1: Hello!!!
Thread3: Hello!!!
Thread2: Hello!!!
Thread1: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Thread1: Hello!!!
Thread2: Hello!!!
Thread3: Hello!!!
Time to say GoodBye!!!
Unit-7, Question-11, Write an application that executes two threads. One
thread displays "Good Morning" every 1000 milliseconds & another
thread displays "Good Afternoon" every 3000 milliseconds. Create the
threads by implementing the Runnable interface.
class TimerThread1 implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
try
{
System.out.println("Good Morning!!!");
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
}
}
}
class TimerThread2 implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(3000);
System.out.println("Good Afternoon!!!");
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
}
}
}
class TimerThread
{
public static void main(String[] args)
{
TimerThread1 time1=new TimerThread1();
Thread t1=new Thread(time1);
t1.start();
TimerThread2 time2=new TimerThread2();
Thread t2=new Thread(time2);
t2.start();
}

Output:-

Good Morning!!!
Good Morning!!!
Good Morning!!!
Good Afternoon!!!
Good Morning!!!
Good Morning!!!
Good Morning!!!
Good Afternoon!!!
Good Morning!!!
Good Morning!!!
Good Morning!!!
Good Afternoon!!!
Good Morning!!!
Good Afternoon!!!
Good Afternoon!!!
Good Afternoon!!!
Good Afternoon!!!
Good Afternoon!!!
Good Afternoon!!!
Good Afternoon!!!
Unit-7, Question-12, Write a program to create two threads, one thread
will print odd numbers and Second thread will print even numbers
between 1 to 20 numbers.
class OddThread extends Thread
{
String name;
OddThread(String threadName)
{
name=threadName;
}
public void run()
{
for(int i=1;i<=20;i++)
{
if(i%2!=0)
{
try
{
System.out.println(name+": "+i);
sleep(500);
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
}
}
}
}
class EvenThread extends Thread
{
String name;
EvenThread(String threadName)
{
name=threadName;
}
public void run()
{
for(int i=1;i<=20;i++)
{
if(i%2==0)
{
try
{
sleep(500);
System.out.println(name+": "+i);
}
catch(InterruptedException e)
{
System.out.println("The Error is:"+e);
}
}
}
}
}
class ThreadOddEven
{
public static void main(String[] args)
{
EvenThread t2=new EvenThread("EvenThread");
t2.start();
OddThread t1=new OddThread("OddThread");
t1.start();
}

Output:-

OddThread: 1
EvenThread: 2
OddThread: 3
EvenThread: 4
OddThread: 5
EvenThread: 6
OddThread: 7
EvenThread: 8
OddThread: 9
EvenThread: 10
OddThread: 11
EvenThread: 12
OddThread: 13
EvenThread: 14
OddThread: 15
EvenThread: 16
OddThread: 17
EvenThread: 18
OddThread: 19
EvenThread: 20
Unit-7, Question-14, Write a program that creates three threads. Make
sure that the main thread executes last.
class ChildThreads implements Runnable
{
String name;
Thread t;
ChildThreads(String ThreadName)
{
name=ThreadName;
t=new Thread(this, name);
System.out.println("The thread: "+t);
t.start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println(name +": "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name+" Interrupted");
}
System.out.println(name+" exiting");
}
}

class MainThreadWait
{
public static void main(String[] args)
{
ChildThreads c1=new ChildThreads("One");
ChildThreads c2=new ChildThreads("Two");
ChildThreads c3=new ChildThreads("Three");
try
{
c1.t.join();
c2.t.join();
c3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Main thread Interrupted!!!");
}
System.out.println("Main thread exiting!!!");
}
}

Output:-

The thread: Thread[One,5,main]


The thread: Thread[Two,5,main]
One: 5
The thread: Thread[Three,5,main]
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
Two: 3
One: 3
Three: 3
Two: 2
One: 2
Three: 2
One: 1
Two: 1
Three: 1
One exiting
Two exiting
Three exiting
Main thread exiting!!!
Note: Here all the Programs of Unit-8 will use only two text Files the
contents of which are as follow:

File-1: SourceFile.txt

Location:
C:\Users\Viral's\Downloads\workspace\QuestionBank\src\Programs\SourceFile.txt

Contents:
was not likely to become extinct for the loss of him, at the worst; and the squire wouldnt
grudge him a few months diversion and a peep at the wide world. far from it; hed send him
some money, and why not he dennis was a bit of a favourite for his mothers sake, and the
squire had a fine heart.

File-2: DestinationFile.txt

Location:
C:\Users\Viral's\Downloads\workspace\QuestionBank\src\Programs\DestinationFile.txt

Contents:
the real difficulty was that it would be at least a month before the squire could get a letter and
dennis could get his money; but if we couldnt keep our heads above water for a month wed
small chance of pushing our way in the world.
Unit-8, Question-1, Write a program using BufferedInputStream,
FileInputStream, BufferedOutputStream, FileOutputStream to copy
Content of one file File1.txt into another file File2.txt.
import java.io.*;
class FileCopy
{
public static void main(String[] args)
{
int x;
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
fis=new FileInputStream("src/Programs/SourceFile.txt");
fos=new FileOutputStream("src/Programs/DestinationFile.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
BufferedOutputStream bos=new BufferedOutputStream(fos);

do
{
x = bis.read();
if(x != -1) bos.write((char) x);
} while(x != -1);
System.out.println("File Successfully Copied!!!");
bis.close();
bos.close();
fis.close();
fos.close();
}
catch(FileNotFoundException e)
{
System.out.println("The Error is:"+e);
}
catch(IOException e)
{
System.out.println("The Error is:"+e);
}
}
}

Output:-
File Successfully Copied!!!
Output in File-2(DestinationFile) After execution of this Program is:
was not likely to become extinct for the loss of him, at the worst; and the squire wouldnt
grudge him a few months diversion and a peep at the wide world. far from it; hed send him
some money, and why not he dennis was a bit of a favourite for his mothers sake, and the
squire had a fine heart.
Unit-8, Question-3, Write a program to display the bytes of a file in reverse
sequence. Provide the name of the file as a command line argument. (Use
RandomAccessFile).
import java.io.*;
class FileReverse
{
public static void main(String[] args)
{
long l;
RandomAccessFile file2=null;

File file1=new File(args[0]);


if(!file1.exists())
{
System.out.println("File does Not Exists!!!");
System.exit(0);
}
try
{
file2=new RandomAccessFile(file1,"rw");
l=file1.length();
for(long i=l-1;i>=0;i--)
{
file2.seek(i);
byte b=file2.readByte();
System.out.print((char)b);
}
file2.close();
}
catch(FileNotFoundException e)
{
System.out.println("The Error is:"+e);
}
catch(IOException e)
{
System.out.println("The Error is:"+e);
}
}
}

File Passed as Command Line argument is: DestinationFile.txt

Output:-

.dlrow eht ni yaw ruo gnihsup fo ecnahc llams dew htnom a rof retaw evoba sdaeh ruo peek
tndluoc ew fi tub ;yenom sih teg dluoc sinned dna rettel a teg dluoc eriuqs eht erofeb htnom a
tsael ta eb dluow ti taht saw ytluciffid laer eht
Unit-8, Question-5, Write a program that takes input for filename and
search word from commandline arguments and checks whether that file
exists or not. If exists, the program will display those lines from a file that
contains given search word.
import java.io.*;
class WordSearch
{
public static void main(String[] args) throws IOException
{
File f1=new File(args[0]);
boolean wordcheck=false;
if(f1.exists())
{
BufferedReader br=new BufferedReader(new FileReader(f1));
String line;
String word=args[1];
while((line=br.readLine())!=null)
{
String wordarray[]=line.split(" ");
for(String tempword:wordarray)
{
if(tempword.equalsIgnoreCase(word))
{
System.out.println("The Word '"+word+"' Exists
in a Line: '"+line+"'");
wordcheck=true;
}
}
}
if(!wordcheck)
{
System.out.println("The Word doesn't Exist in a Line!!!");
}
}
else
{
System.out.println("File doesn't Exists!!!");
}
}
}

File Passed as Command Line argument is: DestinationFile.txt


Word to be searched is: dennis
Output:-

The Word 'dennis' Exists in a Line: 'the real difficulty was that it would be at least a
month before the squire could get a letter and dennis could'
Unit-8, Question-6 & 12, Write a program that counts the no. of words in a
text file. The file name is passed as a command line argument. The
program should check whether the file exists or not. The words in the file
are separated by white space characters.
import java.io.*;
class WordCount
{
public static void main(String[] args) throws IOException
{
int x,wordCount=0;
try
{
File f1=new File(args[0]);
if(f1.exists())
{
FileInputStream fis=new FileInputStream(f1);
do
{
x=fis.read();
if((char)x==' '||(char)x=='\n'||(char)x=='\t')
{
wordCount++;
}
}while(x!=-1);
System.out.println("The Total Words
are:"+(wordCount+1));
}
else
{
System.out.println("File doesn't Exists!!!");
}
}
catch(FileNotFoundException e)
{
System.out.println("The Error is:"+e);
}
}

File Passed as a Command Line Argument is: SourceFile.txt

Output:-

The Total Words are:61


Unit-8, Question-9, Write a program to replace all “word1” by “word2”
from a file1, and output is written to file2 file and display the no. of
replacement.

import java.io.*;
import java.lang.*;
class FileWordReplace
{
public static void main(String[] args) throws IOException
{
try
{
FileReader fr=new FileReader("src/Programs/DestinationFile.txt");
BufferedReader br=new BufferedReader(fr);
String line="",temp="";
int x=0,wordCount=0;

while((line=br.readLine())!=null)
{
temp=temp+line;
}

br.close();
String s[]=temp.split(" ");

for(int i=0;i<s.length;i++)
{
if(s[i].equalsIgnoreCase("the"))
{
wordCount++;
}
}
String newTemp=temp.replaceAll("the", "La");
RandomAccessFile obj=new
RandomAccessFile("src/Programs/TempFile.txt","rw");
obj.writeChars(newTemp);
System.out.println("The Total Words replaces are:"+ wordCount);
}
catch(FileNotFoundException e)
{
System.out.println("The Error is:"+e);
}
}
}

Output:-

The Total Words replaces are:2


Output in File TempFile.txt:-

difficulty was that it would be at least a month before La


squire could get a letter and dennis couldget his money; b
ut if we couldnt keep our heads above water for a month w
ed small chance of pushingour way in La world.
Unit-8, Question-11, Write a program to check that whether the name
given from command line is file or not? If it is a file then print the size of
file and if it is directory then it should display the name of all files in it.

import java.io.*;
class DirectoryFiles
{
public static void main(String[] args)
{
String dirName=args[0];
File f1=new File(dirName);
if(f1.isFile())
{
System.out.println("File Size: "+f1.length()+" bytes");
}
else if(f1.isDirectory())
{
System.out.println("Directory of: "+dirName);
String s[]=f1.list();
for(int i=0;i<s.length;i++)
{
File f2=new File(dirName+"/"+s[i]);
if(f2.isDirectory())
{
System.out.println(s[i]+" is a Direcory!");
}
else
{
System.out.println(s[i]+" is a File!");
}
}
}
}
}

Run-1, File Passed as a Command Line Argument is: SourceFile.txt

Output:

File Size: 296 bytes

Run-2, Directory Passed as a Command Line Argument is: src\Programs

Output:

Directory of: src\Programs


AnimalMain.java is a File!
BookMain.java is a File!
CountChar.java is a File!
CustomNegativeException.java is a File!
Destination.txt is a File!
DestinationFile.txt is a File!
DirectoryFiles.java is a File!
ExceptionDemo.java is a File!
ExceptionHandling.java is a File!
Fan.java is a File!
FanMain.java is a File!
FileCopy.java is a File!
FileReverse.java is a File!
FileWordReplace.java is a File!
HybridEMain.java is a File!
InterfaceMain.java is a File!
MethodException.java is a File!
MultipathEMain.java is a File!
OperationMain.java is a File!
package-info.java is a File!
RectangleTest.java is a File!
RepeatativeMultiplication.java is a File!
ShapeMain.java is a File!
SourceFile.txt is a File!
SPIMain.java is a File!
ThreadJoin.java is a File!
ThreadOddEven.java is a File!
TimerThread.java is a File!
VegetableMain.java is a File!
WordCount.java is a File!
WordReplaceCount.java is a File!
WordSearch.java is a File!
Q- Declare a class called Book having book title & author name as
members. Create a sub-class of it, called BookDetails having price &
current stock of book as members. Create an array for storing details of n
books. Define methods to achieve following:
- Initialization of members
- To query availability of a book by author name / book title
- To update stock of a book on purchase and sell
Define method main to show usage of above methods.
import java.util.Scanner;
class Book {
String title, authorName;
Book(String a1, String b1) {
title = a1;
authorName = b1;
}
}
class BookDetails extends Book {
int stock;
float price;
BookDetails(String a, String b, int c, float d) {
super(a, b);
stock = c;
price = d;
}
void display() {
System.out.println("Book-Title :" + title);
System.out.println(" -By " + authorName);
System.out.println("No. of Books Available : " +
stock);
System.out.println("Price : " + price);
System.out.println("----------------------------------
--------");
System.out.println("");
}
void purchase(int s) {
stock = stock + s;
System.out.println("Total stock available is :" +
stock);

}
void sell(int s) {
stock = stock - s;
System.out.println("Total stock updated--> available
is :" + stock);
}
public static void main(String[] args) {
BookDetails[] b = new BookDetails[3];
b[0] = new BookDetails("Java", "author1", 7, 485.5f);
b[1] = new BookDetails("ADA", "author2", 8, 200.7f);
b[2] = new BookDetails("SP", "author3", 18, 180.4f);

for (int i = 0; i < b.length; i++) {


b[i].display();
}

System.out.println("Search the book availability");


System.out.println("Enter author name:");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();

for (int i = 0; i < b.length; i++) {


if (name.equals(b[i].authorName)) {
if (b[i].stock != 0) {
System.out.println("Book is available");
System.out.println("----------------------
-------------------------");
System.out.println("");
} else {
System.out.println("Book is out of
stock");
}
}
}

System.out.println("For Book Purchase");


System.out.println("Enter subject name:");
String purchasebook = sc.nextLine();

System.out.println("No. of books you want to


purchase:");
int no_of_book_p = sc.nextInt();
sc.nextLine();

for (int i = 0; i < b.length; i++) {


if (purchasebook.equals(b[i].title)) {
b[i].purchase(no_of_book_p);
}
}
System.out.println("For Book Selling");
System.out.println("Enter subject name:");
String sellbook = sc.nextLine();

System.out.println("No. of books you want to sell:");


int no_of_book_s = sc.nextInt();
sc.nextLine();

for (int i = 0; i < b.length; i++) {


if (sellbook.equals(b[i].title)) {
b[i].sell(no_of_book_s);
}
}
}
}

/*Output:
Book-Title :Java
-By author1
No. of Books Available : 7
Price : 485.5
------------------------------------------

Book-Title :ADA
-By author2
No. of Books Available : 8
Price : 200.7
------------------------------------------

Book-Title :SP
-By author3
No. of Books Available : 18
Price : 180.4
------------------------------------------
Search the book availability
Enter author name:
author1
Book is available
-----------------------------------------------

For Book Purchase


Enter subject name:
Java
No. of books you want to purchase:
20
Total stock available is :27
For Book Selling
Enter subject name:
SP
No. of books you want to sell:
5
Total stock updated--> available is :13
*/

Q: Example Of StringBuffer
StringBuffer example in Java:-
class demo
{ public static void main(String args[])
{ StringBuffer s=new StringBuffer("L.J. Institute");
//reversing the string
s.reverse();
System.out.println(s);
s.reverse();
//replacing some letters of the string
s.replace(5,13,"college");
System.out.println(s);
//appending letters to the string
s.append(" of Engineering");
System.out.println(s);
//insert string at mentioned index position
s.insert(4,"K. ");
System.out.println(s);
//deleting letter at specified index
s.delete(4,5);
System.out.println(s);

System.out.println(s.capacity());
//s.ensureCapacity(78);
//System.out.println(s.capacity());
System.out.println(s.charAt(5));
System.out.println(s.substring(3));
}}
Compile: javac sbuffer.java Run: java demo

You might also like