0% found this document useful (0 votes)
98 views58 pages

Java Programming Basics and Examples

Here are the steps to create a package and store a class in Java: 1. Create a folder named "Calculator" 2. Create a file named "Add.java" inside the Calculator folder 3. Add the package declaration "package Calculator;" at the top 4. Write the Add class inside the package: package Calculator; public class Add{ // class definition } 5. Compile the class using javac: javac -d . Add.java 6. You have now successfully created a package Calculator and stored the Add class inside it. The -d option specifies the current directory as the destination for the class files. So in summary,
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

Topics covered

  • Error Handling,
  • Vector Class,
  • Inheritance,
  • Matrix Multiplication,
  • Sorting Arrays,
  • Hello World,
  • AWT,
  • Command Line Arguments,
  • IP Address,
  • Java
0% found this document useful (0 votes)
98 views58 pages

Java Programming Basics and Examples

Here are the steps to create a package and store a class in Java: 1. Create a folder named "Calculator" 2. Create a file named "Add.java" inside the Calculator folder 3. Add the package declaration "package Calculator;" at the top 4. Write the Add class inside the package: package Calculator; public class Add{ // class definition } 5. Compile the class using javac: javac -d . Add.java 6. You have now successfully created a package Calculator and stored the Add class inside it. The -d option specifies the current directory as the destination for the class files. So in summary,
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

Topics covered

  • Error Handling,
  • Vector Class,
  • Inheritance,
  • Matrix Multiplication,
  • Sorting Arrays,
  • Hello World,
  • AWT,
  • Command Line Arguments,
  • IP Address,
  • Java

1.

Write a Program to print the “Hello World”

Program:
class Simple
{
public static void main(String args[])
{
[Link]("Hello World");
}
}

Save the above file as [Link].

To compile:

javac [Link]

2. Display the messages using print() & println()


methods.

class Demo
{
public static void main(String args[])
{
[Link]("Hello ");
[Link]("Java");
}
}

Output:
Hello Java
1
Java println() method
The println() method is similar to print() method except that it moves the
cursor to the next line after printing the result. It is used when you want the result
in two separate lines. It is called with "out" object. If we want the result in two
separate lines, then we should use the println() method.

Example
The following example, the println() method display the string in two separate
lines.

class Demo
{
public static void main(String args[])
{
[Link]("Hello ");
[Link]("Java");
}
}

Output:

Hello

Java

3. WAP to print the addition of two numbers using


command line arguments.

Program:
public class CommandLineArguments
{
public static void main(String[] args)
{
int a = [Link](args[0]);
2
int b = [Link](args[1]);
int sum = a + b;
[Link]("Sum is: " + sum);
}
}

Run above program from command prompt


Compile:
javac [Link]

Run:
java CommandLineArguments 20 50

Output:

Sum is: 70

4. WAP to find the largest number among 3


numbers.

Program:
public class Largest
{
public static void main(String[] args)
{
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)
[Link](num1+" is the largest Number");
else if (num2 >= num1 && num2 >= num3)
[Link](num2+" is the largest Number");
else
[Link](num3+" is the largest Number");
}
}
3
Output:

20 is the largest Number

5. WAP to calculate the factorial of a given number.

Program:

import [Link];
class FactorialExample
{
public static void main(String args[])
{
int i,fact=1, n;
Scanner s1=new Scanner([Link]);
[Link](“Enter a number :”);
n=[Link]();

for(i=1;i<=n; i++)
{
fact=fact*i;
}
[Link]("Factorial of "+n+" is: "+fact);
}
}

Output:

4
Enter a number : 5
Factorial of 5 is : 120

6. WAP to sort the array elements.


Program

import [Link];
public class SortArrayExample1
{
public static void main(String[] args)
{
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
[Link](array);
[Link]("Elements of array sorted in ascending order: ");
for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}
}
}

Output:
Array elements in ascending order:
5
12
22
23
34
67
90
5
109

7. WAP to print the multiplication of two matrices.

Program:
import [Link];

public class Multiplication


