Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 01: WAP in java to simulate condition to generate Wi-Fi password. Take input as Name,
City, Age and Gender.
CODE:
import java.util.Scanner;
class q1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Criteria: Length of Name and City Greater than 3 and age!=18\n");
System.out.println("Enter your Name = ");
String Name = sc.nextLine();
System.out.println("Enter your City=");
String City = sc.nextLine();
System.out.println("Enter your Gender (M or F)");
char gender = sc.next().charAt(0);
System.out.println("Enter your Age=");
int age = sc.nextInt();
if (Name.length() < 3 || City.length() < 3 || age < 10)
{
System.out.println("You are not matching the Criteria");
return;
}
if (gender == 'M' || gender == 'm')
{
int pwd2 = 0;
String pwd1 = Name.substring(0, 3);
String pwd3 = City.substring(City.length() - 3, City.length());
while (age != 0) {
pwd2 = age % 10;
if (pwd2 < 0)
pwd2 = -pwd2;
age = age / 10;

1
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

}
System.out.println("WifiPassword is = " + pwd1 + pwd2 + pwd3);
} else if (gender == 'F' || gender == 'f')
{
int pwd2 = 0;
String pwd1 = Name.substring(0, 3);
String pwd3 = City.substring(Name.length() - 3, Name.length());
while (age != 0) {
pwd2 += age % 10;
age = age / 10;
}
System.out.println("WifiPwd is = " + pwd1 + pwd2 + pwd3);
}
}
}
OUTPUT:

2
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 02: WAP in Java to initialize a string in order to find that character which frequency is
2nd most in that string.
CODE:
import java.util.Scanner;
public class q2 {
static final int NO_OF_CHARS = 256;
static char getSecondMostFreq(String str) {
int[] count = new int[NO_OF_CHARS];
int i;
for (i = 0; i < str.length(); i++)
(count[str.charAt(i)])++;
int first = 0, second = 0;
for (i = 0; i < NO_OF_CHARS; i++) {
if (count[i] > count[first]) {
second = first;
first = i;
} else if (count[i] > count[second] && count[i] != count[first]) {
second = i;
}
}
if (count[second] == 0) {
return '\0'; // No second most frequent character
}
return (char) second;
}
public static void main(String args[]) {
System.out.println("Enter a String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char res = getSecondMostFreq(str);

3
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

if (res != '\0') {
System.out.println("\nSecond Most Frequent Char" + " is: " + res);
} else {
System.out.println("No Second Most Frequent" + " character");
}
}
}
OUTPUT:

4
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 03: WAP to check longest sub sequence of a same character in an initialized string?
[aaaabppppp, p=5] [aabbcc, a=2].
CODE:
public class Q3 {
public static void main(String[] args) {
String str = "aaaabppppp";
char longestChar = '\0';
int longestCount = 0;
int currentCount = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1))
{
currentCount++;
} else
{
if (currentCount > longestCount)
{
longestCount = currentCount;
longestChar = str.charAt(i - 1);
}
currentCount = 1;
}
}
if (currentCount > longestCount) {
longestCount = currentCount;
longestChar = str.charAt(str.length() - 1);
}
System.out.println("Longest subsequence of the same character:");
System.out.println(longestChar + "=" + longestCount);
}
}

5
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

OUTPUT:

6
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 04: WAP to generate wifi key as user will enter form value Name,City,Age and Gender?
CODE:
import java.util.*;
class q4
{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Criteria :Length of Name and City greater than 3 and age!=18\n");
System.out.println("Enter your Name= ");
String Name=sc.nextLine();
System.out.println("Enter your City= ");
String City=sc.nextLine();
System.out.println("Enter your Gender (M or F) ");
char gender=sc.next().charAt(0);
System.out.println("Enter your age= ");
int age=sc.nextInt();
if(Name.length()<3 || City.length()<3 || age<10)
{
System.out.println("You are not matching the Criteria");
return ;
}
if((gender =='m' || gender =='M') ){
int pwd2=0;
String pwd1= Name.substring(0,3);
String pwd3= City.substring(City.length()-3,City.length());
while(age!=0){
pwd2-= age%10;
if(pwd2<0)
pwd2=-pwd2;
age=age/10;

7
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

}
System.out.println("WifiPwd is ="+ pwd1 + pwd2 + pwd3);
}
else if((gender =='f' || gender =='F') ){
int pwd2=0;
String pwd1= Name.substring(Name.length()-3,Name.length());
String pwd3= City.substring(0,3);
while(age!=0){
pwd2+= age%10;
age=age/10;
}
System.out.println("WiFipwd is ="+ pwd1 + pwd2 + pwd3);
}
}
}
OUTPUT:

