Sanjay Sharma
Page | 1
List of Programs: -1. Program for factorial of an entered number _______________________________________ 4 2. Program to find the sum of all odd no. Lower than the input no. _______________________ 4 3. WAP using (a) default constructor (b) argument constructor(c) copy constructor __________ 4 4. Program to solve the linear Equation ____________________________________________ 5 5. Program to solve a quadratic Equation ___________________________________________ 5 6. To find the volume and surface area of a cuboid. __________________________________ 5 7. Program for illustrate a copy constructor so that a string may be duplicated in to another ___ 5 8. Program for constructor overloading ____________________________________________ 6 9. WAP to implement in how many ways a team of 11 player out of 15 ___________________ 7 10. Wap to calculate the distance travelled by a vehicle by s = ut +(1/2*(a*(t*t)) ____________ 7 11. Program to implment public private & protected mechanism ________________________ 7 12. WAP for user defined package and interface in which you can write your own interface and classes. _____________________________________________________________________ 8 13 Program to display the records of Books _________________________________________ 8 14. Program to find armstrong number between 100-1000 _____________________________ 9 15. Program to implement shift operator ___________________________________________ 9 16. Program to show synchronization between threads ________________________________ 9 17. WAP todemonstrate few types of exception using try and catch blocks ________________ 10 18. WAP to illustrate the use of throw clause _______________________________________ 10 19. W.A.P to design a calculator _________________________________________________ 10 20. Program to find power of 2 __________________________________________________ 12 21. WAP to demonstrate the Mouse handling events. _________________________________ 12 22. WAP in awt to demonstrate frame, checkbox, button ,menu of your own choice ________ 14 23. Swap two values without using any third variable ________________________________ 15 24. Program to change cms in inch and feet ________________________________________ 15 25. wap for the string manipulation ______________________________________________ 15 26. Program to implement shift opeartors__________________________________________ 17 27. Program to search an element in an array _______________________________________ 17 28. Program to solve linear & quadratic equation ___________________________________ 18 29. WAP using default argument constructor _______________________________________ 19 30 . WAP to compute whether the given no. is prime or not ___________________________ 19 31. Program to find the power of 2 without arithematic operation _______________________ 19 32. Program to find permutation p(n,r)=n!/(n-r)! ____________________________________ 19 33. Program to find the transpose of a Matrix ______________________________________ 20 Page | 2
34. Program to display the faculy Records _________________________________________ 21 35. Program for constructor overloading __________________________________________ 22 36. Program to demonstrate linked list ____________________________________________ 22 37. Solving a linear equation ___________________________________________________ 23 38. Program to implement String Tokenizer ________________________________________ 23 39. Program to implement final, static and abstract modifier ___________________________ 24 40. Program for implementing Fibonacci series _____________________________________ 24 41. Write a program of ur own which implements interface ___________________________ 24 42. Write a program to show at least 8 exceptions. __________________________________ 25 43. Program to compute division of 2 without using any mathmatical operator ____________ 26 44. Program to implement Runtime polymorphism __________________________________ 27 45. Program for a frog to reach the top of wall. _____________________________________ 27 46. WAP to find the sum of Digits _______________________________________________ 28 47. Program to find the combination 15C11 _________________________________________ 28 48. Program to implement public, private and protected mechanism_____________________ 28 49. Program to check whether the given character is a vowel or not _____________________ 29 50. W.A.P to create an applet with button __________________________________________ 29 51. Program to display actor's name in checkboxes __________________________________ 30 52. Program to demonstrate the User-Defined Exceptions. ____________________________ 31 53. Program to implement bitwise operators _______________________________________ 32 54. WAP to create an applet to receive text from textfield and display on applet ___________ 33 55. Program to create Menu in a Frame. ___________________________________________ 33 56. Program to implement Vector class ___________________________________________ 33 58. Program to implement type casting ___________________________________________ 34 59. Program to display car in list ________________________________________________ 35 60. Program to show magic square in table ________________________________________ 35 61. Program to create a thread by implementing runnable interface _____________________ 36 62. Program to show synchronization between threads _______________________________ 36
Page | 3
2. PROGRAM TO FIND THE SUM OF ALL ODD NO. LOWER THAN THE INPUT NO.
import java.util.Scanner; public class SUM { public static void main(String args[]) { System.out.print("Enter the Number = "); Scanner in = new Scanner(System.in); int n = in.nextInt(); int sum = 0; for(int i= 1 ; i < n ; i+=2) sum = sum + i; System.out.println("Sum is = "+sum); } }
3. WAP USING (A) DEFAULT CONSTRUCTOR (B) ARGUMENT CONSTRUCTOR(C) COPY CONSTRUCTOR
public class Constructor { int a, b; Constructor() { a = 10; b = 20; } Constructor(int a, int b) { this.a = a; this.b = b; } Constructor(Constructor ob) { a = ob.a; b = ob.b; } public void show() { System.out.println("a = " + a + "\nb = " + b); } public static void main(String args[]) { Constructor c = new Constructor(); Constructor c2 = new Constructor(c); c.show(); c2.show(); }} OUTPUT a = 10 b = 20 c = 10 b = 20
Page | 4
7. PROGRAM FOR ILLUSTRATE A COPY CONSTRUCTOR SO THAT A STRING MAY BE DUPLICATED IN TO ANOTHER
public class Constructor { String str; Constructor() { str = "hello java"; } Constructor(String str) { this.str = str; } Constructor(Constructor ob) { this.str = ob.str; } public void show() { System.out.println(str); } public static void main(String args[]) { Constructor c = new Constructor(); Constructor c2 = new Constructor("java for u"); Constructor c3 = new Constructor(c2); c.show(); c2.show();
Page | 5
Page | 6
10. WAP TO CALCULATE THE DISTANCE TRAVELLED BY A VEHICLE BY S = UT +(1/2*(A*(T*T)) 11. PROGRAM TO IMPLMENT PUBLIC PRIVATE & PROTECTED MECHANISM
class base{ private int i; public int j; public base() { i=5; j=15; } protected int add(int a, int b) { return a+b; } public int add() { return i+j; }} class subclass extends base{ public subclass() { super(); } public void display() { System.out.println(add(2,3)+" "+add()); }} public class q19 { public static void main(String[] args) { subclass sub = new subclass(); sub.display(); } } OUTPUT 5 20
Page | 7
Page | 8
} else { i++; } } System.out.println("Want to check for more book records(y/n).."); ans = in.nextLine(); } } } OUTPUT: Enter the book name java java Price of the book is..100/= Want to check for more book records(y/n).. y Enter the book name toc java toc Price of the book is..200/= Want to check for more book records(y/n).. n
Page | 9
17. WAP TODEMONSTRATE FEW TYPES OF EXCEPTION USING TRY AND CATCH BLOCKS
//done in question 42
Page | 10
ActionListener command = new CommandAction(); panel = new JPanel(); panel.setLayout(new GridLayout(4, 4)); addButton("7", insert); addButton("8", insert); addButton("9", insert); addButton("/", command); addButton("4", insert); addButton("5", insert); addButton("6", insert); addButton("*", command); addButton("1", insert); addButton("2", insert); addButton("3", insert); addButton("-", command); addButton("0", insert); addButton(".", insert); addButton("=", command); addButton("+", command); add(panel, BorderLayout.CENTER); } private void addButton(String label, ActionListener listener) { JButton button = new JButton(label); button.addActionListener(listener); panel.add(button); } private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent event) { String input = event.getActionCommand(); if (start) { display.setText(""); start = false; } display.setText(display.getText() + input); } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (start) { if (command.equals("-")) { display.setText(command); start = false; } else { lastCommand = command; } } else { calculate(Double.parseDouble(display.getText())); lastCommand = command; start = true; }}} public void calculate(double x) { if (lastCommand.equals("+")) { result += x; } else if (lastCommand.equals("-")) { result -= x; } else if (lastCommand.equals("*")) { result *= x;
Page | 11
} else if (lastCommand.equals("/")) { result /= x; } else if (lastCommand.equals("=")) { result = x; } display.setText("" + result); } private private private private private } JButton display; JPanel panel; double result; String lastCommand; boolean start;
Page | 12
} public void mouseExited(MouseEvent m){ setBackground(Color.black); showStatus("Mouse Exited"); repaint(); } public void mousePressed(MouseEvent m) { X=10; Y=20; msg="SMVDU"; setBackground(Color.green); repaint(); } public void mouseReleased(MouseEvent m){ X=10; Y=20; msg="Engineering"; setBackground(Color.blue); repaint(); } public void mouseMoved(MouseEvent m){ X=m.getX(); Y=m.getY(); msg="College"; setBackground(Color.white); showStatus("Mouse Moved"); repaint(); } public void mouseDragged(MouseEvent m) { msg="CSE"; setBackground(Color.yellow); showStatus("Mouse Moved"+m.getX()+" "+m.getY()); repaint(); } public void mouseClicked(MouseEvent m) { msg="Students"; setBackground(Color.pink); showStatus("Mouse Clicked"); repaint(); } public void paint(Graphics g) { g.drawString(msg,X,Y); } } Output:
Page | 13
22. WAP IN AWT TO DEMONSTRATE FRAME, CHECKBOX, BUTTON ,MENU OF YOUR OWN CHOICE
import java.awt.*; import java.awt.event.*; public class AWT extends WindowAdapter { private Frame f; private Button b; private MenuBar bar; private Menu file,Edit,Help; private MenuItem New,close; private Checkbox c1,c2,c3; public void windowClosing(WindowEvent e) { System.exit(0); } public void addall() { f = new Frame("PROG NO. 22"); f.setSize(450,300); f.setVisible(true); f.setLayout(null); WindowListener listener = new AWT(); f.addWindowListener(listener); b = new Button("CLOSE"); b.setBounds(200,130,80,40); f.add(b); bar = new MenuBar(); file = new Menu("File"); Edit = new Menu("Edit"); Help = new Menu("Help"); New = new MenuItem("New"); close = new MenuItem("Close"); file.add(New); file.add(close); bar.add(file); bar.add(Edit); bar.add(Help); // f.add(bar); f.setMenuBar(bar); c1 = new Checkbox("YES"); c2 = new Checkbox("NO"); c3 = new Checkbox("CANN'T SAY"); f.add(c1); f.add(c2); f.add(c3); c1.setBounds(50,80,100,40); c2.setBounds(150,80,100,40); c3.setBounds(250,80,100,40); } public static void main(String args[]) { AWT ob = new AWT(); ob.addall(); } } OUTPUT:
Page | 14
Page | 15
SUBSTRING=urab
Page | 16
Page | 17
OUTPUT:: ENTER THE TOTAL NO. OF ELEMENT IN ARRAY = 4 ENTER THE 1 ELEMENT = 4 ENTER THE 2 ELEMENT = 3 ENTER THE 3 ELEMENT = 10 ENTER THE 4 ELEMENT = 2 ENTER THE NUMBER U WANT TO SEARCH = 10 ELEMENT FOUND IN ARRAY AT 3 POSITION
Page | 18
Page | 19
if(n==1) return 1; else return n*fact(n-1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("For Permutation nPr Enter the value of n & r : "); int n = sc.nextInt(); int r = sc.nextInt(); int P = fact(n)/fact(n-r); System.out.println("Permutation "+n+"P"+r+" : "+P); } } OUTPUT For Permutation nPr Enter the value of n & r ::7 Permutation 7P3 : 210 3
Page | 20
OUTPUT: Enter no. of rows 2 Enter no. of columns 2 Enter (mat0,0) 1 Enter (mat0,1) 2 Enter (mat1,0) 3 Enter (mat1,1) 4 original array is 1 2 3 4 transposed array is 1 3 2 4
Page | 21
Page | 22
ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); System.out.println("Original contents of ll: " + ll); // remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: "+ ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: "+ ll); // get and set a value Object val = ll.get(2); ll.set(2, (String) val + " Changed"); System.out.println("ll after change: " + ll); } } OUTPUT Original contents of ll: [A, A2, F, B, D, E, C, Z] Contents of ll after deletion: [A, A2, D, E, C, Z] ll after deleting first and last: [A2, D, E, C] ll after change: [A2, D, E Changed, C]
Page | 23
Page | 24
void print3(); } class face implements two { public void print1() { System.out.println("ONE::1"); } public void print2() { System.out.println("TWO::2"); } public void print3() { System.out.println("THREE::3"); } } public class q23 { public static void main(String args[]) { face f = new face(); f.print1(); f.print2(); f.print3(); } } OUTPUT ONE::1 TWO::2 THREE::3
Page | 25
System.out.println(a[5]); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } try { //excep5 FileInputStream in = new FileInputStream("hello.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { //excep6 Socket s = new Socket("localhost", 4567); } catch (Exception e) { e.printStackTrace(); } try{ //excep7 int a[] = new int[-7]; } catch (NegativeArraySizeException e) { e.printStackTrace(); } try { //excep8 String str = "hello"; System.out.println(str.charAt(7)); } catch (StringIndexOutOfBoundsException e) { e.printStackTrace(); } } } OUTPUT java.net.MalformedURLException: unknown protocol: abc java.net.UnknownHostException: www.gaagle.com java.lang.ArithmeticException: / by zero java.lang.ArrayIndexOutOfBoundsException: 5 java.io.FileNotFoundException: hello.txt (No such file or directory) java.net.ConnectException: Connection refused java.lang.NegativeArraySizeException java.lang.StringIndexOutOfBoundsException: String index out of range: 7
Page | 26
Page | 27
Page | 28
} public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Yes")) { msg = "You pressed Yes."; } else if(str.equals("No")) { msg = "You pressed No."; } else {
Page | 29
msg = "You pressed Undecided."; } repaint(); } public void paint(Graphics g) { g.drawString(msg, 6, 100); }}
public A33A() { init(); this.setBounds(0, 0, 500, 510); this.setLocationRelativeTo(null); } private void init() { buttonGroup1 = new ButtonGroup(); disp = new JLabel(); jCheckBox1 = new JCheckBox("Amitabh Bachchan"); jCheckBox2 = new JCheckBox("Akshay Kumar"); jCheckBox3 = new JCheckBox("Shahrukh Khan"); jCheckBox4 = new JCheckBox("Salman Khan"); jCheckBox5 = new JCheckBox("Sunny Deol"); jLabel1 = new JLabel("Select any Actor of your choice : "); jLabel2 = new JLabel("You Selected :"); ActionListener al = new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { if (jCheckBox1.isSelected()) { disp.setText("Amitabh Bachchan"); } else if (jCheckBox2.isSelected()) { disp.setText("Akshay Kumar"); } else if (jCheckBox3.isSelected()) { disp.setText("Shahrukh Khan"); } else if (jCheckBox4.isSelected()) { disp.setText("Salman Khan"); } else if (jCheckBox5.isSelected()) { disp.setText("Sunny Deol"); } } }; buttonGroup1.add(jCheckBox1); buttonGroup1.add(jCheckBox2); buttonGroup1.add(jCheckBox3);
Page | 30
buttonGroup1.add(jCheckBox4); buttonGroup1.add(jCheckBox5); jCheckBox5.addActionListener(al); jCheckBox4.addActionListener(al); jCheckBox3.addActionListener(al); jCheckBox2.addActionListener(al); jCheckBox1.addActionListener(al); } public static void main(String[] args) { A33A a = new A33A(); a.setVisible(true); a.add(disp).setBounds(101, 225, 200, 30); a.add(jCheckBox1).setBounds(101, 150, 200, 20); a.add(jCheckBox2).setBounds(101, 100, 200, 20); a.add(jCheckBox3).setBounds(101, 125, 200, 20); a.add(jCheckBox4).setBounds(101, 175, 200, 20); a.add(jCheckBox5).setBounds(101, 200, 200, 20); a.add(jLabel1).setBounds(100, 50, 300, 30); a.add(jLabel2).setBounds(5, 225, 100, 30); }}
Page | 31
if (e instanceof MySubException) System.out.print("MySubException: "); else System.out.print("MyException: "); System.out.println(e.getMessage()); System.out.println("Handled at point 1"); } } public static void b(int i) throws MyException { int result; try { System.out.print("i = " + i); result = c(i); System.out.print(" c(i) = " + result); } catch (MyOtherException e) { // Point 2 // Handle MyOtherException exceptions: System.out.println("MyOtherException: " + e.getMessage()); System.out.println("Handled at point 2"); } finally { // Terminate the output we printed above with a newline. System.out.print("\n"); } } public static int c(int i) throws MyException, MyOtherException { switch (i) { case 0: // processing resumes at point 1 above throw new MyException("input too low"); case 1: // processing resumes at point 1 above throw new MySubException("input still too low"); case 99:// processing resumes at point 2 above throw new MyOtherException("input too high"); default: return i*i; } } }
Page | 32
54. WAP TO CREATE AN APPLET TO RECEIVE TEXT FROM TEXTFIELD AND DISPLAY ON APPLET
import java.awt.*; import java.awt.event.*; import java.applet.*; public class appletdemo2 extends Applet implements ActionListener { TextField name; public void init() { Label namep = new Label("Enter Text: ", Label.RIGHT); Button button = new Button("CLEAR TEXT"); name = new TextField(12); add(namep); add(name); add(button,BorderLayout.SOUTH); name.addActionListener(this); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { name.setText(null); repaint(); }});} public void actionPerformed(ActionEvent ae) { repaint(); } public void paint(Graphics g) { g.drawString("Your text is : " + name.getText(), 6, 60); }}
// done in question 39
56. PROGRAM TO IMPLEMENT VECTOR CLASS
import java.util.*; class VectorClass { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println("Initial size: " + v.size()); System.out.println("Initial capacity: " + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println("Capacity after four additions: " + v.capacity()); v.addElement(new Double(5.45)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Double(6.08));
Page | 33
v.addElement(new Integer(7)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println("First element: " +(Integer)v.firstElement()); System.out.println("Last element: " +(Integer)v.lastElement()); if(v.contains(new Integer(3))) System.out.println("Vector contains 3."); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println("\nElements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); System.out.println(); } } OUTPUT Initial size: 0 Initial capacity: 3 Capacity after four additions: 5 Current capacity:5 Current capacity: 7 Current capacity: 9 First element: 1 Last element: 12 Vector contains 3. Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12
Page | 34
Page | 35
private void init() { jt = new JTable(); jsp = new JScrollPane(); jsp.setViewportView(jt); jt.setModel(new DefaultTableModel( new Object[][]{ {2, 9, 4}, {7, 3, 5}, {6, 1, 8} }, new String[]{ "MAGIC", "SQUARE", "TABLE" })); add(jt).setBounds(100, 100, 300, 100); } public static void main(String[] a) { new magic().setVisible(true); } }
Page | 36
wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); }} class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); }}} class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); }}} class q31 { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); }}
Page | 37