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

Answer CIA FINAL Java

The document provides answers to 4 Java programming questions: 1. A menu driven program to reverse a number, find the sum of digits, and print prime numbers from 1 to 100. 2. A program to execute all String and StringBuffer functions. 3. A program to find the volume of a box using constructor overloading to initialize dimensions. 4. A program to find available and used memory before and after invoking the garbage collector.

Uploaded by

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

Answer CIA FINAL Java

The document provides answers to 4 Java programming questions: 1. A menu driven program to reverse a number, find the sum of digits, and print prime numbers from 1 to 100. 2. A program to execute all String and StringBuffer functions. 3. A program to find the volume of a box using constructor overloading to initialize dimensions. 4. A program to find available and used memory before and after invoking the garbage collector.

Uploaded by

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

Java lab manual answers

1.Write a menu driven program to


i. Reverse the number.
ii. Sum of the digits of the number.
iii. Printing the prime number between 1 to 100.

Ans:
import java.util.Scanner;
public class ca1 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("1.Reverse of number");
System.out.println("2.Sum of digits of number");
System.out.println("3.Prime number between 1 to 100");
System.out.println("Choose any option:");
int ch=s.nextInt();
switch (ch)
{
case 1:
int rem,rev=0;
System.out.println("Enter the number");
int n=s.nextInt();
while (n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
System.out.println("Reverse of number is:" +rev);
break;
case 2:
int rem1,sum=0;
System.out.println("Enter the number");
int n1=s.nextInt();
while (n1>0)
{
rem=n1%10;
sum=sum+rem;
n1=n1/10;
}
System.out.println("The sum of the digits of the number is:"+ sum);
break;
case 3:
int factor=0;
for (int j=1;j<=100;j++)
{
for (int i=1;i<=j;i++)
{
if (j%i==0)
factor++;
}
if (factor==2)
System.out.print(j+ " ");
factor=0;
}
break;
default:System.out.println("Invalid entry");
}
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

2. Write a java program to execute all String and StringBuffer


functions.
Ans:
import java.util.Scanner;
import java.lang.*;
class Ca1
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER YOUR CHOICE");
System.out.println("1.String functions\n2.StringBuffer functions");
int ch=sc.nextInt();
switch(ch)
{
case 1: String s1 = "Jain";
System.out.println("Concat using String:");
String str1 = s1.concat(" University") ;
System.out.println("Concatenated String is: " + str1);

System.out.println("length of String str1 is:"+ str1.length());

System.out.println("Character at position 5: " + str1.charAt(5));

System.out.println("Index of character 'a': " + str1.indexOf('a'));

System.out.println("uppercase:"+str1.toUpperCase());

System.out.println("lowercase:"+str1.toLowerCase());
String s=" hello ";
System.out.println(s);
System.out.println(s.trim());
String s2="hello";
String s3="hemlo";
System.out.println(s2.compareTo(s3));
String replaceString=str1.replace('i','z');
System.out.println(replaceString);
break;
case 2: StringBuffer sb1 = new StringBuffer("Jain");
System.out.println("Concat using StringBuffer:");
sb1.append("University");
System.out.println("StringBuffer: " + sb1);
sb1.insert(1,"Java");
System.out.println("String after inserting:"+sb1);
sb1.delete(1,5);
System.out.println("string after deleting:"+sb1);
sb1.replace(1,3,"Java");
System.out.println(sb1);
sb1.reverse();
System.out.println(sb1);
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
break;
}
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________
3. Write a program to find the volume of the box and use the
constructors to initialize the different dimensions of the box
(Constructor Overloading).
Ans:
class Constructor
{
int width,height,length;
Constructor()
{
width=10;
height=10;
length=10;
}
Constructor(int w,int h,int l)
{
width=w;
height=h;
length=l;
}
Constructor(Constructor c)
{
width=c.width;
height=c.height;
length=c.length;
}
float volume()
{
return(width*height*length);
}
}
class Consoverload
{
public static void main(String args[])
{
Constructor c1=new Constructor();
Constructor c2=new Constructor(20,30,40);
Constructor c3=new Constructor(c1);
System.out.println(c1.volume());
System.out.println(c2.volume());
System.out.println(c3.volume());
}
}
OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

4. Write a program to find the available memory and used memory


before and after invoking the garbage collector.
Ans:
class memoryDemo
{
public static void main(String arg[])
{
Runtime r = Runtime.getRuntime();
long memory1, memory2;
long mb=1024*1024;
Integer integer[] = new Integer[1000];
System.out.println("Total memory is: "
+ r.totalMemory()/mb);
memory1 = r.freeMemory()/mb;
System.out.println("Initial free memory: "
+ memory1);
r.gc();
memory1 = r.freeMemory()/mb;
System.out.println("Free memory after garbage "
+ "collection: " + memory1);
for (int i = 0; i < 1000; i++)
integer[i] = new Integer(i);
memory2 = r.freeMemory()/mb;
System.out.println("Free memory after allocation: "+ memory2);
System.out.println("Memeory used by allocation: " + (memory1 - memory2));
for (int i = 0; i < 1000; i++)
integer[i] = null;
r.gc();
memory2 = r.freeMemory()/mb;
System.out.println("Free memeory after "
+ "collecting discarded Integers: " + memory2);
}
}
OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

5. Write a java program to create an applet for login page.


Ans:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Login extends Applet implements ActionListener


{
TextField t,t1;
String s3;
Label name,pass;
Button b;
public void init()
{

Label name =new Label("username");


add(name);

t=new TextField(20);
add(t);

Label pass =new Label("password");


add(pass);

t1=new TextField(20);
add(t1);
t1.setEchoChar('*');
Button b = new Button("login");
add(b);

b.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String str =ae.getActionCommand();

String s1=t.getText();
String s2=t1.getText();
int i=1;

{
if(s1.equals("adlin") && s2.equals("adlin"))
{
s3="Login Successful";
t.setText("");
t1.setText("");
repaint();
}

else
{
i++;
t.setText("");
t1.setText("");}

if(i==3)
System.exit(0);
}
}

public void paint(Graphics g)


{

g.drawString(s3,500,400);

}
}

OUTPUT:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_________________________________________________________

6. Write a program to take a number from keyboard, create an array of that


size, insert element in existing array and display it .
Ans:
package lab6;
import java.util.*;
public class Lab6 {
public static void main(String[] args) {
int n, pos, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n+1];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the position where you want to insert element:");
pos = s.nextInt();
System.out.print("Enter the element you want to insert:");
x = s.nextInt();
for(int i = (n-1); i >= (pos-1); i--)
{
a[i+1] = a[i];
}
a[pos-1] = x;
System.out.print("After inserting:");
for(int i = 0; i < n; i++)
{
System.out.print(a[i]+",");
}
System.out.print(a[n]);
}
}
OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

