Divya Java
Divya Java
Divya Java
MANAGEMENT SCHOOL
(DEPT.OF INFORMATION TECHNOLOGY)
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
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
25 Writeaprogramtoimplementallstringoperationsusing
String Buffer Methods.
26 WAPtoreadthecontentsfromfileandwritingcontentsint
o a file
27 Developan appletthatdisplaysasimplemessage.
28 WriteaGUIProgramtoAddTwoNumbersUsingAWTa
nd event handling.
WAPtomakealoginGUIusingTextField,PasswordFiel
29 dandLoginButton usingSwings.
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!");
}
}
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;
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");
}
}
}
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);
}
}
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();
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:
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;
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;
}
}
CODE:
CODE:
CODE:
package data;
// Print message
System.out.println("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}
import data.*;
CODE:
class ppClass{
ppClass(){
System.out.println("Parent constructor got called");
}
public void attribute(){
System.out.println("Parent method called using method overriding");
}
}
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);}}
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);
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(16);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
CODE:
public class threadpriority implements Runnable {
public void run() {
System.out.println(Thread.currentThread()); // This method is static.
}
CODE:
import java.util.Set;
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");
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.reverse();
System.out.println("\n Reverse String = "+s );
s.reverse();
CODE:
import java.io.*;
CODE:
USERREGISTRATION.JAVA
import java.awt.*;
public class userregistration extends java.applet.Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
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:
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.*;
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");
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;
LoginFrame() {
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
@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);
}
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>
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");
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("\n\n");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}