8
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 05: WAP to delete only those text file which are non-empty in these folders.
[E://MCA/BCA/DCA].
CODE:
import java.io.File;
public class q5 {
public static void search_f(File r) {
String a = r.getPath().toString();
System.out.println(a + " " + r.getName());
if (r.length() > 0)
{
if (r.delete())
{
System.out.println(a + " file deleted");
}
}
}
public static void search_type(File f) {
File[] m = f.listFiles();
if (m != null) {
for (File r : m)
{
if (r.isFile())
{
search_f(r);
}
if (r.isDirectory())
{
search_d(r);
}
}
}

9
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

}
public static void search_d(File r) {
String s = r.getName().toLowerCase();
if (s.matches(".*bca.*") || s.matches(".*dca.*") || s.matches(".*mca.*"))
{
search_type(r);
}
}
public static void main(String[] args) {
File f = new File("D:/College-GEU/2nd Sem/JAVA/mca/bca");
search_type(f);
}
}
OUTPUT:

D:\College-GEU\2nd Sem\JAVA\Term Work>javac q5.java

D:\College-GEU\2nd Sem\JAVA\Term Work>java q5


D:\College-GEU\2nd Sem\JAVA\mca\bca\a.txt a.txt
D:\College-GEU\2nd Sem\JAVA\mca\bca\a.txt File Deleted

10
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 06: WAP to create a method check which returns two values. If first string having a
character twice as well second string also then return both the string by removing that character?
CODE:
import java.util.*;
public class q6 {
static final int NO_OF_CHARS = 256;
public static Map<Character, Integer> count_frequency(String s)
{
Map<Character, Integer> d = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++)
{
if(d.containsKey(s.charAt(i)))
{
d.put(s.charAt(i), d.get(s.charAt(i)) + 1);
}
else
{
d.put(s.charAt(i), 1);
}
}
return d;
}
public static String[] check(String s1,String s2)
{
String arr[]=new String[2];
String ans1=s1,ans2=s2;
Map<Character, Integer> d = new HashMap<Character, Integer>();
Map<Character, Integer> d1 = new HashMap<Character, Integer>();
d.putAll(count_frequency(s1));
d1.putAll(count_frequency(s2));
for(int i = 0; i < s1.length(); i++)

11
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

{
String c=""+s1.charAt(i);
if((d.get(s1.charAt(i))==2)&&(s2.contains(c)))
{ans1=ans1.replace(c, "");
ans2=ans2.replace(c, "");
}
}
arr[0] = ans1;
arr[1] = ans2;
return arr;
}
public static void main(String str[])
{Scanner sc=new Scanner(System.in);
System.out.print("Enter first string : ");
String s1=sc.nextLine();
System.out.print("Enter second string : ");
String s2=sc.nextLine();
String res[]=check(s1, s2);
System.out.println("\nfirst: "+res[0]+" second: "+res[1]);
}
}
OUTPUT:

12
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 07: WAP to print number of days gape in your age as enter DD-MM-YYYY with current
system date?
CODE:
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
class q7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
Date currentDate = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String s2 = dateFormat.format(currentDate);
String[] a = s1.split("-");
String[] b = s2.split("-");
int c = 0;
for (int i = 0; i < a.length; i++) {
int d = Integer.parseInt(a[i]);
int e = Integer.parseInt(b[i]);
if (d > e)
c = d - e;
else
c = e - d;

if (i == a.length - 1)
System.out.print(c);
else
System.out.print(c + "-");
}

13
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

}
}
OUTPUT:

