100% found this document useful (1 vote)
142 views43 pages

Java Programs for Basic Operations and GUI

The document contains 6 code snippets demonstrating various Java programming concepts. The first snippet shows a program that accepts two numbers as command line arguments and performs basic arithmetic operations. The second snippet creates a mouse event handler that displays the mouse click position in a text field. The remaining snippets cover additional topics like file handling, database operations, and GUI programming using Swing components.

Uploaded by

66 Rohit Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
142 views43 pages

Java Programs for Basic Operations and GUI

The document contains 6 code snippets demonstrating various Java programming concepts. The first snippet shows a program that accepts two numbers as command line arguments and performs basic arithmetic operations. The second snippet creates a mouse event handler that displays the mouse click position in a text field. The remaining snippets cover additional topics like file handling, database operations, and GUI programming using Swing components.

Uploaded by

66 Rohit Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SLIP 1

1. Write a Java program to accept two numbers using command line argument and calculate
addition, subtraction, multiplication and division
class Command1
public static void main(String args[])
{
int a= [Link](args[0]);
int b=[Link](args[1]);
int add,sub,mul,div;
add=a-b;
[Link]("Additon -"+add);
sub=a-b;
[Link]("Substraction ="+sub);
mul=a*b;
[Link]("Multiplication ="+mul);
div=a/b;
[Link]("Division ="+div);
}