{
public static void main(String[] args)
{
int i, j, k, sum=0;
int[][] matrixOne = new int[3][3];
int[][] matrixTwo = new int[3][3];
int[][] matrixThree = new int[3][3];
Scanner scan = new Scanner([Link]);
[Link]("Enter Elements of First Matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
matrixOne[i][j] = [Link]();
}
}
[Link]("Enter Elements of Second Matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
matrixTwo[i][j] = [Link]();
}
}
// multiplying the two matrices
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
6
sum = 0;
for(k=0; k<3; k++)
{
sum = sum + (matrixOne[i][k] * matrixTwo[k][j]);
}
matrixThree[i][j] = sum;
}
}
[Link]("\nMultiplication of Two Matrices is:");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
[Link](matrixThree[i][j]+ " ");
}
[Link]("\n");
}
}
}

Output:
Enter elements of First Matrix:
1
2
3
4
5
6
7
8
9
Enter elements of Second Matrix:
1
2
1
2

7
4
6
7
2
5
Multiplication of two Matrices is :

26 16 28
56 40 64
86 64 100

8. WAP to demonstrate the Vector Class.

Program:
import [Link].*;
public class VectorExample1
{
public static void main(String args[])
{
Vector<String> vec = new Vector<String>(4);
[Link]("Tiger");
[Link]("Lion");
[Link]("Dog");
[Link]("Elephant");
[Link]("Size is: "+[Link]());
[Link]("Default capacity is: "+[Link]());
[Link]("Vector element is: "+vec);
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
[Link]("Size after addition: "+[Link]());
8
[Link]("Capacity after addition is: "+[Link]());
[Link]("Elements are: "+vec);
if([Link]("Tiger"))
{
[Link]("Tiger is present at the index " +[Link]("Tiger"));
}
else
{
[Link]("Tiger is not present in the list.");
}
[Link]("The first animal of the vector is = "+[Link]());
[Link]("The last animal of the vector is = "+[Link]());
}
}

Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

9
9. WAP to show the method overloading and
overriding.

Method Overloading: changing no. of arguments

class Adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}

Output:
22

33

Method Overloading: changing data type of arguments

class Adder
{
10
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}
}

Output:
22

24.9

Example:

class Bank
{
int getRateOfInterest()
{
return 0;
}
11
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}

class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
[Link]("SBI Rate of Interest: "+[Link]());
12
[Link]("ICICI Rate of Interest: "+[Link]());
[Link]("AXIS Rate of Interest: "+[Link]());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

13
10. WAP to calculate the area of rectangle using
parameterized constructor.

Example:
import [Link];

class Rectangle

int area;

Rectangle(int l, int w)

area = l * w;

void display()

[Link]("Area of rectangle is: " + area);

class Test

public static void main(String args[])

int length, width;

Scanner sc = new Scanner([Link]);


14
[Link]("Enter length of rectangle:");

length = [Link]();

[Link]("Enter width of rectangle:");

width = [Link]();

Rectangle t = new Rectangle(length, width);

[Link]();

Output:
Enter length of rectangle:12

Enter width of rectangle: 3

Area of rectangle is: 36

15
11: Write a program to create a package and store
class in this package.

Program:
Create a package named as Calculator and store Add class in this package –
package p1;
import [Link].*;
public class Add
{
int s;
public void sum()
{
[Link]("Enter the first number: ");
Scanner scan=new Scanner([Link]);
int x=[Link]();
[Link]("Enter the second number: ");
Scanner scan1=new Scanner([Link]);
int y=[Link]();
s=x+y;
[Link]("sum="+s);
}
}

How to compile java package


Syntax:
javac -d directory javafilename

16
For Example
javac -d . [Link]

Add another class Sub in the same package


package p1;
import [Link].*;
public class Sub
{
int s;
public void minus()
{
[Link]("Enter the first number: ");
Scanner scan=new Scanner([Link]);
int x=[Link]();
[Link]("Enter the second number: ");
Scanner scan1=new Scanner([Link]);
int y=[Link]();
s=x-y;
[Link]("sub="+s);
}
}

Now, Compile this file again


Syntax:
javac -d directory javafilename

17
For example
javac -d . [Link]

[Link]
import [Link].*;
import [Link];
import [Link];
public class Calculator
{
public static void main(String args[])
{
[Link]("Enter your choice: ");
Scanner scan=new Scanner([Link]);
int t=[Link]();
switch(t)
{
case 1:
Add a=new Add();
[Link]();
break;
case 2:
Sub s=new Sub();
[Link]();
break;
default:
[Link](“Invalid Choice”);
}

18
}
}

