0% found this document useful (0 votes)
3K views

3rd Sem Java Lab Programs

The document contains code for several Java programs that demonstrate different Java concepts: 1. A class with multiple constructors and methods that performs addition of variables. 2. Classes demonstrating inheritance and calling superclass methods from subclasses. 3. A class with nested classes where one throws a custom exception. 4. A producer-consumer problem solved using threads and synchronization. 5. Classes implementing a stack interface using both fixed-size and dynamic arrays. 6. A generic class with type parameters. 7. Demonstration of LinkedList methods like add, addFirst, and set.

Uploaded by

rajakammara
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views

3rd Sem Java Lab Programs

The document contains code for several Java programs that demonstrate different Java concepts: 1. A class with multiple constructors and methods that performs addition of variables. 2. Classes demonstrating inheritance and calling superclass methods from subclasses. 3. A class with nested classes where one throws a custom exception. 4. A producer-consumer problem solved using threads and synchronization. 5. Classes implementing a stack interface using both fixed-size and dynamic arrays. 6. A generic class with type parameters. 7. Demonstration of LinkedList methods like add, addFirst, and set.

Uploaded by

rajakammara
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Srini JAVA programs

1.a class add { double a,b,c,n; add() { System.out.println("\nwith 0 arguement constructor invoked"); a=0;b=0;c=0; } add(int x,int y) { System.out.println("\nwith 2 integer arugement constructor invoked"); a=x;b=y;c=0; } add(double i,double j,double k) { System.out.println("\nwith 3 arugement constructor invoked"); a=i;b=j;c=k; } void join() { n=a+b+c; System.out.println("\nwith no arguement method invoked"); System.out.println("a="+a+"\nb="+b+"\nc="+c); System.out.println("Answer="+n); } void join(int s,int t) { a=s;b=t;c=0; n=a+b+c; System.out.println("\nwith 2 integer arugement method invoked"); System.out.println("a="+a+"\nb="+b+"\nc="+c); System.out.println("Answer="+n); } void join(int s,int t,int u) { a=s;b=t;c=u; n=a+b+c; System.out.println("\nwith 3 integer arugement method invoked"); System.out.println("a="+a+"\nb="+b+"\nc="+c); System.out.println("Answer="+n); } void join(double m,double n,double o) { a=m;b=n;c=o; n=a+b+c; System.out.println("\nwith 3 double arugement method invoked"); System.out.println("methoda="+a+"\nb="+b+"\nc="+c); System.out.println("Answer="+n); } } class Onea { public static void main(String srini[]) { add a1=new add(); a1.join(); add a2=new add(2,3); a2.join();

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


add a3=new add(1.1,2.3,4.5); a3.join(); a1.join(4,5); a2.join(2,4,1); a3.join(4.2,6.8,4); }} 1.b class Outter { int a; Outter(){a=10;} Inner in1=new Inner(); class Inner { int b; Inner() { b=150; a=100; System.out.println("\nin inner class: Outter class variable a="+a); System.out.println("in inner class: Inner class variable b="+b); } } void pri2() { System.out.println("\nin outter class: Outter class variable a="+a); System.out.println("in outter class: Inner class variable cant be used"); } } class Oneb { public static void main(String srini[]) { Outter a1=new Outter(); a1.pri2(); } }

