0% found this document useful (0 votes)
55 views39 pages

Divya Java

1. The document is a lab session submission sheet for the subject Java from JAGANNATH INTERNATIONAL MANAGEMENT SCHOOL. It contains 30 practical questions related to Java programming. 2. Code snippets and explanations are provided for the first 7 questions. This includes steps to compile and run a Java program, programs to read user input, find average of numbers, check if a number is palindrome etc. 3. The submission sheet is signed by the student DIVYA MALIK and contains details like subject name, semester, date of submission etc. It will be evaluated by the faculty member Ms. Minal Maheshwari.

Uploaded by

Paawan Gaba
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
55 views39 pages

Divya Java

1. The document is a lab session submission sheet for the subject Java from JAGANNATH INTERNATIONAL MANAGEMENT SCHOOL. It contains 30 practical questions related to Java programming. 2. Code snippets and explanations are provided for the first 7 questions. This includes steps to compile and run a Java program, programs to read user input, find average of numbers, check if a number is palindrome etc. 3. The submission sheet is signed by the student DIVYA MALIK and contains details like subject name, semester, date of submission etc. It will be evaluated by the faculty member Ms. Minal Maheshwari.

Uploaded by

Paawan Gaba
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 39

JAGANNATH INTERNATIONAL

MANAGEMENT SCHOOL
(DEPT.OF INFORMATION TECHNOLOGY)

(P-VII) Java LabSession:Feb2022-


June2022
BCA-252

SubmittedTo SubmittedBy:
Ms.MinalMaheshwari Name:DIVYA MALIK

AssistantProfessor-IT 01814202020

JIMS,VASANTKUNJ
S.No. NameofthePractical Date Signatur
e
1 Write down the steps to compile and run a
JavaProgram?
WriteaprogramtoprintHelloWorld.
Tostudythe basics of programming

a. Write a program to read name, age, phone


no,genderandCGPAfromuserandprintthevalue.
b. WAPtofindthelargestandsmallestof3numbersusi
ngifelse statement
c. Write a Java program that takes three
2 numbersas input to calculate and print the
average of thenumbers.
d. WAPtocalculateFactorial ofanumber
e. WAPtocheckwhetheragivennumberisArmstrong
or not
f. WAPtocheckleapyear.
g. WriteaJavaprogramthatcheckswhetheragiven
stringis a palindrome ornot.

3 WAP to display integer values of an array using


foreachloop.
4 WAPtoprintStringElementsinarrayusingforeachl
oop
5 WriteaJavaProgram toimplement arrayof objects.

6 WAP to read the array dynamically, sort the


arrayanddisplaythe sorted array.
7 WriteaJavaProgramto
demonstrateuseofnestedclass.
8 ProgramtofindAreaofcircle,RectangleandTria
ngleusingdifferentmethods

9 Javaprogramtodemonstrateexampleofstaticvar
iableand staticmethod.

10 WAPtoimplementSingleInheritance

11 WAPtoimplementMultilevelandHierarchyIn
heritance
12 WAPto createapackage in java
13 WAPto illustratetheconcept ofMethod Overriding
14 WAPtodemonstratetheconceptofAbstractClass
15 Write a program to demonstrate use of
implementinginterfaces.
16 Write a program to demonstrate use of
extendinginterfaces
17 Writeanprogramusingtry,catch,throwandfinally
18 WriteaprogramtoimplementtheconceptofExceptionHa
ndlingusingpredefined exception
19 WriteaprogramtoimplementtheconceptofExceptionH
andlingbycreatinguser-definedexceptions.

20 Writeaprogramtodemonstratethread priority.

21 WAPtoimplementtheconceptofMultithreading

22 WAPtodemonstrateMethodoverloading

23 WAPtoshowconstructoroverloading

24 Writeaprogram toimplementall stringoperations.

25 Writeaprogramtoimplementallstringoperationsusing
String Buffer Methods.

26 WAPtoreadthecontentsfromfileandwritingcontentsint
o a file

27 Developan appletthatdisplaysasimplemessage.

28 WriteaGUIProgramtoAddTwoNumbersUsingAWTa
nd event handling.

WAPtomakealoginGUIusingTextField,PasswordFiel
29 dandLoginButton usingSwings.

