Class12 ProggAssign Answers Notes
Class12 ProggAssign Answers Notes
com Page 1 of 66
Create a Form to do the following:
1. Input a string in a text box and print its length in another text field.
2. Input a string and print it in reverse order in another text box.
3. Input a string and print a message whether it’s a palindrome string or not. A palindrome string is a string
that reads same from start and end e.g. nitin
4. Input a string and print total number of vowels in it. Also count the total of individual vowels.
5. Input a string and convert it to uppercase and lowercase.
6. Input two strings in two text boxes and concat them and display the concated string in a third text box.
7. Input two strings in two text boxes and print whether they are same :
a. Ignoring case
b. Case sensitive
8. Input a string and print :
a. First three characters
b. Last two characters
c. Two middle characters
9. Input a number and check whether it’s an even number or an odd number.
10. Input a number and print its table upto 10.
11. Input a number and reverse it and display it in another text box.
12. Input a number and count how many digits it contains.
13. Input a number and print sum of its individual digits.
14. Input a start value and an end value and display all the digits in between those two values.
15. Input a number and display whether it’s a prime number or not.
16. Input a number and display its sign i.e. positive, negative or zero.
17. Input a number and check whether it’s an armstrong number. Armstrong numbers are those three digit
numbers whose sum of cube of individual digits is the number itself.
18. Input a number and print that number of prime numbers .
19. Create a button which when clicked will display all the armstrong numbers.
20. Input 3 numbers and print maximum of these three numbers.
21. Input a number and print its factorial.
22. The fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1,1. every
subsequent value is the sum of the two values preceding it. Create a form that will display this series.
23. Compute the following series:
a. 1+1/2+1/3+…..+1/n
b. 1+1/2+1/22+1/23+…….+1/2n
24. Input marks of 5 subjects and print its total, average and grade. Grade is based on the following rules:
Average Grade
>=90 S
>=80 and <90 A
>=70 and <80 B
>=60 and <70 C
>=50 and <60 D
>=40 and <50 E
<40 F
25. A bank pays 12% interest on a fixed deposit for 6 months or more. Input the deposited amount and the
period for which the amount is deposited . Display the interest and total amount in two text boxes.
26. Input a number between 1-7 and display dayname as 1-Monday, 2- Tuesday….Also check for invalid
value entered.
27. Input a number between 1-12 and display monthname as 1-January, 2- February….Also check for invalid
value entered.
28. Input a number and print all the even numbers and odd numbers till that number.
29. Input a year and display if it is a leap year or not.
30. Write a program which will keep on asking for a number until user enters -999 and then will display the
sum and count of those numbers.
31. Write a program to print the following series:
1 1 *
12 22 **
123 333 ***
1234 4444 ****
12345 55555 *****
List Box class 12 [email protected] Page 2 of 66
b. To add the values that you type in a text box into the List box or say to add the values
in the List Box at runtime do the following:
i. Select the List Box.
ii. From its Properties dialog box, click on the ellipsis next to ‘model.
iii. A model window will appear.
iv. Click on the drop down box displayed at the top of the model window and
select Custom code.
v. In the new window a text box will appear. There type the model name as
‘modLstCity. (It can be any name you want)
vi. Now click on the source tab.
vii. At the topmost line and just before the class definition begins add the line :
import javax.swing.*;
viii. At the bottom of the source window just above the ‘variable declaration code’
type the following :
1. DefaultListModel modLstCity=new DefaultListModel();
ix. Now on the button click event, type the following code:
1. modLstCity.addElement(txt1.getText());
c. To display the index number of the selected item in the list box do the following:
i. Select the List Box.
ii. From the shortcut menu select Events -> ListSelection > valueChanged and
type the following code there:
1. JOptionPane.showMessageDialog(null,jList1.getSelectedIndex());
d. To display the selected item in the list box in another text box do the following:
i. Select the List Box.
ii. From the shortcut menu select Events -> ListSelection _> valueChanged and
type the following code there:
1. txt2.setText(“”+jList1.getSelectedValue());
g. To copy a selected item of a list box to another list box on clicking a button:
i. Create a new list box. Name is jList2
ii. Create its model as described above as ‘modLstCity2’
iii. Add its DefaultListModel code in source window as explained above.
iv. Create a button ‘copy element’ and add the following code:
modLstCity2.addElement(jList1.getSelectedValue());
h. To insert an item before the selected item in a list box do the following:
i. Add elements in the list box.
ii. Create a button ‘Insert element’ and add the following code:
int pos=jList1.getSelectedIndex();
String s=txt1.getText();
modLstCity.insertElementAt(s, pos);
Combo Box class 12 [email protected] Page 4 of 66
b. To add the values that you type in a text box into the Combo box or say to add the
values in the Combo Box at runtime do the following:
i. Select the Combo Box.
ii. From its Properties dialog box, click on the ellipsis next to ‘model.
iii. A model window will appear.
iv. Click on the drop down box displayed at the top of the model window and
select Custom code.
v. In the new window a text box will appear. There type the model name as
‘modCmbState. (It can be any name you want)
vi. Now click on the source tab.
vii. At the topmost line and just before the class definition begins add the line :
import javax.swing.*;
viii. At the bottom of the source window just above the ‘variable declaration code’
type the following :
1. DefaultComboBoxModel modCmbState=new DefaultComboBoxModel();
ix. Add a button ‘Add’ and type the following code :
1. modCmbState.addElement(txt1.getText());
c. To display the index number of the selected item in the combo box do the following:
i. Add items in the Combo Box.
ii. Select the Combo Box.
iii. From the shortcut menu select Events -> Items > itemStateChanged and type
the following code there:
1. JOptionPane.showMessageDialog(null,jCombo1.getSelectedIndex());
d. To display the selected item in the combo box in another text box do the following:
i. Select the Combo Box.
ii. From the shortcut menu select Events -> Items > itemStateChanged and type
the following code there:
1. txt2.setText(""+jCombo1.getSelectedItem());
String s=txt2.getText();
jCombo1.setSelectedItem(s);
g. To copy a selected item of a combo box to another combo box on clicking a button:
i. Create a new combo box. Name is jCombo2
ii. Create its model as described above as ‘modCmbState2’
iii. Add its DefaultComboModel code in source window as explained above.
iv. Create a button ‘copy element’ and add the following code:
modCmbState2.addElement(jCombo1.getSelectedItem());
h. To insert an item before the selected item in a combo box do the following:
i. Add elements in the combo box.
ii. Create a button ‘Insert element’ and add the following code:
int pos=jCombo1.getSelectedIndex();
String s=txt1.getText();
modCmbState.insertElementAt(s, pos);
Check Box class 12 [email protected] Page 6 of 66
Check Boxes : it returns only two values; true or false i.e. selected or not selected.
if(chkPhy.isSelected()==true)
ta.append(chkPhy.getText()+" ");
if(chkBio.isSelected()==true)
ta.append(chkBio.getText()+" ");
4. To set all the check boxes value to false or unselect them all, do the following:
a. Add a button titled ‘Unselect All’
b. Add the following code to the
button:
chkInf.setSelected(false);
chkPhy.setSelected(false);
chkBio.setSelected(false);
txt1.setText("");
c.
On Clicking Unselect All
button
Radio Buttons class 12 [email protected] Page 7 of 66
Radio Buttons/Option Buttons: In radiobutton we can have the only one decision. But checkbox we can
have mulitiple options. Based on the usage we choose these controls.
for example,
RadioButton
-----------
Gender - ⃝ Male ⃝ Female here we can select only one option
CheckBox
--------
your Interested Games?
⃞ cricket ⃞ football ⃞ valleyball ⃞ hockey here you may have more than option.
1. To add a group of radio buttons to ask for stream selected, Science, Commerce or Arts.
a. Add three radio buttons on to the form.
b. Change their names to opSc, opCom and opArts, by selecting ‘Change Variable
Name’ option from the shortcut menu.
c. Change their displayed text to Science, Commerce and Arts by selecting ‘Edit Text’
option from the shortcut menu.
d. Now to have only one radio button selected out of these three do the following:
i. From the palette drag component namely ‘Button Group’ on the form. This
component will not be visible on the form but it will be visible in the inspector
window under ‘Other Components’ heading’. The default name will be
‘buttonGroup1’. Select this name , and from the shortcut menu select ‘Change
variable name’ option and change the name to grStream.
ii. Now in the form, select all the three buttons together and open Properties
dialog box from the shortcut menu.
iii. Click the drop down next to buttonGroup option and select grStream from the
dropdown and close the window.
iv. You will see that all the three buttons are now
connected together
v. These steps will ensure that only one of these
radio buttons is selected or you can say that
these three buttons belong to a group namely ‘grStream’.
2. To display value of the radio button which can be either true or false or say selected or not
selected do the following:
a. Select the radio button ‘opSc’
b. From the shortcut menu, select Events -> Action -> actionPerformed and add the
following code:
boolean s=opSc.isSelected();
String caption=opSc.getText();
txt1.setText(caption + " is "+ s);
c. Do (a) and (b) steps for other two radio buttons namely opCom and opArts and in the
code just change opSc to opCom and opArts respectively.
3. To set all the radio buttons to false or unselected state, do the following:
a. Add a button with title “Unselect”.
b. Add the code : grStream.clearSelection(); // name of the buttonGroup
Radio Buttons class 12 [email protected] Page 8 of 66
4. Now, add three ‘Panel’ container on the form. Add a border around each panel. Name them
as panSc, panCom and panArts and add different labels in each panel as shown below:
6. Next step is, when we click ‘opSc’ option button, ‘panSc’ should be visible and when we click
‘opCom’ option button, ‘panCom’ should be visible and when we click ‘opArts’ option button,
‘panArts’ should be visible.
7. Select ‘opSc’ button and from the shortcut menu select Events -> Action -> actionPerformed
and add the following code:
panSc.setVisible(true);
panCom.setVisible(false);
panArts.setVisible(false);
8. Select ‘opCom’ button and from the shortcut menu select Events -> Action ->
actionPerformed and add the following code:
panSc.setVisible(false);
panCom.setVisible(true);
panArts.setVisible(false);
9. Select ‘opArts’ button and from the shortcut menu select Events -> Action ->
actionPerformed and add the following code:
panSc.setVisible(false);
panCom.setVisible(false);
panArts.setVisible(true);
10.
Classes & Objects class 12 [email protected] Page 9 of 66
Class : this is a template from which you can create objects. The definition of class includes the formal
specifications for the class and any data and method in it.
Object: this is an instance of a class much as a variable is an instance of a data type. We can think of a class as
the type of an object. Objects encapsulates methods and instance variables.
Data members: those variables that are part of a class. We use them to store the data the object uses. Objects
supports both ‘instance variables’ whose values are specific to the object and ‘class/static variables’ whose
values are shared among the objects of a specified class.
Methods/Functions: this is a function built into a class or object. We have instance and class methods. We can
use instance methods with objects and class methods just by referring to the class name, no object is required.
{
// class definition
The keyword ‘static’ turns variable into a class variable and a methods into a class method.
The ‘access’ term specifies the accessibility of the class or a class method or a class variable to bthe rest of the
program and it can be public, private or protected.
Instance and Class variables: instance variables are specific to the objects. If you have 2 objects(i.e. two
instances of a class), the instance variables in each object are independent of the instance variables in other
object
On the other hand, class variables of both the objects will refer to the same data and therefore will hgold the
same value.
public class A {
int a; // instance variable
static int b; //class variable
Now create a jFrame form and add a button in the form. Add the following code behind the button.
Object a1 Object a2
Static variable
a a
b
In the above example, instance variable ‘a’ is different for both the objects. Thus changes made to ‘a’ by the
object a1 is not reflected in object a2.
In the above example, the class variable ‘b’ is same for both the objects or say both the objects share the
same class variable ‘b’. thus changes made to ‘b’ by object a1 is reflected in object a2.
About variables:
About Methods:
Õ An instance method can ONLY be accessed by an instance of a class. It cannot be accessed by the
class directly.
Õ A static method can be accessed by an instance of a class as well as the class itself.
*** A user defined class ‘MyMath’ with various mathematical functions created by the user. Note that all functions
are declared to be static and thus they can be directly qualified with the class name i.e. you can call fact function
as MyMath.fact(23)
while(n>0){
c=c+1;
n=n/10;
}
return c;
}
while(n>0){
temp=(temp*10)+(n%10);
n=n/10;
}
return temp;
}
while(n>0){
sum=sum+(n%10);
n=n/10;
}
return sum;
}
while(n>0){
long i=n%10;
sum=sum+cubedigit(i);
n/=10;
}
return sum;
}
MyMath class XII [email protected] Page 12 of 66
for(long i=2;i<=n/2;i++){
if(n%i==0){
tf=false;
break;
}
}
return tf;
}
} // end class
Assignment Answers class XII [email protected] Page 13 of 66
1.
2.
String nws="";
for(int i=n-1;i>=0;--i){
nws=nws+s.charAt(i);
}
3.
for(int i=n-1;i>=0;--i){
nws=nws+s.charAt(i);
}
if(s.equalsIgnoreCase(nws)==true)
return true;
else
return false;
}
Assignment Answers class XII [email protected] Page 14 of 66
4.
int vow=0;
int a=0;int e=0; int i=0; int o=0; int u=0;
int c=0;
while(c<s.length()){
if(isVowel(s.charAt(c))==true){
++vow;
a=s.charAt(c)=='A'?++a:a;
e=s.charAt(c)=='E'?++e:e;
i=s.charAt(c)=='I'?++i:i;
o=s.charAt(c)=='O'?++o:o;
u=s.charAt(c)=='U'?++u:u;
}
c++;
}
ta.append("Total Vowels : "+ vow + "\n");
ta.append("Total 'a' : " + a + "\n");
ta.append("Total 'e' : " + e + "\n");
ta.append("Total 'i' : " + i + "\n");
ta.append("Total 'o' : " + o + "\n");
ta.append("Total 'u' : " + u + "\n");
}
5.
s=s.toUpperCase();
t2.setText(s);
}
s=s.toLowerCase();
t2.setText(s);
}
Assignment Answers class XII [email protected] Page 15 of 66
6.
7.
String s2=t2.getText();
boolean same;
if(s1.equals(""+s2))
same=true;
else
same=false;
String s2=t2.getText();
boolean same;
if(s1.equalsIgnoreCase(s2))
same=true;
else
same=false;
8.
private void jButton1ActionPerformed(java.awt.event.ActionEvent
evt) {
String str=t1.getText();
int s=Integer.parseInt(t2.getText());
int e=Integer.parseInt(t3.getText());
String str2=str.substring(s,e);
t4.setText(str2);
}
The following forms assumes that you have created ‘MyMath’ class as was told. These forms will use the static
methods defined in MyMath class.
9.
if(MyMath.evenodd(n))
s="It's an Even Number";
else
s="It's an Odd Number";
res.setText(s);
}
10.
for(int i=1;i<=10;i++){
s=""+n +" x " + i + " = "+ n*i;
ta.append(s + "\n");
}
}
Assignment Answers class XII [email protected] Page 17 of 66
14.
private void btnPrntSeriesActionPerformed(java.awt.event.ActionEvent evt) {
String s1=t1.getText();
String s2=t2.getText();
long n1=0;long n2=0;
try{
n1=Long.parseLong(s1);
n2=Long.parseLong(s2);
}catch(Exception e){
JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value");
t1.requestFocus();
return;
}
if(n1>n2){
long t=n1;
n1=n2;
n2=t;
}
s1="";
Assignment Answers class XII [email protected] Page 18 of 66
for (long i=n1;i<=n2;i++)
s1=s1+i+" ";
lbl1.setText(s1);
}
15.
lbl1.setText(s1);
}
16.
lbl1.setText(s1);
}
Assignment Answers class XII [email protected] Page 19 of 66
17.
if(n==MyMath.sumofcube(n)){
ta.append(""+n+"\n");
}
}
}
Assignment Answers class XII [email protected] Page 20 of 66
20. private void btnMaxActionPerformed(java.awt.event.ActionEvent evt) {
String s1=t1.getText();
String s2=t2.getText();
String s3=t3.getText();
int n1=0;int n2=0;int n3=0;
try{
n1=Integer.parseInt(s1);
n2=Integer.parseInt(s2);
n3=Integer.parseInt(s3);
}catch(Exception e){
JOptionPane.showMessageDialog(this,"Enter a Valid Integer
Value");
t1.requestFocus();
return;
}
int max=MyMath.findmax(n1, n2, n3);
t4.setText("The Maximum Vaslue is : "+ max);
int n1=0;
try{
n1=Integer.parseInt(s1);
}catch(Exception e){
JOptionPane.showMessageDialog(this,"Enter a Valid Integer
Value");
t1.requestFocus();
return;
}
int fact=MyMath.fact(n1);
t4.setText("The Factorial : "+ fact);
for(int i=1;i<=n-2;++i){
n3=n1+n2;
s=s+n3+" ";
n1=n2;
n2=n3;
}
t4.setText(s);
}
Assignment Answers class XII [email protected] Page 21 of 66
float sum=1;
float n=0;
try{
n=Float.parseFloat(s1);
}catch(Exception e){
JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value");
t1.requestFocus();
return;
}
for(float i=2;i<=n;i++){
sum=sum+1/i;
}
24.
e=Integer.parseInt(t1.getText());
p=Integer.parseInt(t2.getText());
c=Integer.parseInt(t3.getText());
m=Integer.parseInt(t4.getText());
i=Integer.parseInt(t5.getText());
t=e+p+c+m+i;
per=t/500.0 * 100;
gr=grade(per);
t6.setText(""+t);
t7.setText(""+per +"%");
t8.setText(""+gr);
if(p>=90) g="S";
else if(p>=80) g="A";
else if(p>=70) g="B";
else if(p>=60) g="C";
else if(p>=50) g="D";
else if(p>=40) g="E";
else g="Fail";
return g;
}
double intamt=0.0;
double tamt=0;
t3.setEditable(false);
t4.setEditable(false);
if(time>6){
intamt=dep*(12.0/100);
}
tamt=dep+intamt;
t3.setText(""+intamt);
t4.setText(""+tamt);
}
26.
try{
d=Integer.parseInt(t1.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(this,"Enter a Valid value..");
t1.requestFocus();
return;
}
if(d<1||d>7){
JOptionPane.showMessageDialog(this,"Enter value between 1-7");
t1.requestFocus();
return;
}
switch(d){
case 1:day="Monday";break;
case 2:day="Tuesday";break;
case 3:day="Wednesday";break;
case 4:day="Thursday";break;
case 5:day="Friday";break;
case 6:day="Saturday";break;
case 7:day="Sunday";break;
}
t2.setText("It is "+day);
}
27. Do Yourself…..Same as 26
Assignment Answers class XII [email protected] Page 23 of 66
28. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int nums=1;
30.
while (true){
String s=JOptionPane.showInputDialog("Enter a Number : (-999 to STOP ) ");
n=Integer.parseInt(s);
if(n==-999){
break;
}
else{
ta.append(s + "\n");
sum=sum+n;
++count;
}
}
JOptionPane.showMessageDialog(this, "Total Numbers :"+count + " Sum = "+ sum);
}
Assignment Answers class XII [email protected] Page 24 of 66
31. Enter a sentence in a text box and apply title case on it i.e. first letter of every word should be
capitalized.
int l=s.length();
int i=0;
s2=""+s.charAt(0);
s2=s2.toUpperCase();
nws=nws+s2;
++i;
while(i<=l-1){
while(true){
c=s.charAt(i);
if(c==32){
++i;
flag=true;
nws=nws+c;
continue;
}else{
s2=""+s.charAt(i);
break;
}
if(flag){
s2=s2.toUpperCase();
flag=false;
}
nws=nws+s2;
++i;
t2.setText(nws);
}
Assignment Answers class XII [email protected] Page 25 of 66
32. Type a text in a text box and apply Toggle case on it i.e. uppercase should be converted to
lowercase and vice versa.
int n;
int l=s.length();
int i=0;
while(i<=l-1){
char c=s.charAt(i);
n=c;
if(c>=97 && c<=122){
n=n-32;
c=(char)n;
}
else if(c>=65 && c<=90){
n=n+32;
c=(char)n;
}
nws=nws+c;
++i;
t2.setText(nws);
}
String nws="";
nws=str.replaceAll(search, repl);
t3.setText(nws);
}
Now convert him with her AND his with her yourself
Assignment Answers class XII [email protected] Page 26 of 66
33. The following GUI program illustrates various ‘Color’ concepts. Before creating this form , do
the following:
Õ write the code at the topmost line : import java.awt.Color ;
Õ add a listbox and name it ‘lstColor’ and in model property type : RED, GREEN, BLUE, BLACK and
YELLOW.
Õ add a combbox and name it ‘cmbColor’ and in model property type : RED, GREEN, BLUE, PINK and
ORANGE.
Õ Add 4 radio buttons and name them opRed, opGreen, opBlue and OPBlack and change their text
properties to RED. GREEN, BLUE and BLACK respectively. Assign the ButtonGroup property of these
buttons as ‘buttonGroup1’
Õ Add a label and name it as ‘lbl1’. Also ‘check’ its ‘Opaque’ property to true.
private void
lstColorValueChanged(javax.swing.event.ListSelectionEve
nt evt) {
String s=""+lstColor.getSelectedValue();
int i=lstColor.getSelectedIndex();
Color c= Color.white;
if(i==0) c=Color.RED;
if(i==1) c=Color.GREEN;
if(i==2) c=Color.BLUE;
if(i==3) c=Color.BLACK;
if(i==4) c=Color.YELLOW;
lbl1.setText(s);
lbl1.setBackground(c);
}
if(i==0) c=Color.RED;
if(i==1) c=Color.GREEN;
if(i==2) c=Color.BLUE;
if(i==3) c=Color.PINK;
if(i==4) c=Color.ORANGE;
lbl1.setText(s);
lbl1.setBackground(c);
}
Color c= Color.red;
lbl1.setText(s);
lbl1.setBackground(c);
}
Assignment Answers class XII [email protected] Page 27 of 66
Color c= Color.green;
lbl1.setText(s);
lbl1.setBackground(c);
}
Color c= Color.blue;
lbl1.setText(s);
lbl1.setBackground(c);
}
Color c= Color.black;
lbl1.setText(s);
lbl1.setBackground(c);
}
if(chkBold.isSelected())
txt1.setFont(new Font(fontname,Font.BOLD,fontsize));
if(chkItalic.isSelected())
txt1.setFont(new Font(fontname,Font.ITALIC,fontsize));
if(chkPlain.isSelected())
txt1.setFont(new Font(fontname,Font.PLAIN,fontsize));
}
Assignment Answers class XII [email protected] Page 29 of 66
After CUT
After PASTE
After COPY
After PASTE
35. Enter a sentence in a text box and apply title case on it i.e. first letter of every word should be
capitalized.
int l=s.length();
int i=0;
s2=""+s.charAt(0);
s2=s2.toUpperCase();
nws=nws+s2;
++i;
while(i<=l-1){
while(true){
c=s.charAt(i);
if(c==32){
++i;
flag=true;
nws=nws+c;
continue;
}else{
s2=""+s.charAt(i);
break;
}
if(flag){
s2=s2.toUpperCase();
flag=false;
}
nws=nws+s2;
++i;
t2.setText(nws);
}
Assignment Answers class XII [email protected] Page 31 of 66
36. Type a text in a text box and apply Toggle case on it i.e. uppercase should be converted to
lowercase and vice versa.
int n;
int l=s.length();
int i=0;
while(i<=l-1){
char c=s.charAt(i);
n=c;
if(c>=97 && c<=122){
n=n-32;
c=(char)n;
}
else if(c>=65 && c<=90){
n=n+32;
c=(char)n;
}
nws=nws+c;
++i;
t2.setText(nws);
}
String nws="";
nws=str.replaceAll(search, repl);
t3.setText(nws);
}
Now convert him with her AND his with her yourself
Assignment Answers class XII [email protected] Page 32 of 66
37. The following GUI program illustrates various ‘Color’ concepts. Before creating this form , do
the following:
Õ write the code at the topmost line : import java.awt.Color ;
Õ add a listbox and name it ‘lstColor’ and in model property type : RED, GREEN, BLUE, BLACK and
YELLOW.
Õ add a combbox and name it ‘cmbColor’ and in model property type : RED, GREEN, BLUE, PINK and
ORANGE.
Õ Add 4 radio buttons and name them opRed, opGreen, opBlue and OPBlack and change their text
properties to RED. GREEN, BLUE and BLACK respectively. Assign the ButtonGroup property of these
buttons as ‘buttonGroup1’
Õ Add a label and name it as ‘lbl1’. Also ‘check’ its ‘Opaque’ property to true.
private void
lstColorValueChanged(javax.swing.event.ListSelectionEve
nt evt) {
String s=""+lstColor.getSelectedValue();
int i=lstColor.getSelectedIndex();
Color c= Color.white;
if(i==0) c=Color.RED;
if(i==1) c=Color.GREEN;
if(i==2) c=Color.BLUE;
if(i==3) c=Color.BLACK;
if(i==4) c=Color.YELLOW;
lbl1.setText(s);
lbl1.setBackground(c);
}
if(i==0) c=Color.RED;
if(i==1) c=Color.GREEN;
if(i==2) c=Color.BLUE;
if(i==3) c=Color.PINK;
if(i==4) c=Color.ORANGE;
lbl1.setText(s);
lbl1.setBackground(c);
}
Color c= Color.red;
lbl1.setText(s);
lbl1.setBackground(c);
}
Assignment Answers class XII [email protected] Page 33 of 66
Color c= Color.green;
lbl1.setText(s);
lbl1.setBackground(c);
}
Color c= Color.blue;
lbl1.setText(s);
lbl1.setBackground(c);
}
Color c= Color.black;
lbl1.setText(s);
lbl1.setBackground(c);
}
if(chkBold.isSelected())
txt1.setFont(new Font(fontname,Font.BOLD,fontsize));
if(chkItalic.isSelected())
txt1.setFont(new Font(fontname,Font.ITALIC,fontsize));
if(chkPlain.isSelected())
txt1.setFont(new Font(fontname,Font.PLAIN,fontsize));
}
Assignment Answers class XII [email protected] Page 35 of 66
After CUT
After PASTE
After COPY
After PASTE
Data Table
row1.addElement(txt1.getText());
row1.addElement(txt2.getText());
row1.addElement(txt3.getText());
row1.addElement(cmbClass.getSelectedItem());
row1.addElement(cmbSection.getSelectedItem());
if(opMale.isSelected()==true)
row1.addElement(opMale.getText());
else
row1.addElement(opFemale.getText());
modTable.addRow(row1);
btnClear.doClick();
txt1.requestFocus();
String gender="";
int n;
n=jTable1.getSelectedRow();
JOptionPane.showMessageDialog(this, n);
txt1.setText(""+modTable.getValueAt(n, 0));
txt2.setText(""+modTable.getValueAt(n, 1));
txt3.setText(""+modTable.getValueAt(n, 2));
cmbClass.setSelectedItem(""+modTable.getValueAt(n, 3));
cmbSection.setSelectedItem(""+modTable.getValueAt(n, 4));
gender=""+modTable.getValueAt(n, 5);
if(gender.equalsIgnoreCase("MALE"))
opMale.setSelected(true);
else
opFemale.setSelected(true);
}
Data Table class XII [email protected] Page 39 of 66
Coding behind ‘Count Records ClassWise’ button. This coding assumes that you enter class in a sorted order.
while(c<=t-1){
String cl=""+modTable.getValueAt(c, 3);
while(cl.equals(""+modTable.getValueAt(c, 3))){
++countclass;
++c;
if(c>t-1)break;
if(!(cl.equals(""+modTable.getValueAt(c, 3)))){
res=res+"Class: "+cl+" Total: "+countclass+"\n";
countclass=0;
break;
}//end if
if(c>t-1){
res=res+"Class: "+cl+" Total: "+countclass+"\n";
break;
}
btnGetValues.doClick();
int n=jTable1.getSelectedRow();
int i=0;
while(modTable2.getRowCount()>0)
modTable2.removeRow(i);
for(i=0;i<=5;i++){
String colname=modTable.getColumnName(i);
String colvalue=""+modTable.getValueAt(n, i);
row.addElement(colname);
row.addElement(colvalue);
modTable2.addRow(row);
} // end for
}
Data Table class XII [email protected] Page 41 of 66
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author subhashv
*/
import java.sql.*;
public class ConnectSv {
public static Connection connect() throws Exception{
String url="jdbc:mysql://localhost/xav";
String uname="root";
String pass="shibu24";
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(url, uname, pass);
}
}
Data Table class XII [email protected] Page 42 of 66
Code behind ‘Insert Record’ button.
int r=jTable1.getSelectedRow();
row1.addElement(txt1.getText());
row1.addElement(txt2.getText());
row1.addElement(txt3.getText());
row1.addElement(cmbClass.getSelectedItem());
row1.addElement(cmbSection.getSelectedItem());
if(opMale.isSelected()==true)
row1.addElement(opMale.getText());
else
row1.addElement(opFemale.getText());
modTable.insertRow(r, row1);
btnClear.doClick();
txt1.requestFocus();
Before Update
Data Table class XII [email protected] Page 44 of 66
After UPDATE
The Code:
int r=jTable1.getSelectedRow();
row1.addElement(txt1.getText());
row1.addElement(txt2.getText());
row1.addElement(txt3.getText());
row1.addElement(cmbClass.getSelectedItem());
row1.addElement(cmbSection.getSelectedItem());
if(opMale.isSelected()==true)
row1.addElement(opMale.getText());
else
row1.addElement(opFemale.getText());
modTable.removeRow(r);
modTable.insertRow(r, row1);
btnClear.doClick();
txt1.requestFocus();
}
GUI Dialogs class XII [email protected] Page 45 of 66
A dialog is a small separate subwindow that appears to either provide or request information to/from the user.
Common Dialogs which we have been using so far have been: JOptionPane swing window control allows us to
create pop up windows such as alerts, message boxes or input box.
JOptionPane.showInputDialog(“Enter a number”) ; -> displays a message and waits for an input from
the user. The input it receives will be of type ‘String’. So if the input is a number, you will be required to convert it
into int value.
Now, there is another dialog which accept ‘YES’, ‘NO’ or ‘CANCEL’ input from the user and act accordingly.
JOptionPane.showConfirmDialog(this,”Do you want to continue?”); -> if the user clicks ‘YES’ button a
value 0 will be returned, if the user clicks ‘NO’ button a value 1 will be returned and if the user clicks ‘CANCEL’
button a value 2 will be returned.
39. Create a GUI for that will accept a series of numbers using an Input dialog box. The program should
allow the user to enter numbers till he clicks ‘NO’ button in Confirm dialog box. In the end, program
should display the count,sum and average of all the numbers entered. To display these values a
Message dialog should be used.
I am first giving you the various screenshots of the above program. The coding will follow.
Õ
Õ
Õ
On clicking NO or
CANCEL button
On clicking YES
button
GUI Dialogs class XII [email protected] Page 46 of 66
Õ
Õ
Õ On clicking NO or CANCEL button the program will display the result as shown:
Õ
1. Null statements are also called empty statements. These statements contains only a semicolon and
no other statements. Such statements are useful in creating ‘time delay loops’. These loops pause
the program for some time. E.g. long wait =0;
while (++wait<10000) ;
3. Selection means that the execution of the statements depend on a condition test. These statements
are also called as conditional statements or decision statements. Java provides if and switch as
selection statements. In certain circumstance, ?: can also be used as an alternative to if statement.
?: operator can make the code little shorter, e.g. if(a> b){
z=20;
}
else{
z=10;
}
this code can be written with ?: as z=(a>b)? 20 : 10;
But this can be complicated if we have too many nested if’s to check eg.
if(a>b){
If(a>c){
m=a;
} else {
m=c;}
}
if(b>c){
m=b;
} else {
m=c;}
}
with ?: above code will look like : m=(a>b: (a>c? a :c) : (b>c? b : c)); // this is little bit confusing..
4. Conditional operators are feasible where conditions to check are minimal. In cases where there are
too many conditions and nested conditions are to be checked, they may prove complicated and
confusing. Also the precedence of conditional operator is less than the other mathematical
operators.
Default dangling else matching can be overridden by making proper use of {} braces.
5. Dangling else problem arises when in a nested if statements, number of ifs is more than the
number of else clauses. The question then arises, with which if does the additional else clause
property match up. In such case , java matches an else with the nearest if clause.
6. Switch and if-else statements can be used to select one of several alternatives.
7. Break statement is used to avoid ‘fall-through’ problem associated with switch statement. In ‘fall-
through’ the control falls to the matching case. When ‘break’ statement is encountered in switch
statement, program execution jumps to the line of code following the ‘switch’ statement i.e. outside
the body of the switch statement.
8. Switch can only test for equality whereas ‘if’ can evaluate a relational or logical expression.
If-else can handle ranges, whereas switch cannot. Each switch case label must be a single value.
Switch case label must be a constant while if-else can be used when 2 or more variables are
tested.
Switch statements are more efficient while testing a value against a set of constants.
9. In the absence of a break statement in switch, java will start executing the statements from
matching case and keep on executing statements for the following cases as well until either a
break statement is found or switch statement end is encountered. This is called fall-through.
10. No two case labels in the same switch statement can have identical values.
11. The default statement gets executed when no match is found in a switch statement.
12. Iteration statements are those statements which repeats a particular set of statements a
finite/infinite number of times based on a condition . E.g. for-next, while, do-while.
Some Basic Concepts class XII [email protected] Page 48 of 66
13. A loop has 4 elements namely:
o initialization expression: this is used to assign a starting value to the loop control variable.
The initialization expression(s) is executed only once, at the start of the loop.
o Test expression: this expression decides whether the loop body will be executed or not. If test
expression is true, the control enters the loop and executes the loop body statements
otherwise the control is transferred just after the loop.
Entry controlled loop or Top-tested loop: here the test expression is evaluated first
before entering the loop. Chances are that the loop body may not be executed even
once. E.g. for and while loop.
Exit controlled loop or Bottom tested loop: here the test condition is evaluated at the
end of the loop. This loop will be executed at least once. E.g. do-while loop.
o Update expression(s): this will change the value of loop control variable. This is evaluated at
the end after the loop body is executed in the absence of this expression, the loop may be
executed infinitely.
o Body of the loop: these contains the statements that will be executed repeatedly until the test
expression evaluates to true.
14. It is true that you can decrement the loop control variable. But in such a case, the start value of the
loop specified as initial value must be greater than the end value specified in test expression.
15. for(int i=51; i<=60;i++) S.o.p(i);
16. for(int i=10;i>=1;--i) S.o.p(i);
17. In a for loop, initialization expression(s), test expression and update expression are optional, i.e.
you can do away with any or all of these expressions. Even if you skip these expressions, the blank
semi colons(;) must be given.
If a loop does not contain any statement in its loop body, it is said to be an empty loop. An empty
loop is used to run a time delay loop. E.g. for(i=1; i<500; i++);
18. A variable scope is the part of the program segment where a particular variable will be visible or
say can be used. It is a block of code where a variable has been declared. It can be used only within
that block and all its subsequent blocks.
19. In the while loop, test expression is first evaluated and then the loop body is executed if the
condition is ‘true’. In case of do-while loop, the loop body is first executed and the test expression is
evaluated at the end of the loop statement. Thus with do-while loop, the loop body will be executed
at least once.
20. The ‘break’ statement terminates the smallest enclosing while, do-while, for and switch statement.
Execution resumes at the statement immediately following the body of the terminated statement.
‘break [label]’ causes the flow of control to break out of the containing statement which must be
labelled [label].
e.g outer:
for(i=0; i<10; i++){
inner:
for(j=0; j<5;j++){
break outer;
}
}
in the above example, the ’break outer’ statement will transfer the control after the ‘i’ loop. If it was just a
‘break’ statement, the control would have been transferred after the ‘j’ loop.
21. Labelled loops are useful as we can then use ‘break [label]’ to break out of a particular loop based
on some condition.
22. do-while loop should be used if the loop has be executed at least once and the condition has to be
checked at the end.
Some Basic Concepts class XII [email protected] Page 49 of 66
23. The ‘dangling-else’ problem arises when in a nested if statement, number of if’s is more than the
number of else clauses. The question then arises, with which if does the additional else clause
property matchup.
to override the default dangling – else matching is to place the last occurring unmatched if in a
compound statement
if(expr1){
if(expr2)
statement 1;
}
else
statement 2;
in the above example, the else statement will go with if(expr1).
24.
switch(a){
case 0: S.o.p(“Zero”);
break;
case 1: S.o.p(“One”);
break;
case 2: S.o.p(“Two”);
break;
case 3: S.o.p(“Three”);
break;
}
25. Java provides a multiple branch selection statement known as switch. This selection statement
successively tests the value of an expression against a list of integer or character constants. When
a match is found, the statement associated with that constant are executed.
switch(expression){
case constant 1: statement sequence 1:
break;
case constant 2: statement sequence 2:
break;
case constant 3: statement sequence 3:
break;
case constant n: statement sequence n:
break;
[ default : default statement sequence :
break;
}
‘default’ case of the switch need not be the last one. It can be anywhere in the switch. Also
there must not be two or more identical cases. It would lead to error.
26. it is a good practice to put a ‘break’ statement after the last case statement so as to avoid forgetting
the ‘break’ when you add another case statement at the end of the switch.
27.
txtBasic
txtOver panPer
(a panel)
txtHr
txtCCA
txtGross txtOvertime
txtNet
Some Basic Concepts class XII [email protected] Page 50 of 66
txtWork
panTemp
(a panel)
txtOverTmp
txtGross txtOvertime
txtNet
Total Amount is the sum total of Salary Amount (TxtSalary) and OverTime
Amount (TxtOverTime).
try{
basic=Integer.parseInt(txtBasic.getText());
}catch(Exception e){
System.out.println("Invalid Basic Amount");
txtBasic.requestFocus();
return;
}
hra=basic*10/100;
txtHr.setText(""+hra);
}
if(panPer.isVisible()==true){
int basic=Integer.parseInt(txtBasic.getText());
int overtime=Integer.parseInt(txtOver.getText());
int hra=Integer.parseInt(txtHr.getText());
Some Basic Concepts class XII [email protected] Page 51 of 66
int cca=Integer.parseInt(txtCCA.getText());
overtimeamt=overtime*75;
gross=basic+hra+cca;
net=gross+overtimeamt;
txtGross.setText(""+gross);
txtOvertime.setText(""+overtimeamt);
txtNet.setText(""+net);
}
if(panTemp.isVisible()==true){
int work=Integer.parseInt(txtWork.getText());
int overtime=Integer.parseInt(txtOverTmp.getText());
gross=(work*250);
overtimeamt=overtime*50;
net=gross+overtimeamt;
txtGross.setText(""+gross);
txtOvertime.setText(""+overtimeamt);
txtNet.setText(""+net);
}
}
int dd,mm,yy;
s=txtOrigin.getText();
txtOrigin.setText(s.toUpperCase());
s=txtDest.getText();
txtDest.setText(s.toUpperCase());
try{
dd=Integer.parseInt(txtDD.getText()) ;
mm=Integer.parseInt(txtMM.getText()) ;
yy=Integer.parseInt(txtYY.getText()) ;
}catch(Exception e){
JOptionPane.showMessageDialog(this,"Invalid Date....");
txtDD.requestFocus();
return;
}
if(dd<0||dd>31){
JOptionPane.showMessageDialog(this,"Not a valid day (1-31)");
txtDD.requestFocus();
return;
}
if(mm<0||mm>12){
JOptionPane.showMessageDialog(this,"Not a valid Month (1-12)");
txtMM.requestFocus();
return;
}
if(yy<2000||yy>2010){
JOptionPane.showMessageDialog(this,"Not a valid YEAR (2000-2010)");
txtYY.requestFocus();
return;
}
}
Data Connectivity class XII [email protected] Page 53 of 66
Data Connectivity_Add_Record
classlist:
classtest1
1. Adding Records:
import java.sql.*;
import javax.swing.*;
s=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
s2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
} catch(Exception e){
System.out.println(e);
}
System.out.println("success");
int t=0;
while(rs.next()){
++t;
}
JOptionPane.showMessageDialog(this,t);
} catch(Exception e){
System.out.println(e);
}
}
rs2.moveToInsertRow();
rs2.updateString("regno", txtRegno.getText());
rs2.insertRow();
System.out.println("Record Added");
}catch(Exception e){System.out.println(e);
txtRegno.requestFocus();
}
boolean morerecs=true;
try{
rs=s.executeQuery("select * from classlist order by std,sec,sname");
System.out.println(cl+" "+section);
rs.first();
while(morerecs==true){
cl=rs.getString("std");
section=rs.getString("sec");
System.out.println(cl+" "+section);
while((cl.equalsIgnoreCase(rs.getString("std"))) &&
(section.equalsIgnoreCase(rs.getString("sec")))){
rs.updateString("roll", ""+n);
++n;
rs.updateRow();
rs.next();
if(rs.isAfterLast()){
morerecs=false;
break;
} // end if
n=1;
}catch(Exception e){System.out.println(e);}
} // end function
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Add().setVisible(true);
}
});
}
Connection conn=null;
Statement s,s2;
ResultSet rs,rs2;
} // end class
Data Connectivity class XII [email protected] Page 56 of 66
Data Connectivity_Modify_Record
* @author subhashv
*/
import java.sql.*;
import javax.swing.*;
import java.util.*;
import javax.swing.table.*;
int oldReg=0;
/** Creates new form Modifications */
public Modifications() {
initComponents();
try{
conn=ConnectSv.connect();
System.out.println("Success in Connectiion");
s=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
s2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
} catch(Exception e){
System.out.println(e);
}
System.out.println("success");
rsmd=rs.getMetaData();
emptyTable();
for(int i=1;i<=rsmd.getColumnCount();++i){
modTable.addColumn(rsmd.getColumnLabel(i));
}
int t=0;
while(rs.next()){
++t;
Vector row=new Vector();
for(int i=1;i<=rsmd.getColumnCount();++i){
row.addElement(rs.getString(i));
}
modTable.addRow(row);
}
rs.close();
}catch(Exception e){
System.out.println(e);
}
} // end btnConnect
tRegno.setText(""+modTable.getValueAt(n, 0));
oldReg=Integer.parseInt(tRegno.getText()); // storing old regno value
tRoll.setText(""+modTable.getValueAt(n, 1));
tClass.setText(""+modTable.getValueAt(n, 2));
tSection.setText(""+modTable.getValueAt(n, 3));
tMF.setText(""+modTable.getValueAt(n, 4));
tName.setText(""+modTable.getValueAt(n, 5));
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
int n=jTable1.getSelectedRow();
try{
rs.absolute(n+1);
rs.updateString(1, tRegno.getText());
rs.updateString(2, tRoll.getText());
rs.updateString(3, tClass.getText());
rs.updateString(4, tSection.getText());
rs.updateString(5, tMF.getText());
rs.updateString(6, tName.getText());
rs.updateRow();
System.out.println("Row "+n +" Successfully Updated");
}catch(Exception e){System.out.println(e);}
} // end btnUpdate
Data Connectivity class XII [email protected] Page 58 of 66
void emptyTable(){
int trow=jTable1.getRowCount();
System.out.println(trow);
int i=0;
while(i<trow){
modTable.removeRow(0);
++i;
}
modTable.setColumnCount(0);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Modifications().setVisible(true);
}
});
}
Connection conn=null;
Statement s,s2;
ResultSet rs,rs2;
ResultSetMetaData rsmd;
Data Connectivity_Add_Marks
import java.sql.*;
import javax.swing.*;
}catch(Exception e){
System.out.println(e);
}
rs1.first();
System.out.println("success");
int t=0;
while(rs1.next()){
++t;
}
JOptionPane.showMessageDialog(this,t);
}catch(Exception e){
System.out.println(e);
}
} // end btnConnect
rs2.updateRow();
}catch(Exception e){System.out.println(e);}
} // end btnSave
tPhy.setEditable(false);
tChe.setEditable(false);
tMat.setEditable(false);
tInf.setEditable(false);
}
tEng.setEditable(false);
tChe.setEditable(false);
tMat.setEditable(false);
tInf.setEditable(false);
}
tPhy.setEditable(false);
tEng.setEditable(false);
tMat.setEditable(false);
tInf.setEditable(false);
}
tPhy.setEditable(false);
tChe.setEditable(false);
tEng.setEditable(false);
tInf.setEditable(false);
}
tPhy.setEditable(false);
tChe.setEditable(false);
tMat.setEditable(false);
tEng.setEditable(false);
}
Data Connectivity class XII [email protected] Page 62 of 66
if(kc==10){
btnSave.doClick();
btnNext.doClick();
}
}
void focus(){
if(opEng.isSelected())tEng.requestFocus();
if(opPhy.isSelected())tPhy.requestFocus();
if(opChe.isSelected())tChe.requestFocus();
if(opMat.isSelected())tMat.requestFocus();
if(opInf.isSelected())tInf.requestFocus();
}
Data Connectivity class XII [email protected] Page 63 of 66
void showrec(){
try{
tRegno1.setText(rs1.getString("regno"));
String r=tRegno1.getText();
tRoll.setText(rs1.getString("roll"));
tName.setText(rs1.getString("sname"));
tClass.setText(rs1.getString("std"));
tSection.setText(rs1.getString("sec"));
tMF.setText(rs1.getString("mf"));
tRegno2.setText(rs2.getString("regno"));
tEng.setText(rs2.getString("eng"));
tPhy.setText(rs2.getString("phy"));
tChe.setText(rs2.getString("che"));
tMat.setText(rs2.getString("maths"));
tInf.setText(rs2.getString("info"));
}catch(Exception e){
System.out.println(e);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addMarks().setVisible(true);
}
});
}
Connection conn=null;;
Statement s1,s2;
ResultSet rs1,rs2;
Data Connectivity_View_Record
import java.sql.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.*;
}catch(Exception e){
System.out.println(e);
}
System.out.println("success");
emptyTable();
rsmd=rs1.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();++i){
modTable.addColumn(rsmd.getColumnLabel(i));
}
Data Connectivity class XII [email protected] Page 65 of 66
int t=0;
while(rs1.next()){
++t;
Vector row=new Vector();
for(int i=1;i<=rsmd.getColumnCount();++i){
row.addElement(rs1.getString(i));
}
modTable.addRow(row);
}
rs1.close();
}catch(Exception e){
System.out.println(e);
}
} // end jButton1
void emptyTable(){
int trow=jTable1.getRowCount();
System.out.println(trow);
int i=0;
while(i<trow){
modTable.removeRow(0);
++i;
}
modTable.setColumnCount(0);
}
int en,ph,ch,ma,in;
int tot;
double per;
try{
en=Integer.parseInt(""+modTable.getValueAt(n, 7));
}catch(Exception e){ en=0;}
try{
ph=Integer.parseInt(""+modTable.getValueAt(n, 8));
}catch(Exception e){ ph=0;}
try{
ch=Integer.parseInt(""+modTable.getValueAt(n, 9));
}catch(Exception e){ ch=0;}
try{
ma=Integer.parseInt(""+modTable.getValueAt(n, 10));
}catch(Exception e){ ma=0;}
try{
in=Integer.parseInt(""+modTable.getValueAt(n, 11));
}catch(Exception e){ in=0;}
tot=en+ph+ch+ma+in;
per=tot/250.0*100;
tTotal.setText(""+tot);
tPercent.setText(""+per);
} // end JTable1MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new vueMarks().setVisible(true);
}
});
}
Connection conn=null;
Statement s1,s2;
ResultSet rs1,rs2;
ResultSetMetaData rsmd;
Data Connectivity class XII [email protected] Page 66 of 66