Output:
Enter your choice: 1
Enter the first number: 20
Enter the second number: 10
Sum= 30

Enter your choice: 2


Enter the first number: 20
Enter the second number: 10
Sub= 10

19
12: Write a program to demonstrate the multithreading.

Program:
class A extends Thread
{
public void run()
{
for(int i=1; i<=5; i++)
{
[Link]("From Thread A : "+i);
}
[Link]("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
[Link]("From Thread B : "+j);
}
[Link]("Exit from B");
}
}
class C extends Thread

20
{
public void run()
{
for(int k=1; k<=5; k++)
{
[Link]("From Thread C : "+k);
}
[Link]("Exit from C");
}
}
class TestThread
{
public static void main(String arg[])
{
A a1=new A();
B b1=new B();
C c1=new C();
[Link]();
[Link]();
[Link]();
}
}

Output:

21
13: WAP to draw a Human Face using Applet.

Program:

import [Link].*;
import [Link].*;
public class Human_Face extends Applet
{
public void init()
{
setBackground([Link]);
}
public void paint(Graphics g)
{

22
Color clr=new Color(255,179,86);
[Link](clr);
[Link](100,100,250,300);
[Link](100,100,250,300);
[Link]([Link]);
[Link](160,185,40,25);
[Link](160,185,40,25);
[Link](250,185,40,25);
[Link](250,185,40,25);
[Link](160,170,35,10,0,180);
[Link](250,170,35,10,0,180);
[Link](210,265,210,275);
[Link](240,265,240,275);
[Link](210,275,30,10,0,-180);
[Link](175,300,100,50,0,-180);
}
}
/*
<applet code = Human_Face.class width=500 height=500>
</applet>
*/

To execute the applet use the following commands:


javac Human_Face.java

appletviewer Human_Face.java

23
Output:

14: Write a program to show the IP address and host


name of your system.

Program
import [Link].*;
public class Demo
{
public static void main(String[] args)
{
Try
{
InetAddress my_address = [Link]();
[Link]("The IP address is : " + my_address.getHostAddress());
[Link]("The host name is : " + my_address.getHostName());

24
}
catch (UnknownHostException e)
{
[Link]( "Couldn't find the local address.");
}
}
}

Output:

15: Write a program to design an interface of Login


Form using AWT.
Program:

[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
class CreateLoginForm extends JFrame implements ActionListener
{
25
JButton b1;
JPanel newPanel;
JLabel userLabel, passLabel;
final JTextField textField1, textField2;
CreateLoginForm()
{
userLabel = new JLabel();
[Link]("Username");
textField1 = new JTextField(15);
passLabel = new JLabel();
[Link]("Password");
textField2 = new JPasswordField(15);
b1 = new JButton("SUBMIT");
newPanel = new JPanel(new GridLayout(3, 1));
[Link](userLabel);
[Link](textField1);
[Link](passLabel);
[Link](textField2);
[Link](b1);
add(newPanel, [Link]);
[Link](this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae)
{
String userValue = [Link](); //get user entered username from th
e textField1 String passValue = [Link]();
26
if ([Link]("bca") && [Link]("123"))
{
NewPage page = new NewPage();
[Link](true);
JLabel wel_label = new JLabel("Welcome: "+userValue);
[Link]().add(wel_label);
}
Else
{
[Link]("Please enter valid username and password");
}
}
}
//create the main class
class LoginFormDemo
{
//main() method start
public static void main(String arg[])
{
try
{
CreateLoginForm form = new CreateLoginForm();
[Link](300,100);
[Link](true);
}
catch(Exception e)
{
27
[Link](null, [Link]());
}
}
}
[Link]
//import required classes and packages
import [Link].*;
import [Link].*;
class NewPage extends JFrame
{
NewPage()
{
setDefaultCloseOperation([Link].
WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
setSize(400, 200);
}
}

Output:
Javac [Link]
Java CreateLoginForm

28
16: Write a program to design an interface of
Calculator to perform basic arithmetic operations.

Aim:
To design an interface of Calculator to perform basic arithmetic operations

Program:
import [Link].*;
import [Link].*;
class Calculator extends Frame implements ActionListener
{
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bm, bd, bs, ba, be, bc;
TextField screen;
int n1 = 0, sign = 4;

Calculator()
{
b0 = new Button("0");
29
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
bm = new Button("*");
bd = new Button("/");
bs = new Button("-");
ba = new Button("+");
be = new Button("=");
bc = new Button("Clear");
[Link](10,100,50,50);
[Link](60,100,50,50);
[Link](110,100,50,50);
[Link](160,100,50,50);
[Link](10,150,50,50);
[Link](60,150,50,50);
[Link](110,150,50,50);
[Link](160,150,50,50);
[Link](10,200,50,50);
[Link](60,200,50,50);
[Link](110,200,50,50);
[Link](160,200,50,50);
30
[Link](10,250,50,50);
[Link](60,250,100,50);
[Link](160,250,50,50);
[Link](10,80,200,20);
[Link]([Link]);
[Link]([Link]);
screen = new TextField();
[Link](10,50,200,30);
add(b7);
add(b8);
add(b9);
add(bm);
add(b4);
add(b5);
add(b6);
add(bd);
add(b1);
add(b2);
add(b3);
add(bs);
add(b0);
add(be);
add(ba);
add(bc);
add(screen);
[Link](this);
[Link](this);
31
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
setSize(220,310);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
};
}
public void append(int a)
{
32
int c;
if([Link]().equals(""))
{
[Link]([Link](a));
}

else
{
c = [Link]([Link]());
[Link]([Link]((c*10)+a));
}
}

public void actionPerformed(ActionEvent e)


{
int n2 = 1, res;
if([Link]()==b0)
{
append(0);
}
if([Link]()==b1)
{
append(1);
}
if([Link]()==b2)
{
append(2);

33
}
if([Link]()==b3)
{
append(3);
}
if([Link]()==b4)
{
append(4);
}

if([Link]()==b5)
{
append(5);
}
if([Link]()==b6)
{
append(6);
}
if([Link]()==b7)
{
append(7);
}
if([Link]()==b8)
{
append(8);
}
if([Link]()==b9)
34
{
append(9);
}
if([Link]()==be)
{

[Link](n1);
if(n1>0)
{
n2 = [Link]([Link]());
if(sign < 4)
{
switch(sign)
{
case 0:
[Link]([Link](n1*n2));
break;
case 1:
[Link]([Link](n1/n2));
break;
case 2:
[Link]([Link](n1-n2));
break;
default:
[Link]([Link](n1+n2));
break;
}
35
}
}
else
{
[Link]("");
}
}
if([Link]()==bd || [Link]()==bm || [Link]()==bs ||
[Link]()==ba || [Link]()==bc)
{
if([Link]().equals(""))
{
[Link]("");
}
else if([Link]()==bm)
{
n1 = [Link]([Link]());
[Link](n1);
[Link]("");
sign = 0;
}
else if([Link]()==bd)
{
n1 = [Link]([Link]());
[Link]("");
sign = 1;
}
36
else if([Link]()==bs)
{
n1 = [Link]([Link]());
[Link]("");
sign = 2;
}
else if([Link]()==ba)
{
n1 = [Link]([Link]());
[Link]("");
sign = 3;
}
else if([Link]()==bc)
{
[Link]("");
}
}
}
public static void main(String[] args)
{
new Calculator();
}
}

Output:

37
17: Write a program to design a registration form in
HTML.
Program:
Registration Form
<Html>
<head>
<title> Registration Page </title>
</head>
<body bgcolor="Lightskyblue">
<br> <br>
<form>
<label> Firstname </label>
<input type="text" name="firstname" size="15"/> <br> <br>
<label> Middlename: </label>
<input type="text" name="middlename" size="15"/> <br> <br>
<label> Lastname: </label>
38
<input type="text" name="lastname" size="15"/> <br> <br>
<label> Course : </label>
<select>
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="[Link]">[Link]</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="[Link]">[Link]</option>
</select>
<br>
<br>
<label> Gender : </label><br>
<input type="radio" name="male"/> Male <br>
<input type="radio" name="female"/> Female <br>
<input type="radio" name="other"/> Other
<br>
<br>
<label> Phone : </label>
<input type="text" name="country code" value="+91" size="2"/>
<input type="text" name="phone" size="10"/> <br> <br>
Address
<br>
<textarea cols="80" rows="5" value="address"> </textarea>
<br> <br>
Email:
39
<input type="email" id="email" name="email"/> <br>
<br> <br>
Password:
<input type="Password" id="pass" name="pass"> <br>
<br> <br>
Re-type password:
<input type="Password" id="repass" name="repass"> <br> <br>
<input type="button" value="Submit"/>
</form>
</body>
</html>

Output:

40
18. WAP to design an interface to save, modify and
delete the student’s record.

41
Program:

import [Link].*;
import [Link];
public class Student extends [Link]
{
Connection con;
Statement st;
ResultSet rs;
public Student()
{
initComponents();
}
private void jButton1ActionPerformed([Link] evt)
{
try
{
[Link]("[Link]");
con=[Link]("jdbc:odbc:stud");
st=[Link]();
int i=[Link]("insert into Student values("+[Link]([Link]() )
+",'" + [Link]()+"','"+[Link]()+"','"+[Link]()+"')");
if(i>0)
{
[Link](null, "Record Saved....");
[Link](null);
[Link](null);
[Link](null);
[Link](null);
}
}
catch(Exception e)
42
{
[Link](e);

}
}
private void jButton5ActionPerformed([Link] evt)
{
if([Link]().equals(""))
{
[Link](null, "Fill Dept Id");
[Link]();
}
else
{
try
{
[Link]("[Link]");
con=[Link]("jdbc:odbc:stud");
st=[Link]();
rs=[Link]("select * from Student where sid="+[Link]([Link]())
+"" );
if([Link]())
{
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
}
else
{
[Link](null, "Record not found");
}

43
}
catch(Exception e)
{
[Link](e);

}}
}
private void jButton3ActionPerformed([Link] evt)
{
try
{
[Link]("[Link]");// load the driver
con=[Link]("jdbc:odbc:Stud");// Create the connection with
datanase
st=[Link]();// Create the statement for the database
int a=[Link]("delete from Student where sid="+[Link]([Link]() )
+"");
if(a>0)
{
[Link](null, "Student Information deleted...");
[Link](null);
[Link](null);
[Link](null);
[Link](null);
}
else
{
[Link](null, "Student Information not deleted...");
}
}
catch(Exception e)

44
{
[Link](e);
}
}
private void jButton2ActionPerformed([Link] evt)
{
try
{
[Link]("[Link]");// load the driver
con=[Link]("jdbc:odbc:Stud");
st=[Link]();// Create the statement for the database
int a=[Link]("update Student set sname='"+[Link]()+"',
sclass='"+[Link]()+"', SContact='"+[Link]()+"' where
sid="+[Link]([Link]())+"");
if(a>0)
{
[Link](null, "Record Updated");
[Link](false);
[Link](false);
[Link](false);
[Link](true);
}
else
{
[Link](null, "Record not Updated");
}
}
catch(Exception e)
{
[Link](e);
}

45
}
private void jButton4ActionPerformed([Link] evt)
{
[Link](0);
}
public static void main(String args[])
{
try {
for ([Link] info :
[Link]()) {
if ("Nimbus".equals([Link]())) {
[Link]([Link]());
break;
}
}
} catch (ClassNotFoundException ex)
{ [Link]([Link]()).log([Link]
ERE, null, ex);
} catch (InstantiationException ex)
{ [Link]([Link]()).log([Link]
VERE, null, ex);
} catch (IllegalAccessException ex)
{ [Link]([Link]()).log([Link]
ERE, null, ex);
} catch ([Link] ex)
{ [Link]([Link]()).log([Link]
VERE, null, ex);
}
[Link](new Runnable()
{
public void run() {

46
new Student().setVisible(true);
}
});
}

47
Output:

19: WAP to design the File and Edit menus in java.

Program:
import [Link].*;
import [Link];
import [Link];
import [Link];

48
import [Link];
public class MenuDialog extends Frame implements ActionListener ,ItemListener
{
Dialog dialog;
Label l;
MenuDialog()
{
MenuBar mBar = new MenuBar();
setMenuBar(mBar);
Menu file = new Menu("File");
MenuItem new_file = new MenuItem("New");
MenuItem open_file = new MenuItem("Open");
MenuItem save_file = new MenuItem("Save");
new_file.addActionListener(this);
open_file.addActionListener(this);
save_file.addActionListener(this);
[Link](new_file);
[Link](open_file);
[Link](save_file);
[Link](file);
Menu edit = new Menu("Edit");
MenuItem undo_edit = new MenuItem("Undo");
CheckboxMenuItem cut_edit = new CheckboxMenuItem("Cut");
CheckboxMenuItem copy_edit = new CheckboxMenuItem("Copy");
CheckboxMenuItem edit_edit = new CheckboxMenuItem("Paste");
undo_edit.addActionListener(this);
cut_edit.addItemListener(this);
49
copy_edit.addItemListener(this);
edit_edit.addItemListener(this);
[Link](undo_edit);
[Link](cut_edit);
[Link](copy_edit);
[Link](edit_edit);
[Link](edit);
dialog = new Dialog(this,false);
[Link](200,200);
[Link]("Dialog Box");
Button b = new Button("Close");
[Link](this);
[Link](b);
[Link](new FlowLayout());
l = new Label();
[Link](l);
}
public void actionPerformed(ActionEvent ie)
{
String selected_item = [Link]();
switch(selected_item)
{
case "New": [Link]("New");
break;
case "Open": [Link]("Open");
break;
case "Save": [Link]("Save");
50
break;
case "Undo": [Link]("Undo");
break;
case "Cut": [Link]("Cut");
break;
case "Copy": [Link]("Copy");
break;
case "Paste": [Link]("Paste");
break;
default: [Link]("Invalid Input");
}
[Link](true);
if(selected_item.equals("Close"))
{
[Link]();
}
}
public void itemStateChanged(ItemEvent ie)
{
[Link]();
}
public static void main(String[] args)
{
MenuDialog md = new MenuDialog();
[Link](true);
[Link](400,400);
}
51
}
Output:

52
20. WAP to display the student’s data in a table.

Program:

import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;

public class SearchResult implements ActionListener


{
JFrame frame, frame1;
JTextField textbox;
JLabel label;
JButton button;
JPanel panel;
static JTable table;
String[] columnNames = {"Roll No", "Name", "Class", "Section"};
public void createUI()
{
frame = new JFrame("Database Search Result");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](null);
textbox = new JTextField();
[Link](120,30,150,20);
label = new JLabel("Enter your roll no");
53
[Link](10, 30, 100, 20);
button = new JButton("search");
[Link](120,130,150,20);
[Link](this);
[Link](textbox);
[Link](label);
[Link](button);
[Link](true);
[Link](500, 400);
}
public void actionPerformed(ActionEvent ae)
{
button = (JButton)[Link]();
[Link]("Showing Table Data.......");
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
[Link](columnNames);
table = new JTable();
[Link](model);
[Link](JTable.AUTO_RESIZE_ALL_COLUMNS);
[Link](true);
54
JScrollPane scroll = new JScrollPane(table);
[Link](
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
[Link](
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
String textvalue = [Link]();
String roll= "";
String name= "";
String cl = "";
String sec = "";
try
{
[Link](“[Link]”);
Connection con = [Link](“jdbc:odbc:mydsn”);
String sql = "select * from student where rollno = "+textvalue;
PreparedStatement ps = [Link](sql);
ResultSet rs = [Link]();
int i =0;
if([Link]())
{
roll = [Link]("rollno");
name = [Link]("name");
cl = [Link]("class");
sec = [Link]("section");
[Link](new Object[]{roll, name, cl, sec});
i++;
}
55
if(i <1)
{
[Link](null, "No Record Found","Error",
JOptionPane.ERROR_MESSAGE);
}
if(i ==1)
{
[Link](i+" Record Found");
}
else
{
[Link](i+" Records Found");
}
}
catch(Exception ex)
{
[Link](null, [Link](),"Error",
JOptionPane.ERROR_MESSAGE);
}
[Link](scroll);
[Link](true);
[Link](400,300);
}
public static void main(String args[])
{
SearchResult sr = new SearchResult();
[Link]();
56
}
}
Output :

When you will execute the [Link] class you will get the output as
follows :
1. At first a GUI window will be opened for taking input to fetch the corresponding
record into the database table as follows :

2. When you will input the value into the textbox (say, give the value 125 into the
textbox) and click on search button then the output will be as follows :

57
58

Common questions

Powered by AI

Method overloading in Java occurs when multiple methods have the same name but differ in the number or type of parameters, allowing them to perform different tasks based on the arguments provided. For example, class Adder has add(int a, int b) and add(int a, int b, int c) which sum varying numbers of integers . Method overriding happens when a child class provides a specific implementation of a method already defined in its parent class, allowing for dynamic polymorphism. For example, if Bank has getRateOfInterest() and subclasses like SBI override it to return different interest rates .

A Java program retrieves and displays data from a database using JDBC (Java Database Connectivity). Establish a connection to the database with DriverManager.getConnection, then use a Statement or PreparedStatement to execute SQL queries. Data is retrieved into a ResultSet object. For displaying student records, iterate through the ResultSet and populate a JTable with the data. Utilize DefaultTableModel to manage table data and JScrollPane for the display interface. For instance, connect to the database via a DSN, execute a 'select' query, and map results to table components for user interaction .

Packages in Java provide namespaces for organizing classes and interfaces, preventing naming conflicts, and promoting modular design. To use packages effectively, a Java file is prefixed with a package statement. Compilation with packages involves using javac with the -d option to specify a directory structure matching the package name. For example, package p1 for class Add requires compiling with javac -d . Add.java, creating a subdirectory reflecting the package hierarchy. Inner classes of packages are accessed with their fully qualified names in other Java files or by importing the package .

Constructors in Java initialize new objects and can be parameterized to assign specific initial values to the object's fields during creation. Parameterized constructors allow for setting initial state without additional setter methods, enhancing encapsulation and reducing potential errors. For instance, in the Rectangle class, a parameterized constructor Rectangle(int l, int w) initializes the rectangle's area with the provided dimensions when an object is instantiated, ensuring the object is fully initialized with consistent data .

The main difference between the print() and println() methods in Java is that println() moves the cursor to the next line after printing the result, unlike print() which keeps the cursor on the same line. This affects the program's output by allowing println() to display each printed element on a new line, whereas print() displays elements on the same line without line breaks .

The Vector class in Java demonstrates dynamic array behavior by automatically resizing itself when elements are added beyond its capacity, which grows in predefined increments. Elements in a Vector can be manipulated using methods like add(), remove(), and set(). For example, a Vector instantiated with an initial capacity of 4 can grow as more elements are added. Methods such as addElement() allow adding items, while remove() deletes them. The size() method returns the number of elements, while capacity() shows the current capacity, demonstrating how Vectors handle collections of varying sizes dynamically .

To find the largest number among three given numbers in Java, you can use nested if-else statements. First, compare the first and second numbers to determine which is greater. Then, compare the larger of these two with the third number. The final comparison yields the largest number. The conditional checks should be structured as follows: if(num1 >= num2 && num1 >= num3) print num1; else if(num2 >= num1 && num2 >= num3) print num2; else print num3 .

To implement matrix multiplication in Java, start by reading two matrices' elements, typically using nested loops and a Scanner for user inputs. Then, to multiply, iterate through each element of the matrices: for each position (i, j) in the result matrix, calculate the sum of products of corresponding row elements from the first matrix and column elements from the second, storing this sum in result[i][j]. The algorithm requires three nested loops: two for iterating through result matrix indices and one for computing the dot product. Matrix dimensions must be compatible (e.g., 3x3 multiplying with 3x3).

Command-line arguments in Java can be utilized by passing them as inputs while executing the program. They are accessed in the main method as a String array. To add two numbers using command-line arguments, first parse the arguments to integers using Integer.parseInt(args[index]). Then, perform the addition and display the result. For instance, int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; System.out.println('Sum is: ' + sum).

In Java, multithreading is implemented by extending the Thread class or implementing the Runnable interface, followed by overriding the run() method where the thread's operational code is defined. Threads are initiated using the start() method which calls the run() method. This approach enables concurrent execution of tasks, improving performance by making full use of CPU resources and allowing for responsive applications even when handling large numbers of tasks or heavy operations. For example, classes ThreadA, ThreadB, and ThreadC are created as separate threads and started in parallel, demonstrating independent and concurrent execution .

You might also like