30 Write a java program that connects to a


databaseusing JDBC andperform add, delete and
retrieveoperations.
Q1.Write down the steps to compile and run a JavaProgram? Write a
program to print Hello World

CODE:

Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. And type
your first Program.
Step 2: Save the file as FirstJavaProgram.java.
Step 3: In this step, we will compile the program. For this, open command prompt
(cmd) on Windows
To compile the program, type the following command and hit enter.
javac FirstJavaProgram.java
Step 4: After compilation the .java file gets translated into the .class file(byte code). Now
we can run the program. To run the program, type the following command and hit
enter:
java FirstJavaProgram

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Q2. To study the basics of programming


a. Write a program to read name, age, phone no, gender and CGPA
from user and print the value.
b. WAP to find the largest and smallest of 3 number using ifelse
statement
c. Write a Java program that takes three numbers as input to calculate
and print the average of the numbers.
d. WAP to calculate Factorial of a number
e. WAP to check whether a given number is Armstrong or not
f. WAP to check leap year.
Write a Java program that checks whether a given string is a palindrome
or not.

CODE:
A)
import java.util.Scanner;
public class CGPA {
public static void main(String[] args) {
String name;
int age;
Long phoneNum;
boolean gender;
double cgpa;

Scanner scanner = new Scanner(System.in);


System.out.println("Enter name");
name = scanner.nextLine();
System.out.println("Enter the age");
age = scanner.nextInt();
System.out.println("Enter the phoneNum");
phoneNum = scanner.nextLong();
System.out.println("Enter the gender");
gender = scanner.nextBoolean();
System.out.println("Enter the cgpa");
cgpa = scanner.nextDouble();

System.out.println(name);
System.out.println(age);
System.out.println(phoneNum);
System.out.println(gender);
System.out.println(cgpa);
}
}
B)
public class LarAndSmallest {
public static void main(String[] args) {
int fNum = 10;
int sNum = 24;
int tNum = 50;
if(fNum < sNum && fNum < tNum){
System.out.println(fNum + "is the smallest");
}else if(sNum<tNum){
System.out.println(sNum+ "is the smallest");
}else{
System.out.println(tNum + "is the smallest");
}

if(fNum > sNum && fNum > tNum){


System.out.println(fNum + "is the greatest");
}else if(sNum>tNum){
System.out.println(sNum+ "is the greatest");
}else{
System.out.println(tNum + "is the greatest");
}

}
}
C) import java.util.Scanner;
public class AveNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
System.out.println((num1+num2+num3)/3);
}
}

D) public class Factorial {


public static void main(String[] args) {
int num = 5;
int factorial = 1;
for(int i=1;i<=num; i++){
factorial = factorial * i;
}
System.out.println(factorial);
}
}