14
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 08: WAP to print number of days gape in your age as enter DD-MM-YYYY with current
system date?
CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class q8 extends Applet implements ActionListener
{
String name=" ", address=" ";
String exam=" ";
TextField n=new TextField(10);
TextField m1=new TextField(10);
CheckboxGroup g=new CheckboxGroup();

Checkbox m2=new Checkbox("java",g,true);


Checkbox m=new Checkbox("c#",g,true);
Checkbox f=new Checkbox("c",g,false);
Choice c=new Choice();
Label l1=new Label("Enter name:");
Label l=new Label("Enter Address:");
Label l2=new Label("Selec Subject:");
Label l3=new Label("Exam Center:");
Button b=new Button("Button");
public void init()
{
b.setBackground(Color.red);
c.setBackground(Color.red);
setBackground(Color.black);
setForeground(Color.white);
add(l1);
add(n);

15
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

add(l);
add(m1);
add(l2);
add(m);
add(f);
add(m2);
add(l3);
c.add("Kotdwara");
c.add("Haridwar");
c.add("SRE");
c.add("DElhi");
add(c);
add(b);
b.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString("name: "+name,20,100);
g.drawString("Gender: "+address,20,120);
g.drawString("Exam Center: "+exam,20,140);
}
public void actionPerformed(ActionEvent e)
{
name=n.getText();
address=g.getSelectedCheckbox().getLabel();
exam=c.getSelectedItem();
repaint();
}
} /* <applet code="q8.class" height=1000 width=1000></applet>*/

16
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

OUTPUT:

17
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 09: WAP in an Applet Make two Button one is Circle within Square and second is Square
within Circle. When user click on Circle within Square then draw Circle within Square. And when
user click on Square within Circle then draw Square within Circle on the panel window?
CODE:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class q9 extends Applet implements ActionListener
{
Button circleButton, squareButton;
int radius = 20;
int x, y;
int size = 50;
int red, green, blue;
boolean SQUARE = true;
public void init() {
x = 200;
y = 200;
red = green = blue = 0;
circleButton = new Button("Draw Circle");
squareButton = new Button("Draw Square");
add(circleButton);
add(squareButton);
circleButton.addActionListener(this);
squareButton.addActionListener(this);
}
public void paint(Graphics g) {
g.setColor(new Color(red, green, blue));
if (SQUARE == false) {

drawCircle(g, x, y, radius);

18
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

} else {
drawSquare(g, x, y, size);
drawCircle(g, x, y, radius);
}
/*
* print out the values of x, y, and r
* g.drawString("x="+x+", y="+y+", radius="+radius, 10, 390);
*/
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == circleButton) {
SQUARE = false;
} else {
SQUARE = true;
}
red = (int) (Math.random() * 256);
green = (int) (Math.random() * 256);
blue = (int) (Math.random() * 256);
x = (int) (Math.random() * 400);
y = (int) (Math.random() * 400);
radius = (int) (Math.random() * 100);
size = (int) (Math.random() * 200);
repaint();
private void drawSquare(Graphics g, int x, int y, int w) {
g.fillRect(x, y, w, w);
} // drawSquare
private void drawCircle(Graphics g, int x, int y, int r) {
g.fillOval(x - r, y - r, 2 * r, 2 * r);
}
}

19
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

//<applet code = q9.class width=400 height=400></applet>

OUTPUT:

20
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 10: WAP to put one Exception class in a package and to use this Exception class object in
another package class method anyhow?
Code For A.java:
package p;
public class A {
public void show() {
try {
int a = 1 / 0;
} catch (Exception e) {
System.out.println("Exception occurred: " + e.getMessage());
}
System.out.println("Hello, I'm A");
}
}
Code For D.java:
import p.A;
public class D {
public static void main(String[] args) {
A m = new A();
m.show();
}
}
OUTPUT:

21
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 11: WAP to initialize 2D string array at runtime and to print reverse value of diagonal
position only?
CODE:
import java.util.Scanner;
class q11 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows:");
int row = sc.nextInt();
System.out.println("Enter number of columns:");
int column = sc.nextInt();
String[][] arr = new String[row][column];
sc.nextLine(); // Consume the newline character after reading the integer

System.out.println("Enter elements for the array:");