2.a class SuperClass { SuperClass(){ System.out.println("-- Super Class Cons --"); } void superMethod(String str) // para method { System.out.println(" Super class para method str = " + str); } } class SubClass extends SuperClass { SubClass(){ System.out.println("-- Sub Class Cons --"); }

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


void subMethod(String str) // para method { superMethod(str); // call super class method directly System.out.println(" Sub class para method str = " + str); } }

public class Prog_10MCA37_02_a { public static void main(String[] args) { SubClass subClass = new SubClass(); // subclass object created subClass.superMethod("-- String Para for Super Class method --"); // call super class method subClass.subMethod("-- String Para for Sub Class method --"); // call sub class method } } 2.b class TwoBF { public static void main(String sri[]) { try { int a=sri.length; int b=100/a; System.out.println("a:"+a); try { if(a==1) a=a/(a-a); if(a==2) { int c[]={1}; c[42]=99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("arry index out of bounds: "+e); } finally { System.out.println("arry index out of bounds finally"); } } catch(ArithmeticException e) { System.out.println("Divide by 0: "+e); } finally { System.out.println("arithmetic finally"); } } }

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs

3. class Twoclass { void creats() { double r; Account a1=new Account(); a1.deposit(1500); Account a2=new Account(); a2.deposit(1500); try { r=a1.withdraw(1200); withdraw(r); r=a2.withdraw(1800); withdraw(r); } catch(LessBalanceException e) { System.out.println("less balance exception: "+e); } } class Account { double balance; Account() { balance=500; } void deposit(double d) { balance+=d; System.out.println("Account Balance after deposite: "+balance); } double withdraw(double x) { balance-=x; return balance; } } class LessBalanceException extends Exception { double dis; LessBalanceException(double a) { dis=a; } public String toString() { return "LessBalanceException["+dis+"]"; } } void withdraw(double a) throws LessBalanceException { if(a<500) throw new LessBalanceException(a); System.out.println("Account balance after withdraw: "+a); }

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs

} class Three1 { public static void main(String Sri[]) { Twoclass a=new Twoclass(); a.creats(); } } 4. class Q { int n, stop = 20; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("-- InterruptedException caught --"); } System.out.println("<-- Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { 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++); if(q.n == q.stop) break; } }}

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs

class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "--- Consumer ---").start(); } public void run() { while(true) { q.get(); if(q.n == q.stop) break; } }} public class Prog_10MCA37_04 { public static void main(String[] args) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("....... Press Control-C to stop ........."); } } 5. import java.io.*; interface IStack_i { void push(int data); void pop(); void display(); }

class FixedStack_II implements IStack_i{ int stackSize = 3; int top = -1; int[] stack = new int[stackSize]; public void push(int data){ if(top!=stackSize-1){ stack[++top] = data; System.out.println("-- Fixed Stack Data = " + stack[top] + " Pushed --"); } else System.out.println("-- Fixed Stack OverFlow --"); } public void pop(){ if(top!=-1){ System.out.println("-- Fixed Stack Data = " + stack[top--] + " Popped --"); } else System.out.println("-- Fixed Stack UnderFlow --"); }

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs

public void display(){ if(top!=-1){ System.out.println("-- Fixed Stack Elements are --"); for(int i=top;i!=-1;i--) System.out.println(stack[i]); } } } class DynamicStack_III implements IStack_i{ int stackSize; int top = -1; int[] stack; DynamicStack_III(int stackSize){ this.stackSize = stackSize; stack = new int[stackSize]; } public void push(int data){ if(top!=stackSize-1){ stack[++top] = data; System.out.println("-- Dynamic Stack Data = " + stack[top] + " Pushed --"); } else System.out.println("-- Dynamic Stack OverFlow --"); } public void pop(){ if(top!=-1){ System.out.println("-- Dynamic Stack Data = " + stack[top--] + " Popped --"); } else System.out.println("-- Dynamic Stack UnderFlow --"); } public void display(){ if(top!=-1){ System.out.println("-- Dynamic Stack Elements are --"); for(int i=top;i!=-1;i--) System.out.println(stack[i]); } } } public class Prog_10MCA37_05 { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String choice;

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


while(true){ try{ System.out.println("-- Enter u r choice, 1 - Fixed Stack, 2 - Dynamic Stack, 3 - Exit --"); choice = br.readLine().trim(); IStack_i istack; if("1".equals(choice)) istack = new FixedStack_II(); else if("2".equals(choice)){ System.out.println("-- Enter Stack Size --"); istack = new DynamicStack_III(Integer.parseInt(br.readLine().trim())); } else break;

Loop: while(true){ try{ System.out.println("-- Enter u r choice, 1 - Push, 2 - Pop, 3 - Display, 4 - Exit --"); switch(Integer.parseInt(br.readLine().trim())){ case 1: System.out.println("-- Enter an Element to be Pushed --"); istack.push(Integer.parseInt(br.readLine().trim())); break; case 2: istack.pop(); break; case 3: istack.display(); break; default: break Loop; } }catch(Exception e){ System.out.println("-- Please enter valid data --"); } } }catch(Exception e){ System.out.println("-- Please enter valid choice --"); } } } }