E)
public class ArmstrongOrNot {
public static void main(String[] args) {
int number = 1634, originalNumber, remainder, result = 0, n = 0;
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10, ++n);
originalNumber = number;
for (;originalNumber != 0; originalNumber /= 10){
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}

F)
public class LeapYear {
public static void main(String[] args) {
int year = 1996;
boolean leap = false;
// if the year is divided by 4
if (year % 4 == 0) {
// if the year is century
if (year % 100 == 0) {
// if year is divided by 400
// then it is a leap year
if (year % 400 == 0)
leap = true;
else
leap = false;
}
// if the year is not century
else
leap = true;
}
else
leap = false;
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
G) import java.util.Scanner;
public class PalindromeOrNot {
public static void main(String[] args) {
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + str.charAt(i);

if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Q3. WAP to display integer values of an array using for each loop and print
String Element in array using for each loop

CODE:

public class ForEachLoop {


public static void main(String[] args) {
int arr[]= {1,2,3,4};
for (int i : arr){
System.out.println(i);
}
}
}

CODE:
public class Ques4 {
public static void main(String[] args) {
String arr[]= {"apple", "banana", "jackfruit"};
for (String i : arr){
System.out.println(i);
}
}}
Q4.WAP to read the array dynamically, sort the array and display the
sorted array.

CODE:

import java.util.Arrays;

public class Ques6 {


public static void main(String[] args) {
int arr[] = {2,4,5,6};
Arrays.sort(arr);
System.out.println("Sorted Array" + Arrays.toString(arr));
}
}

Q5.WriteaJava Program to demonstrate use of nested class.


CODE:

public class Ques7 {

public static void main(String[] args) {


ParentClass pc = new ParentClass();
ParentClass.ChildClass cc = new ParentClass.ChildClass();
}
}
class ParentClass{
ParentClass(){
System.out.println("Parent class got called");
}
public static class ChildClass{
ChildClass(){
System.out.println("Child class got called");
}
}
}

Q6.Java program to demonstrate example of static variable and static


method.

CODE:
public class Ques9 {
public static void main(String[] args) {
System.out.println(calculation.areaOfCircle(5));
}
}
class calculation
{
static double pi = 3.14;
public static double areaOfCircle(int radius){
return pi*radius*radius;
}
}

Q7. WAP to implement Single Inheritance

CODE:

public class Ques10 {


public static void main(String[] args) {
BClass bc = new BClass();
}
}
class PClass{
static int money = 500000;
}
class BClass extends PClass{
BClass(){
System.out.println("MONEY IS: " + money);
}}
Q8. WAP to implement Multilevel and Hierarchy Inheritance

CODE:

public class Ques11 {


public static void main(String[] args) {
bClass bc = new bClass();
System.out.println("\n\n");
PClass pc = new PClass();
mClass mc = new mClass();
}
}
interface dClass{
int money = 1000000;
}
class PClass implements dClass {
PClass(){
System.out.println("D money is p money: "+ money+ "using hierarchical
inheritance");
}
}
class bClass extends PClass{
bClass(){
System.out.println("p money is b money: "+ money+ " with multilevel inheritance
");
}
}
class mClass implements dClass{
mClass(){
System.out.println("d money is m money: " + money + "using hierarchical
inheritance");
}
Q9. WAP to create a package in java

CODE:

package data;

// Class to which the above package belongs


public class Demo {

// Member functions of the class- 'Demo'


// Method 1 - To show()
public void show()
{

// Print message
System.out.println("Hi Everyone");
}

// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}

import data.*;

// Class to which the package belongs


class ncj {

// main driver method


public static void main(String arg[])
{
// Creating an object of Demo class
Demo d = new Demo();

// Calling the functions show() and view()


// using the object of Demo class
d.show();
d.view();
}
}

Q10. WAP to illustrate the concept of Method Overriding

CODE:

public class Ques13 {


public static void main(String[] args) {
childClass cc = new childClass();
childClass cc1 = new childClass(1);
cc.attribute();
}
}

class ppClass{
ppClass(){
System.out.println("Parent constructor got called");
}
public void attribute(){
System.out.println("Parent method called using method overriding");
}
}

class childClass extends ppClass{


childClass(int i){
System.out.println("Constructor overriding with params");
}

public void attribute(){


super.attribute();
System.out.println("Child method called");
}
childClass(){
System.out.println("Child constructor got called");
}
}

Q11. Write a program using try,catch,throw and finally

CODE:
public class Ques17 {
public static void main(String[] args) throws Exception {
try{
int arr[] = {12,3,4};
System.out.println(arr[5]);
}catch (Exception e){
System.out.println(e);
}
finally {
System.out.println("Error catched finally");
}

try{
throw new Exception("MyCreatedException");
}
catch (Exception e2){
System.out.println(e2);
}
}
}
Q12. WAP to demonstrate the concept of Abstract Class

CODE:
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstractDemo
{
public static void main(String[] args)
{
System.out.println("DIVYA MALIK-01814202020");
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);}}

Q13. Write a program to demonstrate use of implementing interfaces

CODE:
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("Drawing Rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("Drawing Circle");}
}
public class interfaceprog{
public static void main(String args[]){
System.out.println("DIVYA MALIK-01814202020");
Drawable d=new Circle();
d.draw();
}}
Q14. Write a program to implement the concept of Exception Handling
using predefined exception and user defined exception.

A) Predefined Exception-:

CODE:
public class PredefinedException {
public static void main(String args[])
{
int positive = 35;
int zero = 0;
int result = positive/zero;
//Give Unchecked Exception here.
System.out.println(result);
}
}

B) User Defined Exception

class InvalidAgeException extends Exception


{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class UserExceptionMarriage
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(16);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

Q15. Write a program to demonstrate thread priority.

CODE:
public class threadpriority implements Runnable {
public void run() {
System.out.println(Thread.currentThread()); // This method is static.
}

public static void main(String[] args) {


threadpriority a = new threadpriority();
Thread t = new Thread(a, "DIVYA MALIK-01814202020");

System.out.println("Priority of Thread: " + t.getPriority());


System.out.println("Name of Thread: " + t.getName());
t.start();
}
}
Q16. WAP to Check the Thread Status using multithreading

CODE:
import java.util.Set;

class MyThread implements Runnable {


public void run() {
try {
Thread.sleep(2000);
} catch (Exception err) {
System.out.println(err);
}
}
}

public class threadstatus {


public static void main(String args[]) throws Exception {
System.out.println("\nMADEBY:DIVYA MALIK-01814202020\n");

for (int thread_num = 0; thread_num< 5; thread_num++) {


Thread t = new Thread(new MyThread());
t.setName("MyThread:" + thread_num);
t.start();
}
Set<Thread>threadSet = Thread.getAllStackTraces().keySet();
for (Thread t :threadSet) {
System.out.println("Thread :" + t + ":"
+ "Thread status : "
+ t.getState());
}
}
}
Q17. WAP to implement the concept of Multithreading

CODE:
public class MultiThreading {
public static void main (String args[]) {
//try block
try
{
System.out.println ("::Try Block::");
int data = 125 / 5;
System.out.println ("Result:" + data);
throw new ArithmeticException(null);
}
//catch block
catch (NullPointerException e) {
System.out.println ("::Catch Block::");
System.out.println (e);

}
//finally block
finally {
System.out.println (":: Finally Block::");
System.out.println ("No Exception::finally block executed");
}
System.out.println ("rest of the code...");
}
}
Q18. Write a program to implement all string operations.

CODE:
public class stringoperations {
public static void main(String args[]) {
System.out.println("Made By:DIVYA MALIK-01814202020");
String s1 = "Hello";
String s2 = "World";
System.out.println("The strings are " + s1 + "and" + s2);
int len1 = s1.length();
int len2 = s2.length();
System.out.println("The length of " + s1 + " is :" + len1);
System.out.println("The length of " + s2 + " is :" + len2);
System.out.println("The concatenation of two strings = " + s1.concat(s2));
System.out.println("First character of " + s1 + "is=" + s1.charAt(0));
System.out.println("The uppercase of " + s1 + "is=" + s1.toUpperCase());
System.out.println("The lower case of " + s2 + "is=" + s2.toLowerCase());
System.out.println(" the letter e occurs at position" + s1.indexOf("e") + "in" + s1);
System.out.println("Substring of " + s1 + "starting from index 2 and ending at 4 is =" +
s1.substring(2, 4));
System.out.println("Replacing 'e' with 'o' in " + s1 + "is =" + s1.replace('e', 'o'));
boolean check = s1.equals(s2);
if (check == false)
System.out.println("" + s1 + " and " + s2 + " are not same");
else
System.out.println("" + s1 + " and " + s2 + "are same");
}
}
Q19. Write a program to implement all string operation using String
Buffer Methods.

CODE:
public class stringbuffer
{
public static void main( String args[] )
{
StringBuffer s = new StringBuffer("DIVYA MALIK");

System.out.println("\n String = "+s); // Will Print the string

System.out.println("\n Length = "+s.length() ); // total numbers of characters


System.out.println("\n Length = "+s.capacity() ); // total allocated capacity

s.setLength(6); // Sets the length and destroy the remaining characters


System.out.println("\n After setting length String = "+s );

s.setCharAt(0,'K'); // It will change character at specified position


System.out.println("\n SetCharAt String = "+s );

s.setCharAt(0,'C');

int a = 007;
s.append(a); // It concatenates the other data type value
System.out.println("\n Appended String = "+s );

s.insert(6," BCA"); // used to insert one string or char or object


System.out.println("\n Inserted String = "+s );

s.reverse();
System.out.println("\n Reverse String = "+s );

s.reverse();

s.delete(6,14); // used to delete sequence of character


System.out.println("\nAfter deleting string="+s);
}
}
Q20. . WAP to read the contents from file and writing contents into a file.

CODE:
import java.io.*;

public class readandwrite {


public static void main(String arg[]) {

File inf = new File("in.dat");


File outf = new File("out.dat");
FileReader ins = null;
FileWriter outs = null;
try {
ins = new FileReader(inf);
outs = new FileWriter(outf);
int ch;
while ((ch = ins.read()) != -1) {
outs.write(ch);
}
} catch (IOException e) {
System.out.println(e);
System.exit(-1);
} finally {
try {
ins.close();
outs.close();
} catch (IOException e) {
}
}
}
}

Q21. WAP to display user registration form using applet

CODE:
USERREGISTRATION.JAVA

import java.awt.*;
public class userregistration extends java.applet.Applet
{
public void init()
{

setLayout(new FlowLayout(FlowLayout.LEFT));

add(new Label("Name :"));


add(new TextField(10));

add(new Label("Address :"));


add(new TextField(10));

add(new Label("Birthday :"));


add(new TextField(10));
add(new Label("Gender :"));
Choice gender = new Choice();
gender.addItem("Man");
gender.addItem("Woman");
Component add = add(gender);

add(new Label("Job :"));


CheckboxGroup job = new CheckboxGroup();
add(new Checkbox("Student", job, false));
add(new Checkbox("Teacher", job, false));

add(new Button("Register"));
add(new Button("Exit"));
}
}

USERREGISTRATION.HTML

<html>
<head><title>Register</title></head>
<body>
<applet code="userregistration.class" width=230 height=300></applet>
</body>
</html>
Q22. WAP to explain important fields of AWT.

CODE:

Q23. WAP to explain important fields of event handling.

CODE:
import java.awt.*;
import java.awt.event.*;
public class eventhandling extends Frame implements ActionListener
{
TextFieldtextField;
eventhandling ()
{
textField = new TextField ();
textField.setBounds (60, 50, 170, 20);
Button button = new Button ("Show");
button.setBounds (90, 140, 75, 40);
button.addActionListener (this);
add (button);
add (textField);
setSize (250, 250);
setLayout (null);
setVisible (true);
}
public void actionPerformed (ActionEvent e)
{
textField.setText ("Hello World");
}
public static void main (String args[])
{
new eventhandling();
}
}
Q24. Objective:Write a GUI Program to Add Two numbers Using AWT
and event handling.

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

public class Users extends Applet implements ActionListener


{

TextField t1 = new TextField(8);


TextField t2 = new TextField(8);
TextField t3 = new TextField(8);
Label l1 = new Label("FIRST NO :");
Label l2 = new Label("SECOND NO :");
Label l3 = new Label("SUM :");
Button b = new Button("ADD");

public void init()


{
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource() == b)
{
int n1 = Integer.parseInt(t1.getText());
int n2 = Integer.parseInt(t2.getText());
t3.setText(" " +(n1 + n2));
}
}
}
Q25. WAP to show database connection is established.

CODE:
import java.sql.*;
public class testconn{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Persons","root","");

Statement stmt=con.createStatement();
System.out.println(" Connection established");

ResultSetrs=stmt.executeQuery("select * from BOOKS");


while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "
+rs.getFloat(4)+" "+ rs.getInt(5)+" ");

con.close();
}catch(Exception e){ System.out.println(e);} }}
Q26. WAP to make a login GUI using TextField, Password Field and Login
Button using Swings.

CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class LoginFrame extends JFrame implements ActionListener {

Container container = getContentPane();


JLabeluserLabel = new JLabel("USERNAME");
JLabelpasswordLabel = new JLabel("PASSWORD");
JTextFielduserTextField = new JTextField();
JPasswordFieldpasswordField = new JPasswordField();
JButtonloginButton = new JButton("LOGIN");
JButtonresetButton = new JButton("RESET");
JCheckBoxshowPassword = new JCheckBox("Show Password");

LoginFrame() {
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();

public void setLayoutManager() {


container.setLayout(null);
}

public void setLocationAndSize() {


userLabel.setBounds(50, 150, 100, 30);
passwordLabel.setBounds(50, 220, 100, 30);
userTextField.setBounds(150, 150, 150, 30);
passwordField.setBounds(150, 220, 150, 30);
showPassword.setBounds(150, 250, 150, 30);
loginButton.setBounds(50, 300, 100, 30);
resetButton.setBounds(200, 300, 100, 30);

public void addComponentsToContainer() {


container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}

public void addActionEvent() {


loginButton.addActionListener(this);
resetButton.addActionListener(this);
showPassword.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String userText;
String pwdText;
userText = userTextField.getText();
pwdText = passwordField.getText();
if (userText.equalsIgnoreCase("mrinal")
&&pwdText.equalsIgnoreCase("12345")) {
JOptionPane.showMessageDialog(this, "Login Successful");
} else {
JOptionPane.showMessageDialog(this, "Invalid Username or Password");
}

}
if (e.getSource() == resetButton) {
userTextField.setText("");
passwordField.setText("");
}
if (e.getSource() == showPassword) {
if (showPassword.isSelected()) {
passwordField.setEchoChar((char) 0);
} else {
passwordField.setEchoChar('*');
}
}
}

}
public class Login {
public static void main(String[] a) {
System.out.println("Made By:Mrinal Gupta(033)");
LoginFrame frame = new LoginFrame();
frame.setTitle("Login Form");
frame.setVisible(true);

frame.setBounds(10, 10, 370, 600);


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);

}
Q27. WAP to explain servlet concept.

CODE:
import javax.servlet.http.*;  
import javax.servlet.*;  
import java.io.*;  
public class DemoServlet extends HttpServlet{  
public void doGet(HttpServletRequestreq,HttpServletResponse res)  
throws ServletException,IOException  

res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");  
pw.println("Welcome to servlet");  
pw.println("</body></html>");  
pw.close(); 
}}  

web.xml file

<web-app>  
 
<servlet>  
<servlet-name>sonoojaiswal</servlet-name>  
<servlet-class>DemoServlet</servlet-class>  
</servlet>  
 
<servlet-mapping>  
<servlet-name>sonoojaiswal</servlet-name>  
<url-pattern>/welcome</url-pattern>  
</servlet-mapping>  
 
</web-app>  

Q28. WAP to display data of database using jdbc.

CODE:
import java.sql.*;
public class PersonsJDBC{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Persons","root","");

Statement stmt=con.createStatement();
ResultSetrs=stmt.executeQuery("select * from BOOKS");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "
+rs.getFloat(4)+" "+ rs.getInt(5)+" ");

con.close();
}catch(Exception e){ System.out.println(e);}

}}
Q30. Write a java program that connects to a database using JDBC and
does add, delete and retrieve operations.