2. Design a screen in Java to handle the Mouse Event such as MOUSE_CLICK and display
the position of the Mouse_Click in a TextField
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseDemo extends JFrame implements MouseListener,MouseMotionListener
{
JTextField t1;
public MouseDemo()
{
setLayout(null);
t1=new JTextField();
[Link](100,100,100,30);
add(t1);
setSize(200,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
[Link]([Link]() + " " + [Link]());
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void mousePressed(MouseEvent me)
{
}
public void mouseDragged(MouseEvent me)
{
}

public void mouseMoved(MouseEvent me)


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

SLIP2
[Link] a Java program to accept a number from command prompt and generate
multiplication table of that number
import [Link].*;
class Multi
public static void main(String args[]) throws Exception
{
BufferedReader B =new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the number: ");
int n = [Link]([Link]());
for (int i=1;i<=10;i++)
{
[Link](n+"="+i+"="+n*i);
}
}

[Link] a java program to create and implement the following GUI using Swing components.
import [Link].*;
import [Link].*;
import [Link].*;
class Calculator extends JFrame implements ActionListener
{
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
JTextField t1;
JPanel p1;
char op;
float no1,no2,ans;
Calculator()
{
setLayout(new BorderLayout());
p1=new JPanel();
t1=new JTextField();
add(t1,[Link]);
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b10=new JButton("0");
b11=new JButton("+");
b12=new JButton("-");
b13=new JButton("*");
b14=new JButton("/");
b15=new JButton(".");
b16=new JButton("=");
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b11);
[Link](b4);
[Link](b5);
[Link](b6);
[Link](b12);
[Link](b7);
[Link](b8);
[Link](b9);
[Link](b13);
[Link](b10);
[Link](b15);

[Link](b16);
[Link](b14);
[Link](new GridLayout(4,4));
add(p1,[Link]);
setSize(400,400);
setTitle("Calculator");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
[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);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
JButton b=(JButton)[Link]();
if(b==b1||b==b2||b==b3||b==b4||b==b5||b==b6||b==b7||b==b8||b==b9||b==b10||b==b1
5)
{
[Link]([Link]() + " "+ [Link]());
}
if(b==b11||b==b12|| b==b13||b==b14)
{
op=([Link]()).charAt(0);
no1=[Link]([Link]());

[Link](" ");
[Link]();
}
if(b==b16)
{
no2=[Link]([Link]());
switch(op)
{
case '+':
ans=no1+no2;
break;
case '-':
ans=no1-no2;
break;
case '*':
ans=no1*no2;
break;
case '/':
ans=no1/no2;
break;
}
[Link]([Link](ans));
}
}
public static void main(String args[])
{
Calculator C=new Calculator();
}
}

SLIP3

1. Write a Java Program to accept a number using BufferedReader and print reverse of that
number.
class Reverse
{
public static void main(String args[])
{
int n= [Link](args[0]);
int rem, reverse=0,num;
n=num;
while(n!=0)
{
rem=n%10;
reverse= reverse*10+rem;
n=n/10;
}
[Link]("Reverse: "+reverse);
}

[Link] a java program to design and implement event handling for following GUI. Use
appropriate Layout and Components. Display selected Name & Vaccine. If 1st Dose is
taken then write Yes otherwise write No

SLIP4
1. Write a Java program to accept a number from command prompt and print the factors of
that number using BufferedReader
import [Link].*;
class Factor
{
public static void main(String args[]) throws Exception
{
BufferedReader B = new BufferedReader(new InputStreamReader([Link])); [Link]("Enter a
number: ");
int n =[Link]([Link]());
int fact=1;
for (int i=1;i<=n;i++)
{
if(n%i==0)
{
[Link](i);
}
}
}
2. Create a Person table with fields (Pid, Pname, and Paddress). Write a menu driven program
to perform the following operations on Person table.
a. Insert
b. Update address of ‘Mr. Patil’ to Mumbai.
c. Display
d. Exit
import [Link].*;
import [Link].*;
class Emp1
{
public static void main(String args[]) throws Exception
{
int pid,k,ch;
ResultSet rs;
String pname,paddress;
[Link]("[Link]");
Connection cn=[Link]("jdbc:postgresql://localhost:5432/fybcsd","postgres","");
Statement st=[Link]();
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
do
{
[Link]("[Link] Table");
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]("Enter Ur Choice");
ch=[Link]([Link]());
switch(ch)
{
case 1:
sql="create table emp2(pid int,pname text,paddress text)";
[Link](sql);
[Link]("Table Is created");
break;

case 2:
[Link]("pid PName Paddress");
pid=[Link]([Link]());
pname=[Link]();
paddress=[Link]();
sql="insert into emp2 values(" + pid + ",'" + pname +"'," + paddress+ ")";
k=[Link](sql);
if(k>0)

[Link]("Record Is Added...!");

break;
case 3:
[Link]("pid paddress");
pid=[Link]([Link]());
paddress=[Link]();
sql="update emp2 set address="+ paddress + " where eno=" + pid;
k=[Link](sql);
if(k>0)
[Link]("Record Is Updated...!");
break;
case 4:
rs=[Link]("select * from emp2");
while([Link]())
{
[Link]([Link](1) + " " + [Link](2) + " " + [Link](3))
}
case 5:
[Link](0);
}
}
while(ch!=5);
}
}

SLIP5

1. Write a Java program which accepts three integer values using Scanner and prints the
maximum and minimum.
import [Link].*;
class Greatest
{
public static void main (string args [])
{
Scanner s= new Scanner (systuen. In);
int num1, num2, num3;
[Link]("Enter three numbers :");
num1 = [Link]();
num2 =[Link]();
num3 = [Link]();
if (num1 > num2 && num1>num3)
{
[Link](num1+" num is "greater"):
}
else if (num2 >num1 && num2>num3)
{
Systim out printin (num2 + " num is greater"):
}
else
{
[Link] (num 3 + "numg is greater"):
}
}
}

2. Write a Program to design following GUI by using swing component JComboBox. On


click of show button display the selected language on JLabel.
import [Link].*;
import [Link].*;
import [Link].*;
class SwingComboEventdemo extends JFrame implements ItemListener
{
JComboBox c1;
JTextField t1;

SwingComboEventdemo()
{
t1= new JTextField();
c1=new JComboBox();
setLayout(null);
add(c1);
add(t1);
[Link](100,100, 100,50);
[Link] (220, 100,100,50);
[Link]("PHP");
[Link]("DotNet");
[Link]("Java");
[Link]("CPP");
setSize(800,800);
setTitle(Combo Event Demo);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
JComboBox C=(JComboBox)[Link]();
if(C==c1)
{
[Link]((String)[Link]());
}
}
public static void main(String args[])
{
SwingComboEventdemo Obj=new SwingComboEventdemo();
}
}

SLIP 6
1. Write a Java program to read an array and print the sum of elements of the array. Also
display array elements in ascending order.
import [Link].*;
class Ascending
{
public static void main(String args[])
{
int no, temp=0;
Scanner S= new Scanner([Link]);
[Link]("Inter no of element in array:");
no=[Link]();
int a[]=new int[no];
[Link]("Enter element of array:");
for( int i=0; i<no; i++)
{
a[i]=[Link]();
}
//sum, of array elemnt
int sum=0;
for(int i=0;i<[Link];i++)
{
sum=sum+a[i];
}
[Link]("sum of Array elements :" + sum);
// sort array in ascending order.
for(int i=0; i<[Link]; i++)
{
for(int j=i+1;j<[Link];a++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
[Link]("display sorted array");
for(int i=0;i<[Link];i++)
{
[Link]("assending order of array:"+a[i]);
}
}
}
2. Write a java program to create 2 files File1 & File2. Copy the contents of File1 by changing
the case into File2. Also add the additional comment “End of File” at the end of File2.
import [Link].*;
class FileCopyF1F2F3
{
public static void main(String args[]) throws Exception
{
int b;
char ch,ch1;
File f1=new File("[Link]");
File f2=new File("[Link]");
File f3=new File("[Link]");
if (!( [Link]()) ||(!([Link]())))
{
[Link]();
[Link]();
}
FileInputStream fin1=new FileInputStream("[Link]");
FileOutputStream fout2=new FileOutputStream("[Link]");
while((b=[Link]())!=-1)
{
ch=(char)b;
if([Link](ch))
{
if([Link](ch))
ch1=[Link](ch);
else
ch1=[Link](ch);
[Link](ch1);
}
}
[Link]();
[Link]();
FileInputStream fin11=new FileInputStream("[Link]");
FileInputStream fin2=new FileInputStream("[Link]");
FileOutputStream fout3=new FileOutputStream("[Link]");
while((b=[Link]())!=-1)
{
[Link](b);
}
while((b=[Link]())!=-1)
{
[Link](b);
}
[Link]();
FileInputStream fin3=new FileInputStream("[Link]");
while((b=[Link]())!=-1)
{
[Link]((char)b); ;
}
}
}

SLIP7
1. Write a Java Program to create a class Employee with data member as Eid, Ename and
Salary. Store the information of ‘n’ employees and Display the name of employee having
maximum salary (Use array of object).
import [Link].*;
class Employee
{
int id;
string name;
float salary;
void accept()
{
Scanner s= new Scanner([Link]);
[Link]("Enter id: ");
id=[Link]();
[Link]("Enter name :");
name=[Link]();
[Link]("Enter salary:");
salary = [Link]();
void display()
{
[Link]("Id: "+id);
[Link]("Name "+ name);
[Link]("salary: "+ salary);
}
float salary()
{
[Link](salary);
}
static float max(Employee e[],int n)
{
float max=0;
int t=0;
for(int i=0;i<n;i++)
{
if(max <(m[i].salary())
{
max=m[i].salary();
t=i;
}
}
[Link]("max salary:"+max);
return t;
}
}
class EmployeeDemo
{
public static void main( string args[])
{
int n, i,ans;
Scanner s= new Scanner ([Link]);
[Link]("Enter how many records:")
n=[Link]();
Employee e=new Employee[n];
for(i=0;i<n; i++)
{
e[i]=new Employee();
e[i].accept();
}
for(i=0; i<n;i++)
{
e[i].display();
}
ans = [Link](e, n);
e[ans].display();
}
}
2. Cretae a Person(Pid, Pname, Salary) table. Write a menu driven program to perform the
following operations on Person table.
a. Insert
b. Delete all records of employee whose salary is greater than 50000.
c. Display
d. Exit
import [Link].*;
import [Link].*;
class person
{
public static void main(String args[]) throws Exception
{
int pid,sal,k,ch;
ResultSet rs;
String pn,sql;
[Link]("[Link]");
Connection cn=[Link]("jdbc:postgresql://localhost:5432/fybcsd","postgres","");
Statement st=[Link]();
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
do
{
[Link]("[Link] Table");
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]("Enter Ur Choice");
ch=[Link]([Link]());
switch(ch)
{
case 1:
sql="create table person2(pid int,pname text,sal int)";
[Link](sql);
[Link]("Table Is created");
break;

case 2:
[Link]("pid pname Salary");
pid=[Link]([Link]());
pn=[Link]();
sal=[Link]([Link]());
sql="insert into person2 values(" + pid + ",'" + pn +"'," + sal+ ")";
k=[Link](sql);
if(k>0)
[Link]("Record Is Added...!");
break;

case 3:
rs=[Link]("select * from person2");
while([Link]())
{
[Link]([Link](1) + " " + [Link](2) + " " + [Link](3));
}
break;

case 4:
[Link]("pid ");
pid=[Link]([Link]());
sql="delete from person2 where pid="+ pid;
k=[Link](sql);
if(k>0)
[Link]("Record Is Deleteed...!");
break;

case 5:
[Link](0);
}
}
while(ch!=7);
}
}

SLIP 8
1. Write a Java Program to create a class Product with data member as Pid, Pname and Price.
Store the information of ‘n’ products and Display the name of product having maximum
price (Use array of object).
import [Link].*;
class Product
{
int pid;
string pname;
float price;
void accept()
{
Scanner s= new Scanner([Link]);
[Link]("Enter pid: ");
pid=[Link]();
[Link]("Enter name :");
pname=[Link]();
[Link]("Enter salary:");
price=[Link]();
void display()
{
[Link]("Id: "+pid);
[Link]("Name "+ pname);
[Link]("price: "+ price);
}
float price()
{
[Link](price);
}
float max(Product p[],int n)
{
float max=0;
int t=0;
for(int i=0;i<n;i++)
{
if(max <(p[i].price())
{
max=p[i].price();
t=i;
}
}
[Link]("max price:"+max);
return t;
}
}
class EmployeeDemo
{
public static void main( string args[])
{
int n, i,ans;
Scanner s= new Scanner ([Link]);
[Link]("Enter how many records:")
n=[Link]();
Product p=new Product[n];
for(i=0;i<n; i++)
{
p[i]=new Product();
p[i].accept();
}
for(i=0; i<n;i++)
{
p[i].display();
}
ans=[Link](p, n);
p[ans].display();
}
}

2. Write a menu driven program to perform the following operations on Student(Sid, Sname,
Percentage) table.
a. Insert
b. Display a record of student whose sid is “10001”.
c. Display all records of student.
d. Exit
import [Link].*;
import [Link].*;
class student
{
public static void main(String args[]) throws Exception
{
int sid,per,k,ch;
ResultSet rs;
String sname,sql;
[Link]("[Link]");
Connection cn=[Link]("jdbc:postgresql://localhost:5432/fybcsd","postgres","");
Statement st=[Link]();
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
do
{
[Link]("[Link] Table");
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");
[Link]("Enter Ur Choice");
ch=[Link]([Link]());
switch(ch)
{
case 1:
sql="create table student(sid int,sname text,per int)";
[Link](sql);
[Link]("Table Is created");
break;

case 2:
[Link]("sid sname percentage");
sid=[Link]([Link]());
sname=[Link]();
per=[Link]([Link]());
sql="insert into student values(" + sid+ ",'" + sname +"'," + per+ ")";
k=[Link](sql);
if(k>0)
[Link]("Record Is Added...!");
break;

case 3:
rs=[Link]("select * from person2");
while([Link]())
{
[Link]([Link](1) + " " + [Link](2) + " " + [Link](3));
}
break;
case 4:
[Link]("sid For Search");
sid=[Link]([Link]());
rs=[Link]("select * from student where eno="+ sid);
while([Link]())
{
[Link]([Link](1) + " " + [Link](2) + " " + [Link](3));
}
break;

case 5:
[Link](0);
}
}
while(ch!=5);
}
}

SLIP 8

1. Define a class student having Rollno, Name and Percentage. Define Default and
parameterized constructor. Overload the constructor. Accept the 3 student details and
display it. (use this keyword).
import [Link].*;
class Student
{
int rollno;
String name;
Float per;
Student()
{
rollno=0;
name=aa;
per=0;
}
Student(int r,String n,float p)
{
rollno=r;
name=n;
per=p;
}
}
class StudentDemo
{
public static void main(String []args)
{
Student s1=new Student(1,"aaa",60);
Student s2=new Student(2,"bbb",75);
Student s3=new Student(3,"ccc",80);
}
}
2. Create a Hash table containing Employee name and Salary. Display the details of the hash
table. Also search for a specific Employee and display Salary of that Employee.
import [Link].*;
class HashEmp
{
public static void main( string args [])
{
Scanner s = new Scanner([Link]);
Hashtable bt = new Hashtable ();
flow salary;
String name;
[Link]("Enter the no of Employee");
int n=[Link]();
for (int i=0; i<n;i++)
{
[Link]("Enter name of Employee:");
name=[Link]();
[Link]("Enter salary of Employer!');
salary = [Link]();
[Link](name, salary);
}
[Link]("Hash Table="+ ht);
Enumerator k =[Link]();
Enumerater v=[Link]();
[Link]("Enter name to the teached :");
String enum=[Link]();
int cnt=0;
while ([Link]())
{
name = (string) [Link]();
if([Link](name))
{
cnt++;
[Link]("salary:" [Link](na);
}
if (cnt ==0)
[Link]("Employee not found");
}
}

SLIP 9
1. Write a Java program to create class as MyDate with dd,mm,yy as data members. Write
default and parameterized constructor. Display the date in dd-mm-yy format.(Use this
keyword)
import [Link].*;
class MyDate
{
int dd, mm, yy;
MyDate()
{
}
MyDate(int dd, int mm, int yy)
{
[Link]=dd;
[Link]=mm;
[Link]=yy;
}
void display()
{
[Link]("myDade: " + dd + "/ " +mm+"/"+yy);
}
}
class main
{
public static void main(String args[])
{
Scanner S= new Scanner([Link]);
MyDate d=new MyDate(10,05,2022);
[Link]();
}
}
2. Write a java program to accept Person name from the user and check whether it is valid or
not. (It should not contain digits and special symbol) If it is not valid then throw user
defined Exception - Name is Invalid -- otherwise display it
import [Link].*;
class DigitSymbolException extends Exception
{
class Person
{
public static void main(String args[]) throws Exception
{
try
{
int i, len, cnt=0;
BufferedReader b= new BufferedReaded (new InputStreamReader([Link]));
[Link]("Enter Person Name:");
String name=[Link]();
len=[Link]();
for(i=0; i<len; i++)
{
char a=[Link](i);
if ([Link](a) && ! [Link](a) && whitespace(a))
{
cnt++;
throw new DigitSymbolException();
}
}
if (cnt==0)
{
[Link]("Person name:"+name);
}
}
Catch (DigitSymbolException E)
{
[Link]("Exception- -Invalid Name");
}
}
}

SLIP 10

1. Define a class Student with attributes Rollno and Name. Define default and parameterized
constructor. Override the toString() method. Keep the count of Objects created. Create
objects using parameterized constructor and Display the object count after each object is
created.
import [Link].*;
class AgeException extends Exception
{
}
class NameException extends Exception
{
}
class Student
{
int rno,a;
String n,c;
Student(int rollno int age,String name, string course)
{
rno=rollno;
a=age;
n=name;
c=course;
}
try
{
if(a<15 || a>21)
throw new AgeException();
int len=[Link]();
for(int i=0;i<len;i++)
{
char ch=[Link](i);
if ( ! [Link](ch) && ![Link](ch))
throw new NameException();
}
[Link]("Student Name = "+ n);
[Link](" student age=11+a);
[Link](" student roling & course = "+ Eno+c)
}
Catch (AgeException E)
{
[Link]("Exception-Age Not valid ");
}
Catch(NameException E)
{
[Link]("Exception - Name not valid");
}
Class StudentAgeNagm
{
public static void main(string args[])
{
int rollno,age;
string name, course;
Buffered Reader b=new BufferedReader(new InputstreamReader ([Link]));
[Link]("Enter name :");
name = [Link]();
[Link]("Enter age = ");
age=[Link]([Link]());
[Link]("Enter fall no :");
rollno=[Link]([Link]());
[Link]("Enter the course=");
course=[Link]();
Student s=new Student(rollno,age,name,course);
}
}

2. Create a package named “Series” having three different classes to print series:
a. Fibonacci series
b. Cube of numbers
c. Square of numbers
Write a java program to generate “n” terms of the above series. Accpet n from use
package series;
import [Link].*;
public class cube
{
public void cb()
{
int n;
Scanner s= new Scanner([Link]);
[Link]("Enter no:");
n = [Link]();
int ans = n*n*n;
[Link]("Cube="+ans);
}
}//vim cube java
package series;
import [Link].*;
public class fibo
{
public void fb()
{
int n,a=0, b=1,c;
Scanner s = new Scanner([Link]);
[Link]("Enter no:");
n = [Link]();
[Link] in (a);
[Link] in (b);
for(int i=1;i<n; i++)
{
c =a+b;
[Link](c);
a=b;
b=c;
}
}
}// vim [Link]
package series;
import [Link].*;
public class Square
{
public void sq()
{
int n;
Scanner s= new Scanner([Link]);
[Link]("Enter no:");
n = [Link]();
int ans = n*n;
[Link]("square="+ans);
}
}//vim [Link]
import series.*;
class seriespkg
{
public static void main(String args[])
{
Square s=new Square();
[Link]();
Cube c=new Cube();
[Link]();
fibo f=new fibo();
[Link]();
}
}

SLIP 11
1. Define a “Point” class having members – x, y(coordinates). Define default constructor and
parameterized constructors. Define two subclasses “ColorPoint” with member as color and
subclass “Point3D” with member as z (coordinate). Write display method to display the
details of different types of Points
class Point
{
int x,y;
point()
{
x=10;
y=20;
}
Point(int x, int y)
{
this.x=x;
this.y= y;
}
void display()
{
[Link](x);
[Link] (y);
}
class colorpoint extends point
{
String color;
Colorpoint ()
{
color=red;
}
Color Point (int x, int y, string color)
{
Super(x,y);
[Link]= color;
}
void display()
{
[Link]();
[Link](Color);
}
}
}
class Point3D extends Point
{
int z;

Point3D()
{
z=30;
}
paint 3D (int x, int y,int z)
{
Super(x,y);
this.z=z;
}
void display()
{
[Link]();
[Link](z);
}
}
class PointDemo
{
public static void main(String args[])
{
colorpoint c=new Colorpoint(10,20,red);
[Link]();
Point3D d=new Point3D(20,30,40);
[Link]();
}
}

2. Write a program to design and implement following GUI // MENUBAR


import [Link].*;
import [Link].*;
import [Link].*;
class SwingJMenuDemo extends JFrame
{
JMenuBar mb;
JMenu x;
JMenuItem m1, s2,s3,s4 ,s1;
JMenu s;
JMenu h
SwingJMenuDemo()
{
setLayout(null);
setTitle("My Swing Demo");
setSize(400,400);
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
mb = new JMenuBar(); // create a menu bar
x = new JMenu("File"); // create a menu
S=new JMenu("Edit");
h=new JMenu("Help");

m1 = new JMenuItem("New"); // create menuitems


s1= new JMenuItem("Cut");
s2 = new JMenuItem("Copy");
s3=new JMenuItem("Paste");
s4=new JMenuItem("Select All");

[Link](m1); // add menu items to menu


[Link](x); // add menu to menu bar
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);

[Link](S);
[Link](h);

setJMenuBar(mb); // add menubar to frame


}
public static void main(String args[])
{
SwingJMenuDemo b=new SwingJMenuDemo();
}
}

SLIP 12
1. Write a java program that displays the number of characters, lines and words of a file.
import [Link].*;
class FileDemo
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStream fis = new FileInputStream("[Link]");
while([Link]()!=0)
{
code = [Link]();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
[Link]("[Link] characters = "+chars);
[Link]("[Link] words = "+(words+1));
[Link]("[Link] lines = "+(lines+1));
[Link]();
}
catch(FileNotFoundException e)
{
[Link]("Cannot find the specified file...");
}
catch(IOException i)
{
[Link]("Cannot read file...");
}
}

2. Write a Java program to create a super class Employee (members – name, salary). Derive
a sub-class as Developer (member – projectname). Derive a sub-class Programmer
(member – proglanguage) from Developer. Create object of Developer and display the
details of it. Implement this multilevel inheritance with appropriate constructor and
methods

Class Employee
{
String name;
float salary;
Employee (String name, float sulary)
{
this .name name;
this .salary= salary;
}
void display()
{
[Link]("Emp Name: "'+ name);
[Link]("Emp salary: "+ salary);
}
}
class Developer extends Employee
{
string pname;
Developer (string name, float salary, string pname)
{
Super (name, salary);
thispname pname;
}

void display ()
{
Super .display();
[Link]("project name :"+ pname);
}
}
Closs programmer extends Developer.
{
string proglang;
Programmer(string name, float salary, String pnamestring proglang)
{
[Link] = name:
super. salary = salary;
[Link]=pname;
this .proglang = progllanguage;
}
void display()
{
[Link]()
[Link] ("program language:" + proglang);
}
}
class multilevelInheritanceDemo
{
public static void main(string args[])
{
programmer P = new programmes ("aaa",40000,”xyz”,”java”);

[Link]();
}
}
SLIP 13

1. Write a java program to accept a string from the user using command line argument. If it
is a file, display all information about the file (path, size, attributes etc.)
import [Link].*;
class FileInfo
{
public static void main(String args[]) throws Exception
{
File F=new File(args[0]);
if([Link]())
{
[Link]("File Name " + [Link]());
[Link]("File Length " + [Link]());
[Link]("File Path" + [Link]());
[Link]("File Absolute Path " + [Link]());
[Link]("File Parent " + [Link]());
}
else
[Link]([Link]()+ " " + " doesnot Exists");
}
}

2. Construct linked List containing names of colours: red, blue, yellow and orange. Then
extend your program to do the following:
i. Display the contents of the List using an Iterator.
ii. Display the elements of LinkedList in reverse order using ListIterator.
iii. Create another list containing pink and green. Insert the elements of this list between
blue and yellow.

import [Link].*;
dass linkedList Demo
{
public static void main(String args[])
{
List Colcarlist = new linked List ();
[Link]("red");
[Link]("blue");
[Link]("yellow");
colortis).add("orange");

Iterator = colo list. Iterator();


[Link]("Colors List = ");
while([Link]())
[Link]("-next());
}
int n= [Link]();
ListIterator ri= colorlist-ListIterator(n);
[Link]("Reverse colour List:");
while (ri. hasprevious ())
{
[Link](ri-previous ());
}
List colorlist= new linkedlist();
[Link]("pink");
[Link]("green");
Colorlist .addAll(2, colorlists);
[Link]("modified color List:" +colorlist);
}
}

SLIP 14

1. Define a class Number having one integer data member. Write a default constructor
initialize it to 0 and another constructor to initialize it to a value. Write methods
isNegative(), isPositive(). Use command line argument to pass a value to the object and
perform the specified operations.

public class MyNumber {


private int x;
public MyNumber(){
x=0;
}
public MyNumber(int x){
this.x=x;
}
public boolean isNegative(){
if(x<0)
return true;
else return false;
}
public boolean isPositive(){
if(x>0)
return true;
else return false;
}
public boolean isZero(){
if(x==0)
return true;
else return false;
}
public boolean isOdd(){
if(x%2!=0)
return true;
else return false;
}
public boolean isEven(){
if(x%2==0)
return true;
else return false;
}

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


{
int x=[Link](args[0]);
MyNumber m=new MyNumber(x);
if([Link]())
[Link]("Number is Negative");
if([Link]())
[Link]("Number is Positive");
if([Link]())
[Link]("Number is Even");
if([Link]())
[Link]("Number is Odd");
if([Link]())
[Link]("Number is Zero");
}
}
2. Write a program to design following GUI using JTextArea. Write a code to display number
of words and characters of text in JLabel. Use JScrollPane to get scrollbars for JTextArea.

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

public class Test {


public static void main(String[] args)
{
JPanel panel = new JPanel();
[Link](new BoxLayout(panel, BoxLayout.Y_AXIS));
[Link](new JLabel("text"));
[Link](new JLabel("text"));
[Link](new JLabel("text"));

JTextArea textArea = new JTextArea();


[Link](true);
[Link](true);
[Link]("This text fits");
[Link](textArea);

JScrollPane scrollPane =
new JScrollPane(panel, VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER);

JFrame frame = new JFrame("Title");


[Link](WindowConstants.EXIT_ON_CLOSE);
[Link]().add(scrollPane);

[Link]();
[Link](true);
}
}

SLIP 15
1. Define a class Number having one integer data member. Write a default constructor
initialize it to 0 and another constructor to initialize it to a value. Write methods isOdd(),
isEven(). Use command line argument to pass a value to the object and perform the given
operations.
public class MyNumber {
private int x;
public MyNumber(){
x=0;
}
public MyNumber(int x){
this.x=x;
}
public boolean isNegative(){
if(x<0)
return true;
else return false;
}
public boolean isPositive(){
if(x>0)
return true;
else return false;
}
public boolean isZero(){
if(x==0)
return true;
else return false;
}
public boolean isOdd(){
if(x%2!=0)
return true;
else return false;
}
public boolean isEven(){
if(x%2==0)
return true;
else return false;
}

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


{
int x=[Link](args[0]);
MyNumber m=new MyNumber(x);
if([Link]())
[Link]("Number is Negative");
if([Link]())
[Link]("Number is Positive");
if([Link]())
[Link]("Number is Even");
if([Link]())
[Link]("Number is Odd");
if([Link]())
[Link]("Number is Zero");
}
}

2. Write a program to design and implement event handling for following GUI. Verify
username and password in 3 attempts. Display dialog box "Login successful" on success
or display "Username or Password is in correct". After 3 attempts display "Login Failed".
On reset button clear the fields of text box.

SLIP 16
1. Write a java program to accept ‘n’ integers from user and store them in an ArrayList
Collection. Display the elements of ArrayList in reverse order.(Use ListIterator)

import [Link].*;
class array
{
public static void main(String a[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter Limit of ArrayList :");
int n=[Link]();
ArrayList alist=new ArrayList();
[Link]("Enter Elements of ArrayList :");
for(int i=0;i<n;i++)
{
String elmt=[Link]();
[Link](elmt);
}
[Link]("Original ArrayList is :"+alist);
[Link](alist);
[Link]("Reverse of a ArrayList is :"+alist);
}
}
import [Link].*;
class array
{
public static void main(String a[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter Limit of ArrayList :");
int n=[Link]();
ArrayList alist=new ArrayList();
[Link]("Enter Elements of ArrayList :");
for(int i=0;i<n;i++)
{
String elmt=[Link]();
[Link](elmt);
}
[Link]("Original ArrayList is :"+alist);
[Link](alist);
[Link]("Reverse of a ArrayList is :"+alist);
}
}

2. Write a java program to create class Account (accno, accname, balance). Create an array
of “n” Account objects. Define static method “sortAccount” which sorts the array on the
basis of balance. Display account details in sorted order.

import [Link].*;
class Account
{
int accno ;
string accname;
float balance;
Void accept ()
{
Scanner s= new Scanner([Link]);
[Link]("* Enter Account no");
accno=[Link]();
[Link]("Enter Account Name:");
accname = [Link]();
[Link]("Enter Balance:");
balance=[Link]();
}
void display()
{
[Link]("Account No:" + accno);
[Link]("Account Name :"+ accname);
[Link]("Balance"'+ balance);
}
Static void SortAccount (Account a[])
{
for (int i=0; i< a. length; i++)
{
for(int j=i+1;j<[Link]; j++)
{
Account temp;

if (a[i]). balance > a[j].balance)


{
temp = a[i];
a[i[=a[j];
}
}
}
}
}
class Account Demo
{
public static void main (string args [])
{
Scanner s = new scanner ([Link]);
[Link]("HOW many accounts:”);
int n = [Link]();
Account a[] = new Account [n];
for (int i=0; i<n; i++)
{
A[i] = new Account [];
a[i].accept();
}
[Link] In ("Before Sort: ");
for(int i=0; i<n;i++)
{
a[i].display();
}
[Link] (a);
[Link]("After sort :");
for (int i=0; i<n; i++)
{
a[i].display();
}
}
}

SLIP 17

1. Write a program to display information about the ResultSet like number of columns
available in the ResultSet and SQL type of the column. Use Person table. (Use
ResultSetMetaData)

import [Link].*;
class person
{
public static void main(String args[]) throws Exception
{
[Link]("[Link]");
Connection
cn=[Link]("jdbc:postgresql://localhost:5432/fybcsd","postgres","");
Statement st=[Link]();
ResultSet rs=[Link]("select * from emp");
ResultSetMetaData rsmd=[Link]();
[Link]("Total Columns : "+[Link]());
[Link]("Column name of first columns : "+[Link](1));
[Link]("Column Type Name : "+[Link](1));
}
}

[Link] an interface “Operation” which has methods area(),volume(). Define a constant PI


having a value 3.142. Create a class circle (member – radius), cylinder (members – radius,
height) which implements this interface. Calculate and display the area and volume.

interface Operation
{
final float PI = 3.142f;
abstract void area();
abstract vold volume();
}
class circle implements operation
{
float radius;
circle (float r)
{
radius = r;
}
public void area()
{
float aoc;
aoc = pi*radius*radius;
[Link](" Area of circle="'+aoc);
}
public void volume()
{
float voc;
voc= 4/3* PI* radius * radius* radius;
[Link](" volume of circle = "+ voc);
}
Class Cylinder implements operation
{
float radius,height;
Cylinder (float r, float h);
{
radius=r;
height=h;
}
public void area()
{
float area;

area = 2* PI* radius*height +2 PI * radius * radius;


[Link]("area of cylinder = "'+ area);
}
public void volume U
{
float volume;
volume = PI *radius * radius * height;
[Link]("volume of cylindes="+ volume);
}
class Interfacefloss
{
public static void main(String args(1)
{
Circle c1 = [Link] (2.200);

[Link]();
c1. Volume();

Cylinder c2=new cylinder (2.5f,2.7f)


[Link]();
[Link]();
}
}
SLIP 18
1. Write a Java program to display information about database (Use DatabaseMetaData)

import [Link].*;
class person
{
public static void main(String args[]) throws Exception
{
[Link]("[Link]");
Connection
cn=[Link]("jdbc:postgresql://localhost:5432/fybcsd","postgres","");
Statement st=[Link]();
DatabaseMetaData dbmd=[Link]();
[Link]("Driver Name : "+[Link]());
[Link]("Driver Version : "+[Link]());
[Link]("User Name : "+[Link]());
[Link]("DB Product Name : "+[Link]());
}
}

2. Define a class Employee having members – id, name, salary. Define default constructor.
Create a subclass called Manager with private member bonus. Define methods accept and
display in both the classes. Create “n” objects of the Manager class and display the details
of the worker having the maximum total salary (salary + bonus).
Import [Link].*;
Class Employee
{
Int id;
string name;
float salary;
Employee (int eid, stating ename, float salary)
{
Id=eid;
name= ename;
Salary = esalary;
}
void accept ()
{
Scanner s=new Scanner([Link]);
[Link]("Enter id: ");
id=[Link]();
[Link]("Enter name:"");
name=[Link]();
[Link]("Enter salary: ");
salary = [Link]();
}
void display()
{
[Link]("did: "+id);
[Link]("Name :"+ name);
[Link]("salary: "+ salary);
}

float salary()
{
[Link](salary);
}
Class Manager extends Employee
{
private float bonus;
void accept ()
{
Super. Accept()
Scanner s=new scanner([Link]);
[Link]("Enter a bonus:");
bonus = [Link] Float();
void display()
{
super, display [Link]("Bonus is: "'+ bonus);
static float max (manager m[], int n)
float max=0;
int t=0;
for (int i=0;i<n; i++)
{
if(max < (m[i].salary() + m[i] .bonus))
{
max = m[i].salary + m[i].bonus;
t=i;
[Link]("max sulary:" +
return t;
}
}
class EmployeeDemo
{
public static void main( string args[])
{
int n, i,ans;
Scanner s = new Scanner ([Link]);
[Link]("Enter how many records:");
[Link]();
Manager m[] = new Manager [n];
for (i=0; i<n; i++)
{
m[i]=new manager();
m[i]-accept();
}
for(i=0; i<n;i++);
{
m[i]. display();
}
[Link] (m, n);
m[ans]. display();
}
} SLIP 19
1. Accept n integers from the user and store them in a collection. Display them in the sorted
order. The collection should not accept duplicate elements. (Use a suitable collection).
Search for a particular element using predefined search method in the Collection
framework.
import [Link].*;
import [Link].*;
class sortedNumbers
{
public static void main(string args[]) throws Exception
{
BufferedReader b= new BufferedReader(new InputStreamReader([Link]));
set s=new Treeset();
[Link]("Enter no of integers: ");
Int n= [Link]([Link]();
For(int i=0; in; itt).
{
[Link]("Enter Number :");
int x = [Link]([Link] Line ());
[Link](x);
}
Iterator i = [Link]();
while ([Link]()).
{
[Link]("[Link]());
}
[Link]("Enter element to be sorted:");
int no = [Link](b,read Line ());
if([Link](no))
{
[Link]("Number "+no + "found");
}
else
{
[Link]("Number "+no+ "not found ");
}
}
2. Define an abstract class Staff with members name and address. Define two sub-classes of
this class – FullTimeStaff (members - department, salary, hra - 8% of salary, da – 5% of
salary) and PartTimeStaff (members - number-of-hours, rate-per-hour). Define appropriate
constructors. Write abstract method as calculateSalary() in Staff class. Implement this
method in subclasses. Create n objects which could be of either FullTimeStaff or
PartTimeStaff class by asking the user‘s choice. Display details of all FullTimeStaff objects
and all PartTimeStaff objects along with their salary.
import [Link].*;
abstract class Staff
{
String name,address;
Abstract void calculatesalary();
}
class FullTimeStaff extends Staff
{
String department;
double salary;
FullTimeStaff(String name,string address,string department,double salary)
{
[Link]=name;
[Link]=address;
[Link]=department;
[Link]=salary;
}
public void display()
{
[Link]("Name: "+name);
[Link]("Address: "+address);
[Link]("Department: "+department);
[Link]("Salary: "+salary);
[Link](“HRA=”+salary*0.08 );
[Link](“DA=”+salary*0.05);
}
Void calculatesalary()
{
double sal=salary+(salary*0.08)+(salary*0.05);
[Link](“total salary=”+sal);
}
}
class PartTimeStaff extends Staff
{
int noofdays;
float rate;
PartTimeStaff(String name,String address,int noofdays,float rate)
{
[Link]=name;
[Link]=address;
[Link]=noofdays;
[Link]=rate;
}
public void display()
{
[Link]("Name: "+name);
[Link]("Address: "+address);
[Link]("No of days: "+noofdays);
[Link]("Rate per hour: "+rate);

}
Void calculatesalary()
{
float sa=noofdays*rate;
[Link](“total sarary=”+sal);
}
}
public class emp
{
public static void main(String [] args) throws IOException
{
int i,ch=0,n=0,noofdays;
String name,address,department;
float salary,rate;
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
do
{
[Link]("Select Any One: ");
[Link]("[Link] Time Staff");
[Link]("[Link] Time Satff");
[Link]("[Link] ");
[Link]("enter ur choice: ");
int ch=[Link]([Link]());
switch(ch)
{
case 1:
[Link]("Enter the number of Full Time Staff: ");
int n=[Link]([Link]());
FullTimeStaff f[]=new FullTimeStaff[n];
for(i=0;i<n;i++)
{
f[i]=new FullTimeStaff();
f[i].accept();
}
for(i=0;i<n;i++){
l[i].display();
}
break;
case 2:
[Link]("Enter the number of Part Time Staff: ");
int m=[Link]([Link]());
PartTimeStaff [] h=new PartTimeStaff[m];
for(i=0;i<m;i++){
h[i]=new PartTimeStaff();
h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
}
break;

}
}
}

Common questions

Powered by AI

In the "EmployeeDemo" program, employee information is stored using an array of Employee objects, where each object contains fields for employee ID, name, and salary. Users input data via the accept method for each object in the array, and a display method is used to output these details. This structure allows for efficient management of multiple records, as arrays enable quick indexing and iteration over collections of objects. It also facilitates operations such as finding an employee with the maximum salary, which can be done in a single traversal. This object-oriented approach enhances code modularity and reusability, making it scalable and maintainable .

The program initializes a LinkedList with predefined color names and uses an Iterator to traverse and display the list. To display in reverse order, a ListIterator is used with reverse traversal capabilities. The program also demonstrates insertion by introducing a new color list and adding its elements between existing list elements ('blue' and 'yellow'), using the addAll method at the appropriate index. Key considerations include understanding list traversal using iterators for both forward and backward navigation and effectively managing list modifications through correct indexing and the inherent dynamic resizing nature of linked lists. These actions underline the nuances of LinkedList manipulation, emphasizing flexibility and dynamic data management in Java .

A menu-driven program offers an organized interface for users to perform various database operations systematically. It allows users to select operations such as creating tables, inserting records, updating data, and displaying results through a repeated menu prompt and user choices. This approach, as exemplified in the source code, provides a clear, structured means to interact with databases without overwhelming users with commands. Advantages include ease of use, improved user interaction, reduced risk of errors, and scalability for complex operations, acting as a bridge between complex database operations and user-friendly interfaces .

The "MyNumber" class uses a default constructor to initialize its integer member to zero and another parameterized constructor to set it to a specific value from a command line argument. Methods like `isNegative`, `isPositive`, `isZero`, `isOdd`, and `isEven` evaluate the integer state, returning corresponding boolean values. Command line interaction integrates these methods into a program flow where the user-supplied integer is evaluated across multiple dimensions of state (numeric sign and parity). This design effectively employs constructors for initialization flexibility and demonstrates method-driven encapsulation of state assessment in Java .

The "SwingJMenuDemo" program demonstrates the creation of a graphical user interface using Java's Swing components, specifically the JMenuBar, JMenu, and JMenuItem classes. It initializes a JFrame with a JMenuBar, adds JMenus to serve as categories (File, Edit, Help), and populates each menu with JMenuItems like New, Cut, Copy, Paste, and Select All. This setup is meant to mimic the standard menu found in many desktop applications, offering a familiar interface for users to select commands or options. The program's use of layout managers and event handling methods showcases how Java Swing can be employed to design interactive and responsive GUIs .

The "FileDemo" program employs a FileInputStream to read a given text file byte-by-byte. It counts characters by incrementing a `chars` counter for every byte read, words by monitoring spaces (`code == 32`), and lines by detecting end-of-line markers (`code == 13` or newline characters). The program finally reports the counts after file traversal, providing an analysis of file content. This demonstrates basic file processing techniques in Java, showcasing how structured loops and conditional logic can handle file metrics efficiently .

The "SwingComboEventDemo" class showcases Java Swing's capability to handle user events using JComboBox and JTextField components. It sets up a simple graphical user interface with a JComboBox containing programming language options (PHP, DotNet, Java, CPP) and a JTextField. When a user selects an item from the JComboBox, the ItemListener method captures the event and updates the JTextField to display the selected item. This demonstrates real-time interaction and the responsiveness of Swing components in Java, making it an effective tool for developing dynamic applications that respond to user input .

The multi-level inheritance design involves three classes: Employee, Developer, and Programmer, where Developer extends Employee, and Programmer extends Developer. This hierarchy models real-world scenarios where a programmer is a specialized type of developer, who in turn is a type of employee. Constructors in each class initialize relevant attributes, showing explicit use of the 'super' keyword to invoke the parent's constructor for initializing fields from the parent class. Display methods in each subclass invoke the parent class's method, demonstrating overridden methods while retaining core behaviors. This implementation showcases the power of inheritance to reduce repetition, enforce hierarchy, and leverage polymorphic behaviors in Java .

The program utilizes Java's FileInputStream and FileOutputStream classes to manage file input and output operations. It reads data byte-by-byte from 'F1.txt' using a FileInputStream, checks each character to determine if it is a letter, and toggles its case using Character class methods. Converted content is then written to 'F2.txt' with a FileOutputStream. Additionally, the program ensures 'End of File' is appended to the end of 'F2.txt' by adding this string after completing the main writing process. Such operations emphasize Java's capabilities for manipulating file streams and handling text transformation efficiently .

The "Ascending.java" program first calculates the sum of array elements by iterating through the integer array using a for-loop. Each element is added to an accumulator variable. For sorting, a basic selection sort algorithm is used, where the program iterates over the elements, comparing each pair and swapping them to order all elements in ascending order. The program demonstrates basic array handling operations, where sorting organizes data for better usability, and summation provides analytical insights into the dataset's characteristics .

You might also like