6. package prog_10mca37_06; class Class1{ String str; Class1(String str){ this.str = str;

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


System.out.println("-- Class1 Cons String initialized = " + this.str); } } class Class2{ String str; Class2(String str){ this.str = str; System.out.println("-- Class2 Cons String initialized = " + this.str); } } class Generic<T,V>{ T t; V v; Generic(T t, V v){ this.t = t; this.v = v; System.out.println("-- Generic Class Constructor executed --"); } public String toString(){ return "-- Generic toString() method called Automatically by Cons --"; } } public class Prog_10MCA37_06 { public static void main(String[] args) { Generic<Class1, Class2> gen; System.out.println("-- In main = " + (gen = new Generic<Class1, Class2>(new Class1("--> String Para for Class1 from main"), new Class2("--> String Para for Class2 from main")))); System.out.println("-- In main Class1 str = " + gen.t.str); System.out.println("-- In main Class2 str = " + gen.v.str); } }

7. import java.util.*; public class Prog_10MCA37_07 { public static void main(String[] args) { LinkedList lst = new LinkedList(); LinkedList lst1 = new LinkedList(); lst.add("Sem"); lst.add("MCA"); lst.addFirst("3rd"); lst.addLast("MIT"); lst.add(1, "<->"); for(Object i : lst) System.out.print(i);

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs

System.out.println(); lst1.add("--List-01--"); lst1.addAll(0,lst); for(Object i : lst1) System.out.print(i); System.out.println(); lst.set(1, ">-<"); for(Object i : lst) System.out.print(i); System.out.println(); System.out.println("-- List length --" + lst.size()); System.out.println("-- The First element --" + lst.getFirst()); System.out.println("-- The Last element --" + lst.getLast()); System.out.println("-- The List index element --" + lst.get(0)); System.out.println("-- Removes First element --" + lst.remove()); System.out.println("-- Removes First element --" + lst.removeFirst()); System.out.println("-- Removes Last element --" + lst.removeLast()); } }

8. import java.io.*; public class Prog_10MCA37_08 { public static void main(String[] args) { try{ String path = "c:\\1.txt"; // Input file path FileInputStream fis = new FileInputStream(path); byte[] bRead = new byte[fis.available()]; fis.read(bRead); System.out.println("-- Input File Read --"); for(byte data : bRead) System.out.print((char)data);

path = "c:\\2.txt"; // Output file path FileOutputStream fos = new FileOutputStream(path); fos.write(bRead); fos.close(); fis = new FileInputStream(path); System.out.println("\n -- Output File Read --"); int read = -1; while((read = fis.read())!=-1) System.out.print((char)read);

10

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs

fis.close(); }catch(Exception e){ } } }

9. import java.io.*; class MyClass implements Serializable { String s; transient int i; // Not Persist / will not save double d; public MyClass(String s, int i, double d) { this.s = s; this.i = i; this.d = d; } public String toString() { return "s=" + s + "; transient var i=" + i + "; d=" + d; } }

public class Prog_10MCA37_09 { public static void main(String[] args) { // Object serialization try { MyClass object1 = new MyClass("MITM", 41, 13.2); System.out.println("object1: " + object1); FileOutputStream fos = new FileOutputStream("mitm"); // default project path // path with file name or file name with extention // "c:\\mitm", "c:\\mitm.txt", "mitm" ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } catch(Exception e) { System.out.println("Exception during serialization: " + e); System.exit(0); } // Object deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("mitm");// default project path // path with file name or file name with extention // "c:\\mitm", "c:\\mitm.txt", "mitm" ObjectInputStream ois = new ObjectInputStream(fis);

11

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } catch(Exception e) { System.out.println("Exception during deserialization: " + e); System.exit(0); } } }

10. import java.net.*; public class Prog_10MCA37_10 { public static int serverPort = 998; public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; public static byte buffer[] = new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while (true) { int c = System.in.read(); switch (c) { case -1: System.out.println("Server Quits."); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos, InetAddress.getLocalHost(),clientPort)); pos=0; break; default: buffer[pos++] = (byte) c; } } } public static void TheClient() throws Exception { while(true) { DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); System.out.println(new String(p.getData(), 0, p.getLength())); } } public static void main(String[] args) throws Exception{ if(args.length == 1) { ds = new DatagramSocket(serverPort); TheServer();

12

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


} else { ds = new DatagramSocket(clientPort); TheClient(); } } }