for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
arr[i][j] = sc.nextLine();
}
}
System.out.println("The 2D array is:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println("Reverse Diagonal elements are:");
for (int i = row - 1; i >= 0; i--) {
for (int j = column - 1; j >= 0; j--) {
if (i + j == row - 1) {

22
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

System.out.print(arr[i][j] + " ");


}
}
}
}
}
OUTPUT:

23
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 12: WAP to show the Working of multithreading. Make separate program by using
Runnable interface and by using Thread Class. Also use their methods.
CODE:
File: Q12.JAVA
class q12 {
public static void main(String args[]) {
p1 x = new p1();
x.start();
}
}

class p1 extends Thread {


public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("p1" + i + " ");
}
}
}
File: ab.java
class ab implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("B1" + i + " ");
}
}
}
File: t12i.java
class t12i {
public static void main(String args[]) {
ab x = new ab();
Thread t = new Thread(x);

24
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

t.start();
}
}
OUTPUT:

25
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 13: WAP using Applet to draw circle, line, rectangle and fill them with a colour given by
the user.
CODE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Q13 extends Applet implements ItemListener
{
String s="white";
Choice c=new Choice();
public void init()
{
c.add("red");
c.add("green");
c.add("blue");
c.addItemListener(this);
add(c);
c.setVisible(true);
}
public void paint(Graphics g)
{
if(s.equals("red"))
g.setColor(Color.red);
else if(s.equals("blue"))
g.setColor(Color.blue);
else if(s.equals("green"))
g.setColor(Color.green);
g.fillRect(20,200,150,100);
g.fillOval(300,200,100,100);
g.drawLine(500,200,600,300);
}

26
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

public void itemStateChanged(ItemEvent e)


{
s=c.getSelectedItem();
repaint();
}
}
//<applet code=Q13 width=1000 height=500></applet>
OUTPUT:

27
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 14. WAP to implement a color menu which have four options red, Green, Blue and Exit.
When we’ll Press red, green, blue color it will set that color as background color and on exit we
need to exit from the window.
CODE:
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
import javax.swing.*;
class Q14 implements ActionListener
{
JFrame f=new JFrame("Color");
JMenuBar mb=new JMenuBar();
JMenu color=new JMenu("Color");
JMenuItem red=new JMenuItem("Red");
JMenuItem green=new JMenuItem("Green");
JMenuItem blue=new JMenuItem("Blue");
class B extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
}
Q14()
{
color.add(red);
color.add(blue);
color.add(green);
mb.add(color);
color.addSeparator();
f.add(mb,BorderLayout.NORTH);

28
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

f.setSize(400,400);
f.setVisible(true);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
f.addWindowListener(new B());
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==red)
f.getContentPane().setBackground(Color.RED);
else if(e.getSource()==blue)
f.getContentPane().setBackground(Color.BLUE);
else if(e.getSource()==green)
f.getContentPane().setBackground(Color.GREEN);
}
public static void main(String ss[])
{
new Q14();
}
}
OUTPUT:

29
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 15. WAP to show the use of Key Listener/Mouse Listener interface in order to generate
and process those events.
CODE:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Q15 extends Applet implements KeyListener, MouseListener
{
public void init()
{
addKeyListener(this);
addMouseListener(this);
}
String s;
public void paint(Graphics g)
{
showStatus(s);
}
public void keyPressed(KeyEvent e)
{
s="Key "+e.getKeyChar()+" pressed";
repaint();
}
public void keyReleased(KeyEvent e)
{
s="Key "+e.getKeyChar()+" released";
repaint();
}
public void keyTyped(KeyEvent e)
{
s="Key "+e.getKeyChar()+" typed";

30
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

repaint();
}
public void mouseClicked(MouseEvent e)
{
s="Mouse clicked at: ("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseEntered(MouseEvent e)
{
s="Mouse entered the applet";
repaint();
}
public void mouseExited(MouseEvent e)
{
s="Mouse exitted the applet";
repaint();
}
public void mousePressed(MouseEvent e)
{
s="Mouse pressed at("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseReleased(MouseEvent e)
{
s="Mouse released at("+e.getX()+","+e.getY()+")";
repaint();
}
public void mouseDragged(MouseEvent e)
{
s="Mouse is being dragged ("+e.getX()+","+e.getY()+")";

31
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

repaint();
}
public void mouseMoved(MouseEvent e)
{
s="Mouse is being moved ("+e.getX()+","+e.getY()+")";
repaint();
}
}
//<applet code= Q15 width="600" height="100"></applet>
OUTPUT:

32
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 16. WAP to create TCP/IP Socket on both client and server side. and after socket creation
perform the operation as done in chat server.
CODE:
//SERVER FILE
import java.io.*;
import java.net.*;
public class Q16 {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
System.out.println("Server started. Waiting for client connection...");
Socket s = ss.accept(); // establishes connection
System.out.println("Client connected.");
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
System.out.println("Received message: " + str);
ss.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
//CLIENT FILE
import java.io.*;
import java.net.*;
public class Q161 {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666);
System.out.println("Connected to server.");

33
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

DataOutputStream dout = new DataOutputStream(s.getOutputStream());


dout.writeUTF("Hello Server");
dout.flush();
dout.close();

s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
OUTPUT:

34
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 17. WAP to print all numeric digits sum of all database column values.
CODE:
import java.sql.*;
public class q17
{
public static void main(String args[])throws Exception
{
int sum=0;
Class.forName("com.mysql.cj.jdbc.Driver"); //1- load Driver
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/new","root","291429@k");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from st");
ResultSetMetaData rsmd=rs.getMetaData();
int k=rsmd.getColumnCount();
while(rs.next())
{
for(int i=1;i<=k;i++)
{
String str=rs.getString(i);
for(int j=0;j<str.length();j++)
{
char c=str.charAt(j);
if(Character.isDigit(c))
{
sum+=Character.getNumericValue(c);
}
}
}
}
System.out.println("Sum is - " +sum);

35
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

}
}
OUTPUT:

TABLE IN DATABASE:

36
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 18. WAP to update a table column value using stored procedures.
CODE:
import java.sql.*;
public class q18 {
public static void main(String[] args) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/student","root","root");
CallableStatement stmt=con.prepareCall("{call insertR(?,?,?)}");
stmt.setString(1,"Amit");
stmt.setString(2,"Surat");
stmt.setInt(3,33);
stmt.execute();
System.out.println("success");
}
}
/*create or replace procedure "UPDATE"(name IN VARCHAR2,
cit IN VARCHAR2,id IN int)
is
BEGIN
UPDATE employee
SET first_name = name,
city = cit
WHERE id = idd
END; / */
OUTPUT:

37
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 19. WAP to show the use of transient keyword.


CODE:
import java.io.*;
class A implements Serializable
{
int i;
transient int j;
A(int x,int y)
{
i=x;j=y;
}}
class q19
{public static void main(String ss[])throws Exception
{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("b.txt"));
A ob=new A(2,4);
oos.writeObject(ob);
oos.close();
A ob2;
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("b.txt"));
ob2=(A)ois.readObject();
System.out.println("i: "+ob2.i+"\nj: "+ob2.j);
}
}
OUTPUT:

38
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 20. WAP to insert/retrieve an image into database table.


CODE:
import java.sql.*;
import java.io.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class t20{
public static void main(String args[]) throws Exception{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost/Student";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)");
pstmt.setString(1, "sample image");
InputStream in = new FileInputStream("E:\\images\\image.jpg");
pstmt.setBlob(2, in);
pstmt.execute();
System.out.println("Record inserted..... ");
PreparedStatement ps=con.prepareStatement("select * from imgtable");
ResultSet rs=ps.executeQuery();
if(rs.next()){
Blob b=rs.getBlob(2);
byte barr[]=b.getBytes(1,(int)b.length());
FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
fout.write(barr);
fout.close(); }
System.out.println("INPUT SUCCESSFULLY");
con.close();
}} OUTPUT:

39
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 21. WAP to show the use of synchronized keyword in producer consumer problem.
CODE:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

40
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