7. Write a program to create the class Course which contain static variable
course_name=”BCA” and instance variable subject1,subject2, subject3.

class College
{
static char [] course_name=”BCA”;
char [] subject1;
char [] subject2;
cahr [] subject3;
College(int a,int b,int c)
{
this.subject1=a;
this.subject2=b;
this.subject3=c;
}
void display(){
System.out.println(“College” +course_name);

System.out.println(“Subjects”+subject1+”,”+subject2+”,”+subject3);}
}
class Demo_Static{

public static void main(String a[]){


College c1=new College(“Java”,”C”,”RDBMS”);
c1.display();
}
}
OUTPUT:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_________________________________________________________

8. Write a JAVA program which performs multiple Inheritance using


Interface LivingBeing, Animal. Dog is the child class which implements
status(),move(),eat().
Ans:
interface LivingBeing
{
String drink=”Water”;
void status();
}
interface Animal extends LivingBeing
{
void eat();
void move();
}
public class Dog implements Animal
{
public void status()
{
System.out.println(“Living”);
}
public void eat()
{
System.out.println(“It eats food also drink “+drink);
}

public void move()


{
System.out.println(“It will move faster than cat”);
}
public static void main(String[] args)
{
Dog d=new Dog();
d.status();
d.eat();
d.move();
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

9. Write a program to implement KeyListener interface.

public class EventDemo extends Applet implements KeyListener


{
String str;
char c;
public void init()
{
str=“Key Listener”;
addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
showStatus(“Key Pressed”);
}
public void keyReleased(KeyEvent e)
{
showStatus(“Key Released”);
}
public void keyTyped(KeyEvent e)
{
c=(e.getKeyChar());
repaint();
}
public void paint(Graphics g)
{
g.drawString(“Event listener is: “;+c,10,10);
g.drawString(“Event listener is: “;+str,50,50);
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

10.Write a program to display the records from the table Person having field
id, name,dob.

import java.sql.*;

public class JdbcExecutequery {


public static void main(String args[]) {

Connection con = null;


Statement st = null;
ResultSet rs = null;

String url = "jdbc:mysql://localhost:3306/";


String db = "komal";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";

try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);
st = con.createStatement();

String sql = "select * from person";


rs = st.executeQuery(sql);

System.out.println("no. \tName \tDob");


while (rs.next()) {
System.out.print(rs.getString("id") + " \t");
System.out.print(rs.getString("cname") + " \t");
System.out.println(rs.getDate("dob"));
}
} catch (Exception e) {
System.out.println(e);
}
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________
11. Program to demonstrate the AWT Action Listener.

import java.awt.*;
import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {


private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtListenerDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showActionListenerDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});

headerLabel = new Label();


headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showActionListenerDemo(){


headerLabel.setText("Listener in action: ActionListener");

ScrollPane panel = new ScrollPane();


panel.setBackground(Color.magenta);

Button okButton = new Button("OK");

okButton.addActionListener(new CustomActionListener());
panel.add(okButton);
controlPanel.add(panel);

mainFrame.setVisible(true);
}

class CustomActionListener implements ActionListener{

public void actionPerformed(ActionEvent e) {


statusLabel.setText("Ok Button Clicked.");
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

12. Write a program to synchronize the operation of withdraw and deposite


using threading concept.

class Customer{
int amount=10000;
Synchronized void withdraw(int amount){
System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test

{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run(){c.deposit(10000);}
}.start();

}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________
12. Write a program to perform multi-threading operation.

class A extends Thread


{
public void run()
{
System.out.println("Thread A strated");
for(int i=0;i<=5;i++)
{
System.out.println("For thread A = "+i);
}
System.out.println("Exit from Thread A");
}

class B extends Thread


{
public void run()
{
System.out.println("Thread B strated");
for(int i=0;i<=5;i++)
{
System.out.println("For thread B = "+i);
}
System.out.println("Exit from Thread B");
}

public class ThreadPriority


{
public static void main(String args[])
{
A th1=new A();
B th2=new B();
th1.setPriority(Thread.NORM_PRIORITY);
th2.setPriority(th1.getPriority()+3);
System.out.println("Start thread A");
th1.start();

System.out.println("Start Thread B");


th2.start();
System.out.println("End of Main Thread");
}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

13. WAP to demonstrate the exceptions in a menu driven format. The program must have
ArithmeticException, NullPointerException, StringIndexOutOfBoundsException,
FileNotFoundException, ArrayIndexOutOfBoundsException, NumberFormatException and a
finally block.
package firstclass;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class Demo {

public static void main(String[] args) {


try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
try {

// Following file does not exist


File file = new File("E://file.txt");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
finally{System.out.println("finally block is always executed");}
}

OUTPUT:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_____________________

You might also like