1. A Project Report
in
JAVA PROGRAMMING AND SQL
For
………………………. Examination
[As a part of the
……………………………………….]
SUBMITTED BY:
…………………………
Under the Guidance of:
……………………….
3. CERTIFICATE
This is to certify that the Project / Dissertation entitled Programming in JAVA
and SQL is a bonafide work done by …………………………………… in
partial fulfillment of ……………………………………. and has been carried
out under my direct supervision and guidance. This report or a similar report on the
topic has not been submitted for any other examination and does not form a part of
any other course undergone by the candidate.
………………………… ……………………………..
Signature of Students Signature of Teacher/Guide
Name:………………… Name:
………………….
Designation:
……………..
Place:…………….
5. ACKNOWLEDGEMENT
undertook this Project work, as the part of my
………………….course.We had tried to apply my best of
knowledge and experience, gained during the study and class
work experience. However, developing software system is generally a quite complex
and time-consuming process. It requires a systematic study, insight vision and
professional approach during the design and development. Moreover, the developer
always feels the need, the help and good wishes of the people near you, who have
considerable experience and idea.
We
we would like to extend my sincere thanks and gratitude to my teacher
………………… We am very much thankful to our Principal
………………….. for giving valuable time and moral support to develop this
software.
we would like to take the opportunity to extend my sincere thanks and gratitude to
our parents for being a source of inspiration and providing time and freedom to
develop this software project.
We also feel indebted to my friends for the valuable suggestions during the project
work.
6. INDEX
S.NO DESCRIPTIONS SIGNATURE
1 Design a java program to print the table of the entered number?
2 Design a java program to print the Fibonacci series of the entered number?
3 Design a java program to display the scored goal details and match result?
4 Design a java program to add the Digits in input area?
5 Design a java program to change background colour of different input controls?
6 Design a java program to select the character from the list as given in
textfield?
7 Design a java program to print the numbers in between the given input?
8 Design a java program to check a string is palindrome or not?
9 Design a java program to reverse a string?
10 Design a java program to find the occurrence of a character?
11 Design a java program to find the position of a vowel in a string?
12 Design a java program to display a menu of Ice-cream parlor?
13 Ms. Fauzia works as a programmer in “TelTel Mobile Company” where she has
designed a software to compute charges to be paid by the mobile phone user
14 Ms. Angela works as a programmer in a Bus Tour Company named “Heritage
Experiences”. Groups of people come and reserve seats.
15 Vijay has developed software for planning personal budget. Total Income, Expenses of
Bills (Water/Electricity), Groceries, Entertainment, other expenses and whether money is
to be sent to Hostel are entered by the user. Sum of expenses, Grand Total of Expenses
and Savings are calculated
16 RED Public School has computerized its student performance system.
17 ABC Sales Enterprise wants developed a software to make the bill for their customer
18 Common wealth International is a bank. The bank provides three types of loans
Car Loan, House Loan, education Loan. The following is the Interest rate and discount
calculation form.
19 Mr. Krrishnav is working with railways and he has to design an application which can
calculate the total fare.
20 Program to display colour of the background by selecting the button given on the jframe
in java.
21 Program to display the colour by selecting the jRadioButton from a Java Jframe.
22 Program to select the male female option from the jRadioButton and print the
appropriate message
23 Write a Java program that accepts three numbers and prints "All numbers are equal" if all
three numbers are equal, "All numbers are different" if all three numbers are different
and "Neither all are equal or different" otherwise.
24 Write a Java program to display Pascal's triangle
25 Write a Java program that takes a year from user and print whether that year is a leap
year or not.
26 Write a program in Java to display the multiplication table of a given integer
27 Write a Java program to find the common elements between two arrays (string values).
28 Write a Java program to find the second largest element in an array
29 Write a Java program to convert all the characters in a string to uppercase
30 Write a Java method to check whether a string is a valid password.
SQL
7. JAVA PROGRAMMING
Q1.Design a java program to print the table of the entered number?
Source Code-
Code for Table
private void jButton1ActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
int x= Integer.parseInt(AT.getText());
inty,z=0;
for(y=1;y<=10;++y) {
z=y*x;
RT.append(z+"n"); } }
Code for Clear
private void clearActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
AT.setText(" ");
RT.setText(" "); }
8. Q2.Design a java program to print the Fibonacci series of the entered number?
Source Code-
Code for Fibonacci
private void jButton2ActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
int s1=0,s2=1,sum,n;
n=Integer.parseInt(AT.getText());
if(n==0)
RT.append(0+"n");
else
if(n==1)
RT.append(0+"n"+1+"n");
else {
RT.append(0+"n"+1+"n");
RT.append("");
for(inti=2; i<=n; i++) {
sum=s1+s2;
RT.append(sum+"n");
RT.append(" ");
s1=s2;
s2=sum; } } }
Code for Clear
private void clearActionPerformed (java.awt.event.ActionEventevt) {
// TODO add your handling code here:
AT.setText("");
RT.setText("");}
9. Q3.Design a java program to display the scored goal details and match result?
Source Code-
Code for Scored By A
private void GOAActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
intga= Integer.parseInt(tAGoals.getText());
ga=ga+1;
tAGoals.setText(""+ga); }
Code for Scored By B
private void GOBActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
intgb= Integer.parseInt(tBGoals.getText());
gb=gb+1;
tBGoals.setText(""+gb); }
Code for Declare Match
private void DCActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
intga=Integer.parseInt(tAGoals.getText());
intgb=Integer.parseInt(tBGoals.getText());
String res=(ga>gb?"Team A wins":(ga<gb)?"Team B wins":"Draw");
result.setText(res); }
Code for Clear
private void CLEARActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
result.setText(" ");
tBGoals.setText("0");
tAGoals.setText("0"); }
10. Q4. Design a java program to add the Digits in input area?
Code of main method
int addDigits(int n)
{int s=0;
int dig;
while(n>0){
dig=n%10;
s=s+dig;
n=n/10;
}return s;
}
private void ComputeActionPerformed(java.awt.event.ActionEvent evt) {
int num=Integer.parseInt(input.getText());
int sum=addDigits(num);
out.setText("Sum of its digits is "+sum);
}
11. Q5. Design a java program to change background colour of different input controls ?
Code for the jList (Event –ListSelection-valueChanged)-
private void ColValueChanged(javax.swing.event.ListSelectionEventevt) {
// TODO add your handling code here:
Int i;
Color x=Color.WHITE;
i=Col.getSelectedIndex();
switch(i){
case 0: x=Color.RED;
break;
case 1: x=Color.BLUE;
break;
case 2: x=Color.GREEN;
break;
case 3: x=Color.MAGENTA;
break;
case 4: x=Color.CYAN;
break;
case 5: x=Color.YELLOW;
break;
case 6: x=Color.GRAY;
break;
}
if(LBL1.isSelected())
Lb.setBackground(x);
else
Lb.setBackground(Color.WHITE);
if(LBL2.isSelected())
Btn.setBackground(x);
else
Btn.setBackground(Color.WHITE);
if(LBL3.isSelected())
TF.setBackground(x);
else
TF.setBackground(Color.WHITE);
12. Q6. Design a java program to select the character from the list as given in textfield?
Code of Select in List Buttonprivate
void oKActionPerformed(java.awt.event.ActionEventevt) {
// TODO add your handling code here:
List.setSelectedValue(ENTER.getText(), true);
}
13. Q7.Design a java program to print the numbers in between the given input?
Ans.
Code of Count Button
private void CountActionPerformed(java.awt.event.ActionEvent evt) {
int a=Integer.parseInt(IN1.getText());
int b=Integer.parseInt(IN2.getText());
if(a>b){
for(;b<=a;b++)
{OUT.append(b+" ");}
}
else{
for(;a<=b;a++)
{ OUT.append(a+" ");}
}
14. Q8. Design a java program to check a string is palindrome or not?
Code of Perform Palindrome Test Button-
private void PalandromActionPerformed(java.awt.event.ActionEvent evt) {
String str=In.getText();
showPalindrome(str);
}
Main method Code
Public void showPalindrome(String s){
StringBuffer out=new StringBuffer(s);
if(isPalindrome(s))
s=s+": is a palindrome!";
else if(isPalindrome2(s))
s=s+ ": is a palindrome if you ignore case";
else
s=s+": is not a palinidrome! ";
Out.setText(s);
}
public boolean isPalindrome(String s)
{
StringBuffer reversed=(new StringBuffer(s)).reverse();
return equalsIgnoreCase(reversed.toString());
}
publicboolean isPalindrome2(String s)
{
StringBuffer reversed=(new StringBuffer(s)).reverse();
return equalsIgnoreCase(reversed.toString());
}
15. Q9. Design a java program to reverse a string?
Code of Reverse Button-
private void ReverseActionPerformed(java.awt.event.ActionEventevt) {
String a=IN.getText();
String b="";
for(int i=a.length()-1;i>=0;i--){
b=b+a.charAt(i);
}OUT.setText(b);
}
16. Q10. Design a java program to find the occurrence of a character?
Code of Count Button-
private void CountActionPerformed(java.awt.event.ActionEvent evt) {
String a=In1.getText();
char b=In2.getText().charAt(0);
int c=0;
for(int d=0;d<a.length();d++){
if(a.charAt(d)==b)
c++;
}
Out.setText (""+c);
}
17. Q11. Design a java program to find the position of a vowel in a string?
Code of OK Button-
private void OKActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String a=IN.getText();
for(int d=0;d<=a.length();d++){
char c=a.charAt(d);
switch(c){
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
d=d+1;
OUT.append(" "+d+"n");
break;
default: } }
}
18. Q12. Design a java program to display a menu of Ice-cream parlor?
Code of Calculate Buttonif(
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int sum=Integer.parseInt(jLabel4.getText())+Integer.parseInt(jLabel5.getText())+Integer.parseInt(jLabel6.getText());
jLabel7.setText(String.valueOf(sum)); }
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(this.jCheckBox1.isSelected()==true)
{ jLabel1.setText("40");
jLabel4.setText(String.valueOf(Integer.parseInt(jLabel1.getText())*Integer.parseInt(jTextField1.getText())));
}else
{ jLabel1.setText(" ");
jTextField1.setText("0");
jLabel4.setText(" ");
} }
private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(this.jCheckBox2.isSelected()==true)
{ jLabel2.setText("50");
jLabel5.setText(String.valueOf(Integer.parseInt(jLabel2.getText())*Integer.parseInt(jTextField2.getText())));
}else {
jLabel2.setText(" ");
jTextField2.setText("0");
jLabel5.setText(" ");
20. Q13. Ms. Fauzia works as a programmer in “TelTel Mobile Company” where she has designed a
software to compute charges to be paid by the mobile phone user. A screenshot of the same is
shown below:
Each Call is charged at Rs.1.00 .
Each SMS is charged at Rs. 0.50.
Users can also opt for Mobile Data Plan. Charges for Mobile Data Plan are flatRs.50.00.
Help Ms. Fauzia in writing the code to do the following:
When the ‘Calculate Charges’ button is clicked, ‘Calls and SMS Charges’, ‘Mobile Data Plan Charges’ and ‘Amount to Pay’
should be calculated and displayed in the respective text fields.
‘Amount to Pay’ is calculated as: Calls and SMS Charges + Mobile Data Plan Charges(if any)
private void CalculateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int Calls, Sms;
double Total,dataAmt = 0, grandTot, callsChg ,smsChg;
Calls = Integer.parseInt(jTextField3.getText());
Sms = Integer.parseInt(jTextField4.getText());
callsChg = Calls * 1.00 ;
smsChg = Sms * 0.5 ;
Total = callsChg + smsChg;//Total=(Calls*1.00)+(Sms*0.5);
if (jCheckBox1.isSelected())
dataAmt = 50.00;
grandTot = Total + dataAmt;
jTextField5.setText(“”+ Total);
jTextField6.setText(“”+dataAmt);
jTextField7.setText(“”+grandTot);
}
When ‘Clear’ button is clicked, all the textfields and checkbox should be
cleared.
private void clearActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText(“”);jTextField2.setText(“”);jTextField3.setText(“”);jTextField4.setText(“”);jTextField5.setText(“”);jTex
tField6.setText(“”);jTextField7.setText(“”);jCheckBox1.setSelected(false);
}
When the ‘Exit’ button is clicked, the application should close.
private void CloseActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
21. Q14. Ms. Angela works as a programmer in a Bus Tour Company named “Heritage Experiences”.
Groups of people come and reserve seats. There are 3 stopovers for the bus. First stop is at Alwar,
second at Jaipur, third at Udaipur. A group may choose any one destination out of Alwar, Jaipur
and
Udaipur. Angela has designed a software to compute charges to be paid by the entire group. A
screenshot of the same is shown below:
A group can opt for one destination out of Alwar/ Jaipur/ Udaipur.
If the group is “Frequent Traveller Group”, the group gets a 10% discount on Total charges.
Help Ms. Angela in writing the code to do the following:
After selecting appropriate Radio Button and checkbox (if required), when ‘Calculate Charges’
button is clicked, ‘ Total Charges’ , ‘ Discount Amount’ , ‘ Amount to Pay’ should be
calculated and displayed in the respective text fields. The Charges per person for various
destinations are as follows:
Destination Amount(in Rs.)
Alwar 200.00 per person
Jaipur 500.00 per person
Udaipur 900.00 per person
‘Total Charges’ is obtained by multiplying ‘ Number of People in Group’ with
Amount per person .
If ‘ Frequent Traveller Group ’ checkbox is selected, ‘ Discount Amount’ is
calculated as 10% of ‘ Total Charges’ . Otherwise ‘ Discount Amount ’ is 0.
‘ Amount to Pay’ is calculated as :
Amount to Pay = Total Charges – Discount Amount.
private void calculateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Double Total = 0;
if (jRadioButton1.isSelected())
Total= 200* Integer.parseInt(jTextField2.getText());
else if (jRadioButton2.isSelected())
Total= 500* Integer.parseInt(jTextField2.getText());
else if (jRadioButton3.isSelected())
Total= 900* Integer.parseInt(jTextField2.getText());
jTextField3.setText("" + Total);
22. double Disc, Net;
if(jCheckBox1.isSelected())
Disc = 0.10* Integer.parseInt(jTextField3.getText());
else
Disc = 0.0;
jTextField4.setText(" "+Disc);
Net = Total-Disc;
jTextField5.setText(" "+net);
}
When ‘CLEAR’ button is clicked, all the textfields, radio button and checkbox should be cleared.
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jCheckBox1.setSelected(false);
jRadioButton1.setSelected(false);
jRadioButton2.setSelected(false);
jRadioButton3.setSelected(false);
}
When ‘EXIT’ button is clicked, the application should close.
private void CloseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
23. Q15.Vijay has developed a software for planning personal budget. A screenshot of the same is
shown below:
Total Income, Expenses of Bills (Water/Electricity), Groceries,Entertainment, other expenses and
whether money is to be sent to Hostel are entered by the user. Sum of Expenses, Grand Total of
Expenses and Savings are calculated and displayed by the program.
Write the code to do the following :
i. When ‘CALCULATE’ button is clicked, Sum of Expenses, Total Expenses and Savings should be
calculated and displayed in appropriate text fields.
● Sum of Expenses is calculated by adding expenses on Bills(Water/Electricity), Groceries,
Entertainment and other expenses.
● Grand Total of Expenses is calculated according to the following criteria:
If ‘Money to be sent to Hostel’ checkbox is selected, 3000.00 is to be added to the sum of
expenses. If it is not selected, Grand Total of Expenses is the same as sum of expenses.
● Savings = Total Income – Grand Total of Expenses.
private void CalculateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Calculation of Sum of Expenses
jTextField6.setText("" +Integer.parseInt(jTextField2.getText()+Integer.parseInt(jTextField3.getText()+
Integer.parseInt(jTextField4.getText()+Integer.parseInt(jTextField5.getText());
//Calculation of Grand Total of Expenses
if(jCheckBox1.isSelected())
jTextField7.setText("" + 3000 +Integer.parseInt(jTextField6.getText()));
else
jTextField7.setText("" +Integer.parseInt(jTextField6.getText()));
// Calculation of Savings
jTextField8.setText(“” +Integer.parseInt(jTextField1.getText())+ Integer.parseInt(jTextField7.getText()));
}
When ‘CLEAR’ button is clicked, all text fields and checkbox should be cleared.
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
25. Q16. RED Public School has computerized its student performance system. The following
is the data entry form in java used:
Object Type Object Name Description
Frame jFrame The Frame Object
Command
Button
cmdCalculate To calculate the total, percentage and grade
cmdClear To clear all the textfields
cmdQuit To quit from application
Radio
Button
jRB1 To select medical System
jRB2 To select Non-Medical System
Text Fields jTextField1 To accept name
jTextField2 To accept class
jTextField3 To accept Sub1
jTextField4 To accept Sub2
jTextField5 To accept Sub3
jTextField6 To accept Sub4
jTextField7 To accept Sub5
jTextField8 To display total
jTextField9 To display percentage
jTextField10 To display grade
On clicking the calculate button: Total marks should be calculated as sum of all the
Five subjects and percentage and grade. To calculate the grade:
For Medical Students
Percentage Grade
>=85 A1
>=60 and <85 A2
<60 B1
For Non-Medical Students
26. Percentage Grade
>=80 A1
>=60 and <80 A2
<60 B1
private void cmdCalculate ActionPerformed(java.awt.event.ActionEvent evt) {
double total=0.0, perc = 0.0;
String grade;
double m1=Double.parseDouble(jTextField3.getText());
double m2=Double.parseDouble(jTextField4.getText());
double m3=Double.parseDouble(jTextField5.getText());
double m4=Double.parseDouble(jTextField6.getText());
double m5=Double.parseDouble(jTextField7.getText());
total=m1+m2+m3+m4+m5;
perc=total/5;
if ( jRB1.isSelected() )
{
if ( perc >=85 )
grade = “A1”;
if ( perc >= 60 )
grade = “A2”;
if ( perc < 60 )
grade = “B1”;
}
else if ( jRB2.isSelected() )
{
if ( perc >=80 )
grade = “A1”;
if ( perc >= 60 )
grade = “A2”;
if ( perc < 60 )
grade = “B1”;
}
jTextField8.setText( “ “ + total );
jTextField9.setText( “ “ + perc );
jTextField10.setText( grade ); }
On clicking the Clear Button, the contents of all the textfields should be cleared.
private void cmdClear ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText ( null );
jTextField2.setText ( null );
jTextField3.setText ( null );
jTextField4.setText ( null );
jTextField5.setText ( null );
jTextField6.setText ( null );
jTextField7.setText ( null );
jTextField8.setText ( null );
jTextField9.setText ( null );
jTextField10.setText ( null );
}
On clicking the Exit Button will close the application.
private void cmdQuit ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0); }
27. Q17. ABC Sales Enterprise wants developed a software to make the bill for their
customer. GUI for the application given below
Write the java statement for the following requirements.
a) Write the statement to make the text fields (txtDiscount) and txtNet non-editable.
txtDiscount.setEnabled(false);
txtNet.setEnabled(false);
b) Calculate discount and net amount for calculate button based on the following
criteria.
Sales Amount Discount
>=5000 5
>=3000 3
>=1000 1
private void CALActionPerformed(java.awt.event.ActionEvent evt) {
long sales=Long.parseLong(txtsales.getText());
int dis;
long netamt;
if(sales>=1000)
dis=1;
netamt=sales-(sales*1)/100;
else if(sales>=3000)
dis=3;
netamt=sales-(sales*3)/100;
else
29. Q18. Common wealth International is a bank. The bank provides three types of loans
Car Loan, House Loan, education Loan. The following is the Interest rate and discount calculation
form.The list of controls for the above form is as follows:
Write the command for clear button to clear all the text boxes and set car loan as default loan type.
Write the command for Show Interest Amount button to show the Interest rate txtRate according to
the following criteria.
Car Loan ----10%
House Loan ------8.5%
Education Loan -------5%
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double loan=0;
if(jRadioButton1.isSelected()==true)
{
loan=Double.parseDouble(jTextField1.getText());
loan=(loan*10)/100;
jTextField2.setText(String.valueOf(loan));
}
if(jRadioButton2.isSelected()==true)
{
loan=Double.parseDouble(jTextField1.getText());
loan=(loan*8.5)/100;
jTextField2.setText(String.valueOf(loan));
}
if(jRadioButton3.isSelected()==true)
{
loan=Double.parseDouble(jTextField1.getText());
loan=(loan*5)/100;
jTextField2.setText(String.valueOf(loan));
}
}
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
30. // TODO add your handling code here:
jRadioButton2.setSelected(false);
jRadioButton3.setSelected(false);
}
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jRadioButton1.setSelected(false);
jRadioButton3.setSelected(false);
}
private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jRadioButton2.setSelected(false);
jRadioButton1.setSelected(false);
}
(c). Write the command for calculate Discount Button to find discount on loan amount and amount
after discount. Notice that the bank provides discount on loan amount according to following criteria.
If amount <=10,00,000 then 0.20% discount.
If amount >10,00,000 then 0.25% discount.
The discount amount = interest Amount –discount amount.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double dis=0.00;
double discount=0.00;
if(Double.parseDouble(jTextField1.getText())>1000000)
{
discount=(Double.parseDouble(jTextField1.getText())*0.20)/100;
dis=Double.parseDouble(jTextField2.getText())-discount;
jTextField3.setText(String.valueOf(dis));
}else
{
discount=(Double.parseDouble(jTextField1.getText())*0.25)/100;
dis=Double.parseDouble(jTextField2.getText())-discount;
jTextField3.setText(String.valueOf(dis));
}
}
31. Q19.Mr. Krrishnav is working with railways and he has to design an application
which can calculate the total fare. The following is the Fare Calculator along with
details: (Use only defaults name for the controls i.e. Swing Components)
a. Write the code for exit button so that when a user clicks on exit button Application will be
closed. Also display a message “Thank you for your nice visit” before exiting the application.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JOptionPane.showMessageDialog(null, "Thank you for your nice visit", "TITLE",
JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
b.Write a code to calculate the total fare according to the given conditions:
i)The type of coach is selected by the user from the jList1 and the charges are for
1 tier coach Rs. 2000 per person , 2 tier coach Rs 1500 per person and for 3 tier
coach 1000 per person.
ii) If the person is travelling in AC coach then increase the fare by 20%.
iii)If the person is senior citizen the fare will be reduced by 50%.
iv)The total fare will be number of passenger travelling multiply by fare calculated per seat.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
long fare=0;
if(jList1.isSelectedIndex(0))
{
fare=2000;
}else if(jList1.isSelectedIndex(1))
{
fare=1500;
}else if(jList1.isSelectedIndex(2))
{
33. Q20. Program to display colour of the background by selecting the button given on the jframe in java.
public class ButtonDemo extends Frame implements ActionListener
{
Button rb, gb, bb; // three Button reference variables
public ButtonDemo() // constructor to set the properties to a button
{
FlowLayout fl = new FlowLayout(); // set the layout to frame
setLayout(fl);
rb = new Button("Red"); // convert reference variables into objects
gb = new Button("Green");
bb = new Button("Blue");
rb.addActionListener(this); // link the Java button with the ActionListener
gb.addActionListener(this);
bb.addActionListener(this);
add(rb); // add each Java button to the frame
add(gb);
add(bb);
setTitle("Button in Action");
setSize(300, 350); // frame size, width x height
setVisible(true); // to make frame visible on monitor, default is setVisible(false)
}
// override the only abstract method of ActionListener interface
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand(); // to know which Java button user clicked
System.out.println("You clicked " + str + " button"); // just beginner's interest
if(str.equals("Red"))
{
setBackground(Color.red);
} else if(str.equals("Green"))
{
setBackground(Color.green);
} else if(str.equals("Blue"))
{
setBackground(Color.blue);
} }
public static void main(String args[])
{
new ButtonDemo(); // anonymous object of ButtonDemo just to call the constructor
} // as all the code is in the constructor
}
34. Q21. Program to display the colour by selecting the jRadioButton from a Java Jframe.
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class JRadioButtonTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JRadioButton Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton button1 = new JRadioButton("Red");
JRadioButton button2 = new JRadioButton("Green");
JRadioButton button3 = new JRadioButton("Blue");
ButtonGroup colorButtonGroup = new ButtonGroup();
colorButtonGroup.add(button1);
colorButtonGroup.add(button2);
colorButtonGroup.add(button3);
button1.setSelected(true);
frame.add(new JLabel("Color:"));
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.pack();
frame.setVisible(true);
}
}
35. Q22.Program to select the male female option from the jRadioButton and print the appropriate message.
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
36. 23. Write a Java program that accepts three numbers and prints "All numbers are equal" if all
three numbers are equal, "All numbers are different" if all three numbers are different and
"Neither all are equal or different" otherwise.
public class NewJFrame extends javax.swing.JFrame {
int x = Integer.parseInt(jTextField1.getText());
int y = Integer.parseInt(jTextField2.getText());
int z = Integer.parseInt(jTextField3.getText());
if (x == y && x == z)
{
jLabel1.setText("All numbers are equal");
}
else if ((x == y) || (x == z) || (z == y))
{
jLabel1.setText ("Neither all are equal or different");
}
else
{
jLabel1.setText ("All numbers are different");
}
}
}
Sample Output:
Input first number: 2564
Input second number: 3526
Input third number: 2456
All numbers are different
37. Q24. Write a Java program to display Pascal's triangle.
Test Data
Input number of rows: 5
Expected Output :
Input number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
import java.util.Scanner;
public class Exercise22 {
public static void main(String[] args)
{
int no_row,c=1,blk,i,j;
System.out.print("Input number of rows: ");
Scanner in = new Scanner(System.in);
no_row = in.nextInt();
for(i=0;i<no_row;i++)
{
for(blk=1;blk<=no_row-i;blk++)
System.out.print(" ");
for(j=0;j<=i;j++)
{
if (j==0||i==0)
c=1;
else
c=c*(i-j+1)/j;
System.out.print(" "+c);
}
System.out.print("n");
}
}
}
38. Q25. Write a Java program that takes a year from user and print whether that year is a leap
year or not.
public class NewJFrame extends javax.swing.JFrame {
int year = Integer.parseInt(jTextField1.getText());
boolean x = (year % 4) == 0;
boolean y = (year % 100) != 0;
boolean z = ((year % 100 == 0) && (year % 400 == 0));
if (x && (y || z))
{
jLabel1.setText(year + " is a leap year");
}
else
{
jLabel1.setText (year + " is not a leap year");
}
}
}
Test Data
Input the year: 2016
Expected Output :
2016 is a leap year
39. Q26. Write a program in Java to display the multiplication table of a given integer.
import java.util.Scanner;
public class Exercise14 {
public static void main(String[] args)
{
int j,n;
System.out.print("Input the number(Table to be calculated): ");
{
System.out.print("Input number of terms : ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println ("n");
for(j=0;j<=n;j++)
System.out.println(n+" X "+j+" = " +n*j);
}
}
}
Copy
Sample Output:
Input the number(Table to be calculated): Input number of terms : 5
5 X 0 = 0
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
40. Q27. Write a Java program to find the common elements between two arrays (string values).
import java.util.*;
public class Exercise14 {
public static void main(String[] args)
{
String[] array1 = {"Python", "JAVA", "PHP", "C#", "C++", "SQL"};
String[] array2 = {"MySQL", "SQL", "SQLite", "Oracle", "PostgreSQL", "DB2", "JAVA"};
System.out.println("Array1 : "+Arrays.toString(array1));
System.out.println("Array2 : "+Arrays.toString(array2));
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < array1.length; i++)
{
for (int j = 0; j < array2.length; j++)
{
if(array1[i].equals(array2[j]))
{
set.add(array1[i]);
}
}
}System.out.println("Common element : "+(set)); //OUTPUT : [THREE, FOUR, FIVE]
}}Copy
Sample Output:
Array1 : [Python, JAVA, PHP, C#, C++, SQL]
Array2 : [MySQL, SQL, SQLite, Oracle, PostgreSQL, DB2, JAVA]
Common element is : [JAVA, SQL]
41. Q28. Write a Java program to find the second largest element in an array.
import java.util.Arrays;
public class Exercise17 {
public static void main(String[] args) {
int[] my_array = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};
int max = my_array[0];
int second_max = my_array[0];
System.out.println("Original numeric array : "+Arrays.toString(my_array));
for (int i = 0; i < my_array.length; i++) {
if (my_array[i] > max) {
second_max = max;
max = my_array[i];
} else if (my_array[i] > second_max) {
second_max = my_array[i];
}
}
System.out.println("Second largest number is : " + second_max);
}
}
Sample Output:
Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254,
1472, 2365, 1456, 2165, 1457, 2456]
Second largest number is : 2456
42. Q29. Write a Java program to convert all the characters in a string to uppercase.
public class NewJFrame extends javax.swing.JFrame {
String str = jTextField1.getText();
// Convert the above string to all uppercase.
String upper_str = str.toUpperCase();
// Display the two strings for comparison.
jLabel2.setText("String in uppercase: " + upper_str);
}
}
Sample Output:
Original String: The Quick BroWn FoX!
String in uppercase: THE QUICK BROWN FOX!
43. Q30. Write a Java method to check whether a string is a valid password.
Password rules:
A password must have at least ten characters.
A password consists of only letters and digits.
A password must contain at least two digits.
public class NewJFrame extends javax.swing.JFrame {
/*1. A password must have at least eight characters.n" +
"2. A password consists of only letters and digits.n" +
"3. A password must contain at least two digits n" +
"Input a password (You are agreeing to the above Terms and Conditions*/
String s = jTextField1.getText();
if (is_Valid_Password(s)) {
jLabel2.setText("Password is valid: " + s);
} else {
jLabel2.setText("Not a valid password: " + s);
} }
public static boolean is_Valid_Password(String password) {
if (password.length() < PASSWORD_LENGTH) return false;
int charCount = 0;
int numCount = 0;
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if (is_Numeric(ch)) numCount++;
else if (is_Letter(ch)) charCount++;
else return false;
}
return (charCount >= 2 && numCount >= 2);
}
public static boolean is_Letter(char ch) {
ch = Character.toUpperCase(ch);
return (ch >= 'A' && ch <= 'Z');
}
public static boolean is_Numeric(char ch) {
return (ch >= '0' && ch <= '9');
}}
Output:
1. A password must have at least eight characters.
2. A password consists of only letters and digits.
3. A password must contain at least two digits
Input a password (You are agreeing to the above Terms and Conditions.):
abcd1234
Password is valid: abcd1234
44. SQL
Write SQL commands for (i) to (viii) on the basis of relations given below:
BOOKS
book_id Book_name author_name Publishers Price Type qty
k0001 Let us C Sanjay mukharjee EPB 450 Computers 15
p0001 Genuine J. Mukhi FIRST PUBL. 755 Fiction 24
m0001 Mastering c Kanetkar EPB 165 Computers 60
n0002 Vcplusplus advance P. Purohit TDH 250 Computers 45
k0002 Near to heart Sanjeev FIRST PUBL. 350 Fiction 30
i. To show the books of FIRST PUBL Publishers written by P.Purohit.
SELECT * FROM BOOKS WHERE PUBLISHERS=”FIRST PUBL.” AND AUTHOR_NAME=”P.PUROHIT”
ii. To display cost of all the books written for FIRST PUBL.
SELECT SUM(PRICE) FROM BOOKS WHERE PUBLISHERS=”FIRST PUBL.”
iii.Depreciate the price of all books of EPB publishers by 5%.
UPDATE BOOKS SET PRICE=PRICE-(PRICE*.5) WHERE PUBLISHERS=”EPB”
iv.To display the BOOK_NAME,price of the books whose QUANTITY more than 50copies.
SELECT BOOK_NAME,PRICE FROM BOOKS WHERE QTY>=3
v.To show total cost of books of each type.
SELECT TYPE,SUM(PRICE) FROM BOOKS GROUP BY TYPE
vi.To show the detail of the most cost is more 400.
SELECT * FROM BOOKS WHERE PRICE>400
45. Consider the following tables Employee and salary. Write SQL commands for the statements (i) to (iv) and give outputs
for SQL queries (v) to viii
Table : Employee
Eid Name Deptid Qualification Sex
1 Deepali Gupta 101 MCA F
2 Rajat Tyagi 101 BCA M
3 Hari Mohan 102 B.A M
4 Harry 102 M.A M
5 Sumit Mittal 103 B.Tech M
6 Jyoti 101 M.Tech F
Table : Salary
Eid Basic DA HRA Bonus
1 6000 2000 2300 200
2 2000 300 300 30
3 1000 300 300 40
4 1500 390 490 30
5 8000 900 900 80
6 10000 300 490 89
(i) To display the frequency of employees department wise.
SELECT COUNT(*) FROM EMPLOYEE GROUP BY DEPTID
(ii) To list the names of those employees only whose name starts with ‘H’
SELECT NAME FROM EMPLOYEE WHERE NAME LIKE 'H%'
(iii) To add a new column in salary table . The column name is total_sal.
ALTER TABLE SALARY
ADD(TOTAL_SAL NUMBER(15))
(iv) To store the corresponding values in the total_sal column.
UPDATE SALARY SET TOTAL_SUM=BASIC+DA+HRA+BONUS
(v) Select name from employee where eid=(select eid from salary where basic= (select max(basic) from salary));
JYOTI
(vi) select max(basic) from salary where bonus >40;
10000
(vii) Select count(*) from employee group by sex;
4
2
(viii) select Distinct deptid from Employee;
3
46. Consider the following tables Hospital.Write SQL commands for the statements (i) to (vi) and give outputs for SQL
queries (vii)
Table: Hospital
No. Name Age Department Dateofadm Charges Sex
1 Sandeep 65 Surgery 23/02/98 300 M
2 Ravina 24 Orthopedic 20/01/98 200 F
3 Karan 45 Orthopedic 19/02/98 200 M
4 Tarun 12 Surgery 01/01/98 300 M
5 Zubin 36 ENT 12/01/98 250 M
6 Ketaki 16 ENT 24/02/98 300 F
7 Leena 29 Cardiology 20/02/98 800 F
8 Zareen 45 Gynecology 22/02/98 300 F
9 Kush 19 Cardiology 13/01/98 800 M
10 Shailya 31 Medicine 19/02/98 400 F
i. To show all information about the patients of cardiology department.
SELECT * FROM HOSPITAL WHERE DEPARTMENT=”CARDIOLOGY”
ii. To list the names of female patients who are in orthopedic department.
SELECT NAME FROM HOSPITAL WHERE SEX=”F” AND DEPARTMENT=”ORTHOPEDIC”
iii. To list names of all patients with their date of admission in ascending order.
SELECT NAME FROM HOSPITAL ORDER BY DATEOFADM
iv. To display patient’s Name, Charges, AGE for only male patients only.
SELECT NAME,CHARGES,AGE FROM HOSPITAL WHERE SEX=”M”
v. To count the number of patients with Age greater than 30.
SELECT COUNT(*) FROM HOSPITAL WHERE AGE>30
vi. To insert a new row in the Hospital table with the following data:
11, ‘ Nipan ‘, 26 , ‘ENT’, ‘25/02/98’, 50, ‘ M ‘
INSERT INTO HOSPITAL VALUES(11, ‘ Nipan ‘, 26 , ‘ENT’, ‘25/02/98’, 50, ‘ M ‘)
vii. Give the output of following SQL statements:
a). Select COUNT(distinct Department) from Hospital;
SURGERY
ENT
CARDIOLOGY
MEDICINE
ORTHOPEDIC
b). Select MAX(Age) from Hospital where Sex = ‘M’;
65
c). Select AVG(Charges) from Hospital where Sex = ‘ F ‘;
400
d). Select SUM(Charges) from Hospital where Dateofadm < ‘2/08/98’;
1550
47. Given the following LAB table, write SQL command for the questions (i) to (iii) and give the output of (iv).
LAB
No ItemName CostPerItem Quantity Dateofpurchase Warranty Operational
1 Computer 60000 9 21/5/96 2 7
2 Printer 15000 3 21/5/97 4 2
3 Scanner 18000 1 29/8/98 3 1
4 Camera 21000 2 13/10/96 1 1
5 Switch 8000 13 01/10/99 2 1
6 UPS 5000 5 21/5/96 1 4
7 Router 25000 2 11/01/00 2 5
(i) To select the ItemName,which are within the Warranty period till present date.
SELECT ITEMNAME FROM LAB WHERE WARRANTY=(DATEOFPURCHASE-SYSDATE)
(ii) To display all the itemName whose name starts with ‘C’.
SELECT ITEMNAME FROM LAB WHERE ITEMNAME LIKE 'C%'
(iii)To list the ItemName in ascending order of the date of purchase where quantity is more than 3.
SELECT ITEMNAME FROM LAB WHERE QUANTITY>3 ORDER BY DATEOFPURCHASE
(iv) Give the output of the following SQL commands:
(a) select min(DISTINCT Quantity) from LAB;
1
(b) select max(Warranty) from LAB;
4
(c) select sum(CostPerItem) from Lab;
152000