class Producer implements Runnable {


Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class Main {
public static void main(String args[])
{
Q q = new Q();
new Producer(q);

41
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
OUTPUT:

42
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 22. WAP for following OUTPUT


String s="san12may4tya7yyy678rtb62tp"
Output 2 will 4*7=28
Output 1 will sanmytrbp
Output 3 will 12+678+62=690+62 =....
CODE:
import java.util.*;
class Q22
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string - ");
String s =sc.nextLine();
char a[] = s.toCharArray();
String s1="";
for(int i =0; i < a.length; i++)
{
int count=0;
char c =a[i];
if(Character.isLetter(c)) {
if(s1.length()==0)
s1 += c;
else
{
for(int j = 0; j <s1.length();j++)
{
if(s1.charAt(j)==c){
count++;
break;}

43
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

}
if(count==0)
s1+=c;
}
}
}
int mul = 1, sum = 0;
int check = 0;
for(int i =0; i < a.length; i++)
{
int count=0;
char c =a[i];
int temp = 0;
while(Character.isDigit(a[i])) {
temp = (temp*10) + Character.getNumericValue(a[i]);
count++;
i++;
if(i>=a.length)
break; }
if(count ==1) {
mul *= Character.getNumericValue(c);
check++;
}
if(count>1)
sum += temp;
}
if(check == 0)
mul = 0;
System.out.println("Output 1 - "+ s1);
System.out.println("Output 2 - "+ mul);

44
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

System.out.println("Output 3 - "+sum);
}
}
OUTPUT:

45
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 23. Enter a no and then create array of its digits.


CODE:
public class q23
{
public static void main(String[] args) {
int a=123456;
String s=Integer.toString(a);
int ar[]=new int[s.length()];
for(int i=0;i<s.length();i++)
ar[i]=Character.getNumericValue(s.charAt(i));
for(int i=0;i<s.length()/2;i++)
{
int temp=ar[i];
ar[i]=ar[s.length()-1-i];
ar[s.length()-1-i]=temp;
}
for(int i=0;i<s.length();i++)
{
System.out.println("a["+i+"]"+":"+ar[i]);
}
}
}
OUTPUT:

46
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 24. WAP to initialize two integer array of user entered size. Then perform following
operations
add elements in that array which is longest.
I.e., if first array is of 3 size having elements 1,2,3
Second array is of size five and elements are 4,5,6,7,8
Then result array will second and now it's elements will 5,7,9,7,8
CODE:
import java.util.*;
class Q24
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of first array - ");
int n1 = sc.nextInt();
System.out.println("Enter the size of second array - ");
int n2 = sc.nextInt();
int a[] = new int[n1];
int b[] = new int[n2];
System.out.println("Enter the element in first array - ");
for(int i=0; i<n1; i++)
{
a[i] = sc.nextInt();
}
System.out.println("Enter the element in second array - ");
for(int i=0; i<n2; i++)
{
b[i] = sc.nextInt();
}
System.out.print("Result - ");
if(n1>n2) {

47
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

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


a[i] = b[i]+a[i];
for(int i=0; i<n1; i++)
System.out.println(a[i]+" ");
}
else {
for(int i=0; i<n1; i++)
{
b[i] = a[i]+b[i];
}
for(int i=0; i<n2; i++)
{
System.out.print(b[i]+" ");
}
}
}
}
OUTPUT:

48
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

Question 25. Initialize integer array of any size contain values 0 and 1 only.
Now check which is longest series of either 0 or 1, which is existing.
CODE:
import java.util.*;
public class q25
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int vn = 0, zero = 0, onemax = 0, zeromax = 0;
for(int i=0;i<n;i++)
arr[i]= sc.nextInt();
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
onemax = Math.max(onemax, vn);
vn = 0;
zero++;
} else {
zeromax = Math.max(zeromax, zero);
zero = 0;
vn++;
}
}
if (onemax > zeromax) {
System.out.println("1 -> " + onemax);
} else if(zeromax>onemax){
System.out.println("0 -> " + zeromax);
}else{
int tempzero=0,tempone=0;

49
ADITI NEGI MCA C ROLL NO-07 STUDENT ID-22392177

for(int i=0;i<n;i++)
{
if(arr[i]==0)
{
tempone=0;
tempzero++;
if(tempzero==zeromax)
{
System.out.println("0 -> " + zeromax);
break;
}
}else{
tempzero=0;
tempone++;
if(tempone==onemax) {
System.out.println("1 -> " + onemax);
break; }
}}
}}
}
OUTPUT:

50

You might also like