JAVA_LJIET_Coding Questions
JAVA_LJIET_Coding Questions
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:-
Fan()
{
speed=SLOW;
f_on=false;
radius=4;
colour="blue";
}
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
{
Output:-
Rectangle()
{
centerX=0;
centerY=0;
height=1;
width=1;
}
double getArea()
{
return (height*width);
}
double getPerimeter()
{
return (2*(height+width));
}
else
{
return false;
}
}
}
class RectangleTest
{
Output:-
Output:-
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.
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;
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
{
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
For Subject1
For Subject2
Enter Subject Code:
160702
Enter Subject Credit:
6
Enter Grade:
BB
For Subject3
For Subject4
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
For Subject1
For Subject2
For Subject3
For Subject4
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);
}
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:-
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();
}
class InterfaceMain
{
Output:-
interface Transport
{
void deliver();
}
Output:-
interface A
{
void sum();
}
interface B
{
void sub();
}
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:-
interface A
{
int x=20;
int y=10;
}
interface B extends A
{
void sum();
}
interface C extends A
{
void sub();
}
Output:-
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:-
class RepeatativeMultiplication
{
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:-
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:-
Program-1: InterruptedException
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:-
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:-
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;
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!!!");
}
}
}
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);
}
}
Output:-
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:-
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!");
}
}
}
}
}
Output:
Output:
}
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);
/*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
-----------------------------------------------
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