11. import java.awt.*; import java.awt.event.*; import java.applet.*; public class Prog_10MCA37_11 extends Applet implements MouseListener, MouseMotionListener{ String msg = ""; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() { addMouseListener(this); addMouseMotionListener(this); } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } // Handle button released.

13

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


public void mouseReleased(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. public void mouseMoved(MouseEvent me) { // show status showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } 12. import java.awt.*; import java.awt.event.*; import java.applet.*; public class Prog_10MCA37_12 extends Applet implements KeyListener{ String msg = ""; int X = 10, Y = 20; // output coordinates public void init() { addKeyListener(this); requestFocus(); // request input focus } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } // Display keystrokes.

14

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


public void paint(Graphics g) { g.drawString(msg, X, Y); } } 14. import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import javax.swing.tree.*; class Department extends JPanel implements ListSelectionListener{ JList jlst; JLabel jl; public Department(){ jl = new JLabel("........"); add(jl); String[] listData = new String[]{"MCA", "MBA", "BE", "BTec"}; jlst = new JList(listData); jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jlst.addListSelectionListener(this); add(jlst); JScrollPane jsp = new JScrollPane(jlst); jsp.setPreferredSize(new Dimension(100, 50)); add(jsp); } public void valueChanged(ListSelectionEvent e){ jl.setText(jlst.getSelectedIndex() + ", " + jlst.getSelectedValue()); } } class Course extends JPanel implements ActionListener{ JComboBox jcb; JLabel jl; public Course(){ jl = new JLabel("......."); add(jl); String[] listData = new String[]{"1-Sem", "2-Sem","3-Sem", "4-Sem", "5-Sem", "6-Sem", "7-Sem", "8-Sem"}; jcb = new JComboBox(listData); jcb.addActionListener(this); add(jcb); } public void actionPerformed(ActionEvent e){ jl.setText(jcb.getSelectedIndex() + ", " + jcb.getSelectedItem()); }

15

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


} class Gender extends JPanel implements ActionListener{ JRadioButton jb, jb1; JLabel jl; public Gender(){ jl = new JLabel("......"); add(jl); jb = new JRadioButton("Male"); jb.addActionListener(this); add(jb); jb1 = new JRadioButton("Female"); jb1.addActionListener(this); add(jb1); ButtonGroup bg = new ButtonGroup(); bg.add(jb); bg.add(jb1); } public void actionPerformed(ActionEvent e){ jl.setText(e.getActionCommand()); } } class Menu extends JPanel implements TreeSelectionListener{ JTree jt; JLabel jl; public Menu(){ jl = new JLabel("......"); add(jl); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); DefaultMutableTreeNode a = new DefaultMutableTreeNode("PG"); root.add(a); DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("MCA"); a.add(a1); DefaultMutableTreeNode one = new DefaultMutableTreeNode("UG"); root.add(one); DefaultMutableTreeNode b = new DefaultMutableTreeNode("BE"); one.add(b); DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("Cs"); b.add(b1); jt = new JTree(root); jt.addTreeSelectionListener(this); add(jt); JScrollPane jsp = new JScrollPane(jt); jsp.setPreferredSize(new Dimension(200, 100)); add(jsp); } public void valueChanged(TreeSelectionEvent e){ jl.setText(e.getPath().toString()); }} public class Prog_10MCA37_14 extends JApplet { private void GUI(){

16

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

Srini JAVA programs


JTabbedPane jtp = new JTabbedPane(); jtp.addTab("Department", new Department()); jtp.addTab("Course", new Course()); jtp.addTab("Gender", new Gender()); jtp.addTab("Menu", new Menu()); add(jtp); } public void init() { try{ SwingUtilities.invokeAndWait( new Runnable(){ public void run(){ GUI(); } }); }catch(Exception e){}}

17

Collections: http://srinivas-rangan.blogspot.in/p/mca-study-materials.html

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy