Final JAVA PR Ans
Final JAVA PR Ans
Write a java program to demonstrate the use of exception handling. Handled divide
by zero error.
ANS-
try {
result = divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
try {
// Accessing index 5 which is out of bounds
int value = numbers[5];
System.out.println("Value: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Write a java program to implement the concept of file handling, copy the content
from one file to another file.
ANS -
import java.io.*;
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Write a Java program to input name & salary of employee & throw user defined
exception if entered salary is negative.
ANS -
import java.util.Scanner;
class Employee {
private String name;
private double salary;
try {
System.out.print("Enter employee name: ");
String name = scanner.nextLine();
import java.sql.*;
public class GFG {
Class.forName("com.mysql.cj.jdbc.Driver");
//Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Write a Java Program to define a class, describe its constructor, and overload the
constructors and instantiate its object. (Student- Sname, Roll No, Marks1, Marks2)
ANS -
// Creating object using constructor with name and roll number only
Student student2 = new Student("Jane Smith", 456);
student2.displayDetails();
}
}
Write a java program to calculate the area of rectangle, tringle and circle by
implementing interface.
ANS -
interface Shape {
double calculateArea();
}
@Override
public double calculateArea() {
return length * width;
}
}
@Override
public double calculateArea() {
return 0.5 * base * height;
}
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class AreaCalculation {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
double rectangleArea = rectangle.calculateArea();
System.out.println("Rectangle Area: " + rectangleArea);
<html>
<body>
<applet code="ParameterApplet.class" width="200" height="100">
<param name="message" value="Welcome to my Applet!">
</applet>
</body>
</html>
//ParameterApplet.java
import java.applet.Applet;
import java.awt.*;
@Override
public void init() {
message = getParameter("message");
if (message == null) {
message = "Hello, Applet!";
}
}
@Override
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
}
Write a java program to design a Button and TextBox using awt .
ANS -
import java.awt.*;
import java.awt.event.*;
// Create a Button
Button button = new Button("Click Me");
// Create a TextBox
TextField textField = new TextField();
//Fibonacci.html
<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Series</title>
</head>
<body>
<h2>Fibonacci Series</h2>
<form action="fibonacci.jsp" method="post">
Enter the term:
<input type="number" name="term" required>
<input type="submit" value="Generate">
</form>
</body>
</html>
//Fibonacci.jsp
<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Series</title>
</head>
<body>
<h2>Fibonacci Series</h2>
<%-- Retrieve the term value from the request --%>
<% int term = Integer.parseInt(request.getParameter("term")); %>
import java.applet.Applet;
import java.awt.*;
// Draw a rectangle
g.drawRect(200, 50, 100, 50);
// Draw a line
g.drawLine(50, 200, 250, 200);
// Fill an oval
g.fillOval(200, 150, 100, 100);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<h2>Factorial Calculator</h2>
<form action="factorial.jsp" method="post">
Enter a number:
<input type="number" name="number" required>
<input type="submit" value="Calculate">
</form>
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
@Override
public void init() {
// Register the applet to receive keyboard events
addKeyListener(this);
@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println(keyTypedMessage + keyChar);
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyPressedMessage + KeyEvent.getKeyText(keyCode));
}
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyReleasedMessage + KeyEvent.getKeyText(keyCode));
}
}
Write a Java Program to implement inheritance and demonstrate use of method
overriding.
ANS -
class Shape {
protected String color;
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius + " and color " +
color);
}
}
@Override
public void draw() {
System.out.println("Drawing a rectangle with length " + length + ", width " +
width + " and color " + color);
}
}
import java.applet.Applet;
import java.awt.*;
/* <applet code="MessageApplet.class" width=500 height=500> </applet> */
@Override
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
}
Create an abstract class shape. Derive class sphere from it. Calculate area and
volume of sphere (use method overriding)
client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client{
public static void main(String args[]) throws Exception{
Socket s = new Socket("localhost",4444);
BufferedReader br = new
BufferedReader(newInputStreamReader(s.getInputStream()));
System.out.println("From Server:"+br.readLine());
}
}
server.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server{
public static void main(String args[]) throws Exception{
ServerSocket ss = new ServerSocket(4444);
while(true){
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(new Date());
s.close();
}
}
}
Define class MyDate with members day, month, year. Define default and
parameterized constructors. Accept values from the command line and create a
date object. Throw user defined exceptions – “InvalidDayException” or
“InvalidMonthException” if the day and month are invalid. If the date is valid,
display message “Valid date”.
class InvalidDateException extends Exception{
public String toString(){
return "Invalid Date given";
}
}
class MyDate{
public static void main(String[]args){
try{
if(args.length<3)
throw new NullPointerException();
else{
int dd=Integer.parseInt(args[0]);
int mm=Integer.parseInt(args[1]);
int yy=Integer.parseInt(args[2]);
boolean leap=((yy%400==0)||(yy%4==0 && yy%100!=0));
if(mm < 1||mm >12)
throw new InvalidDateException();
switch(mm){
case 1:
case 2:
if(!leap && dd>28)
throw new InvalidDateException();
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
if(dd < 1||dd>30)
throw new InvalidDateException();
case 11:
case 12:
if(dd < 1||dd >31)
throw new InvalidDateException();
}
System.out.println("Valid input");
}
}catch(Exception e){
System.out.println(e);
}
}
}
Output: -
java MyDate
java.lang.NullPointerException
java MyDate 23 5 2000
Valid input
java MyDate 23 15 2000
Invalid Month given
java MyDate 30 2 2000
Invalid Date given