CODE:
import java.sql.*;
public class UpdateJDBC{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Persons","root","");
Statement stmt=con.createStatement();

System.out.println("Database");
ResultSet rs2=stmt.executeQuery("select * from BOOKS");
while(rs2.next())
System.out.println(rs2.getInt(1)+" "+rs2.getString(2)+" "+rs2.getString(3)+" "
+rs2.getFloat(4)+" "+ rs2.getInt(5)+" ");

System.out.println("\n\n");

String sqlInsert = "insert into books values (3001, 'Gone Fishing', 'Kumar', 11.11, 11)";
System.out.println("The SQL statement is: " + sqlInsert + "\n"); // Echo for debugging
int countInserted= stmt.executeUpdate(sqlInsert);
System.out.println(countInserted + " records inserted.\n");

System.out.println("Database after insertion");


ResultSetrs=stmt.executeQuery("select * from BOOKS");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "
+rs.getFloat(4)+" "+ rs.getInt(5)+" ");
System.out.println("\n\n");

String sqlDelete = "delete from books where id >= 3000 and id < 4000";
System.out.println("The SQL statement is: " + sqlDelete + "\n"); // Echo for debugging
int countDeleted =stmt.executeUpdate(sqlDelete);
System.out.println(countDeleted + " records deleted.\n");

System.out.println("Database after deletion");


ResultSet rs1=stmt.executeQuery("select * from BOOKS");
while(rs1.next())
System.out.println(rs1.getInt(1)+" "+rs1.getString(2)+" "+rs1.getString(3)+" "
+rs1.getFloat(4)+" "+ rs1.getInt(5)+" ");

System.out.println("\n\n");

con.close();
}catch(Exception e){ System.out.println(e);}

}
}

You might also like