0% found this document useful (0 votes)
37 views33 pages

Java 10

JAVA PROGRAM
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)
37 views33 pages

Java 10

JAVA PROGRAM
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/ 33

Q44.

) Write a program which constructs a student class with data members –


id, name, age and override the toString() and equals() methods in the class.
Add three student objects to hashSet class and print each student information.
Try to overwrite the hashcode method in student class so that it overwrites the
hashCode() method of object class. Your method may append a particular
number to the value which is returned by the hashCode() method. Now
perform a search operation on your HashSet to find out whether your
HashSet contains a particular student with a given id or not. You have to
perform this program in two ways. Try to remove either the equals() or
hashCode() from student class and see the results.

package javaprograms;

import java.util.*;

public class Student


{
int id;
int age;
String name;

Student(int sid, int a, String n)


{
id=sid;
age=a;
name=n;
}

public String toString()


{
return "The name of Student is " +name;
}

boolean equals(Student s1)


{
System.out.println("In equals()");
if((this.name.equals(s1.name)) && this.id==s1.id &&
this.age==s1.age)
return true;
else
return false;
}

public int hashCode()


{
int hashcode=0;
hashcode+=name.hashCode();
return hashcode;
}

void print()
{
System.out.println("Student ID= "+id+", Student age= "+age+",
Student name= "+name);
}

public static void main(String args[])


{
Set<Student> Students = new HashSet<Student>();
Student s1 = new Student(12,22,"John");
Student s2 = new Student(13,21,"Steve");
Student s3 = new Student(14,25,"Mark");
Students.add(s1);
Students.add(s2);
Students.add(s3);
s1.print();
s2.print();
s3.print();
Students.forEach(System.out::println);
boolean found=Students.contains(s3);
System.out.println("Found= "+found);
}
}
Output:

Student ID= 12, Student age= 22, Student name= John


Student ID= 13, Student age= 21, Student name= Steve
Student ID= 14, Student age= 25, Student name= Mark
The name of Student is Steve
The name of Student is John
The name of Student is Mark
Found= true

After removing hashCode() –

package javaprograms;

import java.util.*;

public class Student


{
int id;
int age;
String name;

Student(int sid, int a, String n)


{
id=sid;
age=a;
name=n;
}

public String toString()


{
return "The name of Student is " +name;
}

boolean equals(Student s1)


{
System.out.println("In equals()");
if((this.name.equals(s1.name)) && this.id==s1.id &&
this.age==s1.age)
return true;
else
return false;
}

/* public int hashCode()


{
int hashcode=0;
hashcode+=name.hashCode();
return hashcode;
}
*/
void print()
{
System.out.println("Student ID= "+id+", Student age= "+age+",
Student name= "+name);
}

public static void main(String args[])


{
Set<Student> Students = new HashSet<Student>();
Student s1 = new Student(12,22,"John");
Student s2 = new Student(13,21,"Steve");
Student s3 = new Student(14,25,"Mark");
Students.add(s1);
Students.add(s2);
Students.add(s3);
s1.print();
s2.print();
s3.print();
Students.forEach(System.out::println);
boolean found=Students.contains(s3);
System.out.println("Found= "+found);
}
}
Ouput:

Student ID= 12, Student age= 22, Student name= John


Student ID= 13, Student age= 21, Student name= Steve
Student ID= 14, Student age= 25, Student name= Mark
The name of Student is John
The name of Student is Mark
The name of Student is Steve
Found= true
Q45.) Write a program which reads from a file which is located in a directory
of your choice. The file contains English alphabets. You can use the absolute
path or relative path. Find out how many bytes are available in the file. Divide
the size of the file by 10 and read those many bytes, one byte at a time. Again
find out the remaining content of the file. Declare an array of your choice and
try to read those many bytes at one go. Again find out the remaining file
content. Try to skip half of the file for reading and then try to read the
remaining file content into another array using third form of read.

package javaprograms;

import java.io.*;

public class Demo1 {

public static void main(String[] args) throws IOException


{
FileInputStream f= new
FileInputStream("C:\\Users\\DELL\\Downloads\\test.txt");
int size=f.available();
int n=size/10;
for(int i=0;i<n;i++)
{
System.out.println((char)f.read());
}
n=f.available();
byte b[]=new byte[5];
int x=f.read(b);

for(int i=0;i<x;i++)
{
System.out.println(b[i]);
}

x=f.available();
f.skip(2);
x=f.available();
byte b1[]=new byte[x];
f.read(b1,0,x);
}

Output:

H
101
108
108
111
32
Q46.) Write a function which write “ABCD” to file alphabet.txt which resides
in temp directory under c:\\ . After writing, it attempts to read the contents.
After reading, the program converts it to lowercase and prints the string on
screen.

import java.io.*;

public class alphabet {

public static void main(String[] args) throws IOException {


String s="ABCD";
byte b1[]=s.getBytes();
FileOutputStream f1=new
FileOutputStream("C:\\TEMP\\alphabet.txt");
f1.write(b1);

FileInputStream f2=new FileInputStream("C:\\TEMP\\alphabet.txt");


byte b2[]=new byte[b1.length];
f2.read(b2);
String s2=new String(b2);
System.out.println(s2.toLowerCase());
}

Output:

abcd
Q47.)Write a program which attempts to read using ByteArrayInputStream
the contents of byte array twice. Let the contents be “ABC”.

import java.io.ByteArrayInputStream;

public class BAIStwice {

public static void main(String[] args) {


String s="ABC";
byte b1[]=s.getBytes();
ByteArrayInputStream bais=new ByteArrayInputStream(b1);

for(int i=0;i<b1.length;i++)
{
System.out.println((char)bais.read());
}
bais.reset();

Output:

A
B
C
Q48.) Write a program which uses a BufferedInputStream by wrapping a
ByteArrayInputStream. The ByteArrayInputStream stores an input which is
thereafter used for marking, skipping and resetting.

package javaprograms;
import java.io.*;
public class buffered
{

public static void main(String[] args) throws IOException


{
String s="This is a &copy; copywright symbol"+" but this is &copy
not \n";
byte b[]=s.getBytes();
ByteArrayInputStream in=new ByteArrayInputStream(b);
BufferedInputStream bis=new BufferedInputStream(in);
int c;
boolean marked=false;
while((c=bis.read())!=-1)
{
switch(c)
{
case '&' : if(!marked)
{
bis.mark(32);
marked=true;
}
else
{
marked=false;
}
break;

case ';' : if(marked)


{
marked=false;
System.out.println("c");
}
else
System.out.println((char)c);
break;

case ':' : if(marked)


{
marked=false;
bis.reset();
System.out.println("&");
}
else
System.out.println((char)c);
break;
}

int x=b.length-3;
for(int i=0;i<b.length;i++)
{
System.out.println((char)bis.read());
if(i==x) {bis.mark(3);}
}
bis.reset();
for(x=0;x<b.length;x++)
{
System.out.println((char)x);
}
}
}
}

Output:

h
i
s

i
s

a
&
c
o
p
y
;

c
o
p
y
w
r
i
g
h
t

s
y
m
b
o
l

b
u
t

t
h
i
s

i
s

&
c
o
p
y

n
o
t

?
!
"
#
$
%
&
'
(
)
*
+
,
-
.
/
0
1
2
3
4
5
6
7
8
9
Q49.) Write a program to show the concept of object serialization

package javaprograms;
import java.io.*;
class Point implements Serializable
{
int x,y;
Point(int a,int b)
{
x=a;
y=b;
}

public String toString()


{
return x+","+y ;
}
}
public class Demo2
{
public static void main(String args[]) throws IOException,
ClassNotFoundException
{
try (ObjectOutputStream os=new ObjectOutputStream(new
FileOutputStream("c.txt")))
{
Point p1=new Point(1,2);
os.writeObject(p1);
}catch(Exception e) {}
try(FileInputStream f1=new FileInputStream("c.txt"))
{
ObjectInputStream is=new ObjectInputStream(f1);
Point p2=(Point) is.readObject();
System.out.println(p2);
}catch(Exception e) {}
} }

Output: 1,2
Q50.) Write a program which has a try resource statement which attempts to
write double, int and Boolean values to file called test.txt. After writing, the
data is read back and attempted to be printed on the screen.

package javaprograms;
import java.io.*;
public class Demo3 {

public static void main(String[] args) throws FileNotFoundException,


IOException
{
try(DataOutputStream dos=new DataOutputStream(new
FileOutputStream("C:\\Users\\DELL\\Downloads\\test1.txt")))
{
dos.writeDouble(89.975);
dos.writeInt(123);
dos.writeBoolean(true);
}catch(Exception e) {}
try(DataInputStream dis=new DataInputStream(new
FileInputStream("C:\\Users\\DELL\\Downloads\\test1.txt")))
{
System.out.println(dis.readDouble()+" "+dis.readInt()+"
"+dis.readBoolean());
}catch(Exception e) {}

Output:

89.975 123 true


Q51.) Write a program which prints floating point numbers with two formats

 Two places after decimal


 Six places after decimal

package javaprograms;

public class printstream {

public static void main(String[] args)


{
Double val=89.975;
System.out.printf("%.2f", val);
System.out.printf("\n%.6f", val);
}

Output:

89.98
89.975000
Q52.) Write a program which tries to obtain the Ip Address of the machine
you are working on and also tries to get the Ip address of domain name
“starworld.com” and get all the Ip addresses which are trying to access that
domain name.

package javaprograms;

import java.net.*;

public class X1 {

public static void main(String[] args) throws UnknownHostException


{
InetAddress add=InetAddress.getLocalHost();
System.out.println(add);
InetAddress add1=InetAddress.getByName("startworld.com");
InetAddress add2[]=InetAddress.getAllByName("startworld.com");
}
}

Output:

DELL-PC/192.168.1.37
Q53.) Write a program to show Client and Server Communication

client.java

package javaprograms;
import java.net.*;
import java.io.*;
public class client {

public static void main(String[] args)


{
Socket s;
PrintStream ps=null;
BufferedReader br=null;
try {
s=new Socket("127.0.0.1",7268);
ps=new PrintStream(s.getOutputStream());
br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
String s1=br.readLine();
System.out.println(s1);
ps.println("Joyesh Malik");

}catch(Exception e) {}

server.java

package javaprograms;
import java.io.*;
import java.net.*;
public class server implements Runnable
{
Socket s;
public static void main(String[] args)
{
try {
ServerSocket ss=new ServerSocket(7268);
System.out.println("Server Started");

while(true)
{
Socket s1=ss.accept();
server s2=new server(s1);
Thread t1=new Thread(s2);
t1.start();
}
}catch(Exception e) {}

}
public server(Socket s)
{
this.s=s;
}
public void run()
{
try
{
InputStream in=s.getInputStream();
InputStreamReader inr=new InputStreamReader(in);
BufferedReader br=new BufferedReader(inr);
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println("Joyesh Malik");
String logname=br.readLine();
System.out.println("Logname is= "+logname);
}catch(Exception e) {}

Output:

Server Started
Logname is= Joyesh Malik
Q54.) Write a program using UDP protocol wherein the server constructs a
datagram packet which contains ‘Hello World’ and sends it to a datagram
client. The client receives the packet and prints it on the screen.

UDPClient.java

package javaprograms;

import java.io.IOException;
import java.net.*;

public class UDPClient {

public static void main(String[] args) throws IOException


{
DatagramSocket ds = new DatagramSocket(7268);
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, 100);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}

UDPServer.java

package javaprograms;

import java.io.IOException;
import java.net.*;

public class UDPServer


{
public static void main(String args[]) throws IOException
{
DatagramSocket ds = new DatagramSocket();
String str = "Hello World";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(),


str.length(), ip, 7268);
ds.send(dp);
ds.close();
}
}

Output:

Hello World
Q55.) Write a program which adds a frame titled by ‘MyfirstAwtPrograms’.
The frame window is set to a dimension size of your choice. Later on we create
three buttons(yes, no, maybe) then the components are added to the container
window and window is made visible.

package javaprograms;

import java.awt.*;

public class frames {

public static void main(String[] args)


{
Frame f=new Frame("My First AWT Program");
f.setSize(400,100);
Button y=new Button("Yes");
Button y1=new Button("No");
Button y2=new Button("Maybe");
f.setLayout(new FlowLayout(FlowLayout.CENTER));
f.add(y);
f.add(y1);
f.add(y2);
f.setVisible(true);
}

Output:
Q56.) Write a program which adds three buttons ‘yes’, ‘no’ and ‘maybe’ to
the frame window. The same class can also register for the action events
which are associated by pressing the buttons. Write a suitable event handling
mechanism which displays which button was pressed for generating the event.

package javaprograms;
import java.awt.*;
import java.awt.event.*;
public class action implements ActionListener{

action()
{
Frame f=new Frame("My First AWT Program");
f.setSize(400,100);
Button y=new Button("Yes");
y.addActionListener(this);
Button y1=new Button("No");
y1.addActionListener(this);
Button y2=new Button("Maybe");
y2.addActionListener(this);
f.setLayout(new FlowLayout(FlowLayout.CENTER));
f.add(y);
f.add(y1);
f.add(y2);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
System.out.println(str);
}
public static void main(String args[])
{
new action();
}

}
Output:

Console:

Maybe
Q57.) Write a program which creates four checkboxes based on four
operating systems. The initial state of first box is checked. You can change the
state of your checkbox and the message is displayed on the window whether
you selected or deselected the option.

package javaprograms;

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

public class X4 implements ItemListener {


Checkbox a,w,s,l;
X4()
{
Frame f=new Frame("My AWT Program");
f.setSize(400,100);
// CheckboxGroup g=new CheckboxGroup();
a=new Checkbox("Android",true);
w=new Checkbox("Window");
s=new Checkbox("Solaris");
l=new Checkbox("Linux");
f.add(a);
a.addItemListener(this);
f.setVisible(true);
f.add(w);
w.addItemListener(this);
f.setVisible(true);
f.add(s);
s.addItemListener(this);
f.setVisible(true);
f.add(l);
l.addItemListener(this);
f.setVisible(true);
}

public void itemStateChanged(ItemEvent e)


{
System.out.println("The state is= "+e.getStateChange());

}
public static void main(String[] args)
{
new X4();
}
}

Output:

Console:

The state is= 1


The state is= 2
Q58.) Write a program which associates two textfields with label name and
roll no. And they respond to the events whenever a text is entered into the text
field.

package javaprograms;
import java.awt.*;
import java.awt.event.*;
public class TF extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TF(){
tf1=new TextField();
tf1.setBounds(70,50,150,20);
tf2=new TextField();
tf2.setBounds(70,100,150,20);
b1=new Button("Click Here");
b1.setBounds(100,200,70,40);
b1.addActionListener(this);
add(tf1);add(tf2);add(b1);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int b=Integer.parseInt(s2);
if(e.getSource()==b1){
System.out.println("Your Name is =" +s1+" and Roll no.= "+b);
}

}
public static void main(String[] args) {
new TF();
}
}
Output:

Console:

Your Name is =Joyesh and Roll no.= 21


Q59.) Write a simple Applet that sets the background color to cyan and sets
the foreground color to red and displays appropriate messages. For example –
when it is inside init() method, it says “inside init()”, “inside start()” and so on.

package javaprograms;
import java.awt.*;
import java.applet.*;
/*<applet code="myApplet" width=300 height=500>*/
public class myApplet extends Applet
{ String msg;
public void init()
{
setBackground(Color.CYAN);
setForeground(Color.red);
msg="Inside init()";
}

public void start()


{
msg+="Inside start()";
}

public void paint(Graphics g)


{
msg+="Inside paint()";
g.drawString(msg, 10, 30);
}

}
Output:
Q60.) Write an applet program which adds a label on the north portion of the
border layout, a button called ‘write’ on the last and a text area in the center
part.

package javaprograms;

import java.awt.*;
import java.applet.*;
/*<applet code="myApplet" width=300 height=500>*/
public class myApplet1 extends Applet {
String msg;
Button b1;
public void init()
{
setLayout(new BorderLayout());
Label l=new Label("BorderLayout()");
add(l,BorderLayout.NORTH);
b1=new Button("Write");
add(b1,BorderLayout.AFTER_LAST_LINE);
TextField tf1=new TextField();
add(tf1,BorderLayout.CENTER);
msg="Inside init()";
}
}

Output:
Q61.) Write an applet program which sets the layout manager to flow layout.
Add three buttons ‘yes’, ‘no’ and ‘maybe’. Then all these three buttons are
event handled by the applet class with the appropriate messages.

package javaprograms;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*<applet code="myApplet2" width=300 height=500>*/


public class myApplet2 extends Applet implements ActionListener
{
String msg;
Button yes,no,maybe;

public void init()


{
setLayout(new FlowLayout());
yes=new Button("Yes");
add(yes);
yes.addActionListener(this);
no=new Button("No");
add(no);
no.addActionListener(this);
maybe=new Button("Maybe");
add(maybe);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str= ae.getActionCommand();
if(str.equals("Yes"))
msg="Press Yes!";
else if(str.equals("No"))
msg="Press No!";
else
msg="Press Maybe!";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,70,80);
}

Output:

You might also like