Practical 1 1(a):Write a Java program that takes a number as input and prints its multiplication table upto 10 Program import java.util.Scanner;
public class Main {
public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Input the Number: "); int n = in .nextInt(); for (int i = 1; i <= 10; i++) { System.out.println(n + "*" + i + " = " + (n * i)); } } }
Output:-Input the Number:
6
6*1 = 6 6*2 = 12 6*3 = 18 6*4 = 24 6*5 = 30 6*6 = 36 6*7 = 42 6*8 = 48 6*9 = 54 6*10 = 60
1(b) Write a Java program to display the following pattern.
***** **** *** ** * program:
Class Displaypattern { Public static void main(String ar[]) { Int i,j;
For(i=5;i>=1;i--) { For(j=1;j<=1;j++) { System.out.print(“*”) } System.out.println(); } } } Output:
***** **** *** ** *
1(C):. Write a Java program to print the area and perimeter of a circle
Program public class Areaperimeter { private static final double radius = 7.5; public static void main(String[] args) { double perimeter = 2 * Math.PI * radius; double area = Math.PI * radius * radius;
System.out.println("Perimeter is = " + perimeter); System.out.println("Area is = " + area); } }
Output: Perimeter is = 47.12388980384689 Area is = 176.71458676442586
Practical no 2 2.Use of Operators 2(a):Write a Java program to add two binary numbers. Program import java.util.Scanner; public class Exercise17 { public static void main(String[] args) { long binary1, binary2; int i = 0, remainder = 0; int[] sum = new int[20]; Scanner in = new Scanner(System.in);
System.out.print("Input first binary number: "); binary1 = in.nextLong(); System.out.print("Input second binary number: "); binary2 = in.nextLong();
while (binary1 != 0 || binary2 != 0) { sum[i++] = (int)((binary1 % 10 + binary2 % 10 + remainder) % 2); remainder = (int)((binary1 % 10 + binary2 % 10 + remainder) / 2); binary1 = binary1 / 10; binary2 = binary2 / 10; } if (remainder != 0) { sum[i++] = remainder; } --i;
System.out.print("Sum of two binary numbers: "); while (i >= 0) { System.out.print(sum[i--]); } System.out.print("\n"); } } Output: Input first binary number: 100010 Input second binary number: 110010 Sum of two binary numbers: 1010100
2(b):Write a Java program to convert a decimal number to binary number and vice versa. Program : public class BinaryDecimal {
public static void main(String[] args) { long num = 110110111; int decimal = convertBinaryToDecimal(num); System.out.printf("%d in binary = %d in decimal", num, decimal); }
public static int convertBinaryToDecimal(long num) { int decimalNumber = 0, i = 0; long remainder; while (num != 0) {
remainder = num % 10; num /= 10; decimalNumber += remainder * Math.pow(2, i); ++i; } return decimalNumber; } }
Output: 110110111 in binary = 439 in decimal
2(c)Write a Java program to reverse a string. Program : import java.lang.*; import java.io.*; import java.util.*;
// Class of ReverseString class ReverseString { public static void main(String[] args) { String input = "puzzles";
byte [] strAsByteArray = input.getBytes();
byte [] result =
new byte [strAsByteArray.length];
for (int i = 0; i<strAsByteArray.length; i++) result[i] = strAsByteArray[strAsByteArray.length-i-1];
System.out.println(new String(result)); } }
Output:
Zzupesl
Practical no
3.
3.Java Data Types 3(a).Write a Java program to count the letters, spaces, numbers and other characters of an input string. Program import java.util.Scanner; public class Exercise38 {
public static void main(String[] args) { String test = "Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33"; count(test);
} public static void count(String x){
char[] ch = x.toCharArray(); int letter = 0; int space = 0; int num = 0; int other = 0; for(int i = 0; i < x.length(); i++){ if(Character.isLetter(ch[i])){ letter ++ ; } else if(Character.isDigit(ch[i])){ num ++ ; } else if(Character.isSpaceChar(ch[i])){ space ++ ; } else{ other ++; } } System.out.println("The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33"); System.out.println("letter: " + letter); System.out.println("space: " + space); System.out.println("number: " + num); System.out.println("other: " + other); }}
Output: The string is : letter: 23 space: 9 number: 10 other: 6
Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33
3(b).Implement a Java function that calculates the sum of digits for a given char array consisting of the digits '0' to '9'. The function should return the digit sum as a long value. Program Class A { Public static void main(String ar[]) { String str=”67281”; Char array[]=str.toCharArray();
Long s=SumOfDigits.sumOfDigits(array); System.out.println(“sum of digits is:”+ s); } }
Class SumOfDigits { Public static long sumOfDigits(char arr[]) { Long sum=0; int n; int i=0;
While(i<=arr.length) { n=(int)arr[i]; Sum =sum+n; i++; } return sum;
} }
Output: Sum of digits is: 24.
3(c).Find the smallest and largest element from the array. Program: import java.util.Scanner; class demo { public static void main(String…s) { int i,n,large,small; Scanner sc=new Scanner(System.in); //used to read from keyboard
System.out.print(“Enter number of elements:”); n=sc.nextInt(); int a[]=new int[n];
System.out.print(“nEnter elements of Array:”); for(i=0;i
large=small=a[0]; for(i=1;i
large) large=a[i]; if(a[i]<small) small=a[i]; }
System.out.print(“nSmallest Element:”+small); System.out.println(“nLargest Element:”+large); } }
Output: Enter no of elements: 6 Enter elements of array: 2 6 38 28 17 12
Smallest element: 2 Largest elements: 38
Practical no 4. 4.Methods and Constructors 4(a):Designed a class SortData that contains the method asec() and desc(). Program import java.util.*; class prac4A { Scanner input=new Scanner(System.in); int num,i; int arr[]; int temp=0; public void getdata() { System.out.print("Enter the size of array: "); num=input.nextInt(); arr=new int[num];
System.out.print("Enter the number: "); for( i=0;iarr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } System.out.print("Ascending order of number are: "); for(int i=0;i
System.out.println(arr[i]); } } void desc() { for(i=0;i
}
Output: Enter array elements: 35 21 54 61 81 29 60 24 33 48
After sorting in ascending order: Sorted elements are: 21 24 29 33 35 48 54 60 61 81
After sorting in descending order: Sorted elements are: 81
61 60 54 48 35 33 29 24 21
4(b)Designed a class that demonstrates the use of constructor and destructor. Program: class xyz { xyz() { System.out.println("Constructor method........"); } protected void finalize() { System.out.print("Garbage Collected....."); } } class prac4B { public static void main(String args[]) { xyz ob=new xyz(); ob=null; System.gc(); }
} Output: Main starts Constructor executes This is set method Main ends Finalizer executes
Program import java.util.Scanner; abstract class test { abstract void get(); } class test1 extends test { void get() { int a,b; Scanner ob=new Scanner(System.in); System.out.print("Enter 1st Number: "); a=ob.nextInt(); System.out.println("Enter 2st Number: "); b=ob.nextInt(); System.out.println("Addition is: "+(a+b)); } } class prac4C { public static void main(String args[]) { test1 obj=new test1(); obj.get(); } }
Output: This is a normal method of abstract class A Abstract method is overridden in derived class This is normal method of derived class B
Practical no 5. 5.Inheritance 5(a)Write a java program to implement single level. Program Class A { public void methodA() { System.out.println("Base class method"); } }
Class B extends A { public void methodB() { System.out.println("Child class method"); } public static void main(String args[]) { B obj = new B(); obj.methodA(); //calling super class method obj.methodB(); //calling local method }}
Output: Main starts This set() method of base class This get() method of base class This check() method of derived class
This demo() method of derived class Main ends
5(b)Write a java program to implement method overriding inheritance. Program: class Parent { void show() { System.out.println("Parent's show()"); } }
class Child extends Parent { void show() { System.out.println("Child's show()"); } } class Main { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.show();
Parent obj2 = new Child(); obj2.show(); } }
Output:
Parent's show() Child's show()
5(c)Write a java program to implement multiple inheritance
Program // First Parent class class Parent1 { void fun() { System.out.println("Parent1"); } } class Parent2 { void fun() { System.out.println("Parent2"); } } class Test extends Parent1, Parent2 { public static void main(String args[]) { Test t = new Test(); t.fun(); } }
Output: Compiler Error
7.VECTORS AND MULTITHREADING Program 7(a): Write a Java program to implement the vectors. import java.util.*; class Vector_demo { public static void main(String[] arg) { ArrayList arr = new ArrayList(); arr.add(3); arr.add("geeks"); arr.add("forgeeks"); arr.add(4); Vector v = new Vector(); v.addAll(arr); System.out.println("vector v:" + v); } }
OUTPUT:-
Program 7(b): Write a program to implement thread life cycle. class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName+" interrupted."); } System.out.println("Thread " + threadName+"exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t=new Thread (this, threadName);
t.start (); } } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } }
Output:
:-
Program 7(c): Write a java program to implement multithreading. class MultithreadingDemo extends Thread { public void run() { try { System.out.println ("Thread " + Thread.currentThread().getId() + "is running"); }catch(Exception e) { System.out.println ("Exception is caught"); } } } public class Multithread { public static void main(String[] args) { int n = 8; for(int i=0; i<8; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start();
Output:
8 . File Handling Program 8(a): Write a program to open a file and display the contents in the console window. import java.util.Scanner; import java.io.*; public class WritingTextFiles { public static void main (String [] args) throws IOException{ FileWriter fw= new FileWriter("testing.txt"); Scanner in= new Scanner (System.in); String testwords=in.nextLine(); fw.write(testwords); BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) ); System.out.print(r); fw.close(); } }
Program 8(b): Write a java program to copy the contents from one file to other file. import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileCopyExample { public static void main(String[] args) { try { FileReader fr = new FileReader("input.txt"); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter("output.txt", true); String s; while ((s = br.readLine()) != null) { fw.write(s); fw.flush(); } br.close(); fw.close(); System.out.println("file copied"); } catch (IOException e) { e.printStackTrace(); } }
}
Program 8(c):- Write a java program to read the student data from the user and store it in the file. import java.io.*; public class Filewrite { public static void main(String args[])throws IOException { int roll; String name,city; DataInputStream dis=new DataInputStream(System.in); File file=new File("E:"); file.createNewFile(); FileWriter writer=new FileWriter(file); System.out.println("Enter students roll no"); roll=Integer.parseInt(dis.readLine()); System.out.println("Enter student name"); name=dis.readLine(); System.out.println("Enter city name"); city=dis.readLine(); writer.write("Roll number"+roll); writer.write("Name is "+name); writer.write("City is"+city); writer.flush(); writer.close();
System.out.println("Student Data saved into the file"); } }
9.GUI AND EXCEPTION HANDLING Program 9(a): Design an AWT program to print the factorial for an input value. import java.awt.*; import java.awt.event.*; public class FactEvent extends java.applet.Applet implements ActionListener { TextField t1,t2; int fact=1,m; Button b1,b2,b3; String msg; Label l1,l2; FactEvent e; public void init() {e=this; t1=new TextField(3); t2=new TextField(10); b1=new Button("FIND FACTORIAL"); l1=new Label("ENTER THE NUMBER"); l2=new Label("RESULT"); add(l1); add(t1);
add(l2); add(t2); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=t1.getText(); if(str!="") { int num=Integer.parseInt(str); for(int i=num;i>0;i--) { fact=fact*i; } msg="" +fact; t2.setText(msg); fact=1; } } }
OUTPUT:-
Program 9(b): Design an AWT program to perform various string operations like reverse string, string concatenation etc.
/* */ import java.awt.*; import java.applet.*; public class concat2Str extends Applet { TextField Ts1,Ts2; public void init(){ Ts1 = new TextField(10); Ts2 = new TextField(10); add(Ts1); add(Ts2); Ts1.setText(""); Ts2.setText("");
} public void paint(Graphics g){ String str1,str2; g.drawString("Enter Two String to Concat Them ",10,50); str1=Ts1.getText(); str2=Ts2.getText(); g.setColor(Color.red); g.drawString(str1+" "+str2,10,70); showStatus("Concatination of 2 String"); } public boolean action(Event e, Object o){ repaint(); return true; } }
OUTPUT:-
Program 9(c): Write a java program to implement exception handling class StringIndexOutOfBound_Demo { public static void main(String args[]) { try { String a = "This is like chipping "; // length is 22 char c = a.charAt(24); // accessing 25th element System.out.println(c); } catch(StringIndexOutOfBoundsException e) { System.out.println("StringIndexOutOfBoundsException"); } } }
OUTPUT:-
10. GUI PROGRAMMING Program 10(a): Design an AWT application that contains the interface to add student information and display the same.
import java.awt.*; import java.applet.*; import java.awt.event.*; /* */ public class Stupanel extends Applet implements ActionListener,ItemListener { String s1,s2,s3; TextField t3,t4,t5,t6,t7; Button tot,avg; Checkbox c1,c2,c3,c4,m,f; CheckboxGroup cbg; Panel p1,p2,p3,p4; public void init() { s3=" "; tot=new Button("Total"); avg=new Button("Average"); c1=new Checkbox("MCA",true); c2=new Checkbox("Msc Comp");
c3=new Checkbox("MSIT"); c4=new Checkbox("MSIS"); cbg=new CheckboxGroup(); m=new Checkbox("Male",cbg,false); f=new Checkbox("Female",cbg,true); p1=new Panel(); p1.setLayout(new GridLayout(2,2)); p1.add(new Label("Student Number ")); p1.add(new TextField(5)); p1.add(new Label("Student Name ")); p1.add(new TextField(15)); add(p1); p2=new Panel(); p2.setLayout(new GridLayout(1,3)); p2.add(new Label("Gender")); p2.add(m); p2.add(f); add(p2); p3=new Panel(); p3.setLayout(new GridLayout(1,5)); p3.add(new Label("Degree")); p3.add(c1); p3.add(c2);
p3.add(c3);
p3.add(c4);
add(p3); p4=new Panel(); p4.setLayout(new GridLayout(6,2)); p4.add(new Label("Marks in JAVA")); t3=new TextField(3); p4.add(t3);
p4.add(new Label("Marks in VB .Net")); t4=new TextField(3); p4.add(t4); p4.add(new Label("Marks In C")); t5=new TextField(3); p4.add(t5); p4.add(new Label("Total ")); t6=new TextField(3); p4.add(t6); p4.add(new Label(" Average")); t7=new TextField(3); p4.add(t7); p4.add(tot); p4.add(avg); tot.addActionListener(this); avg.addActionListener(this); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); c4.addItemListener(this); m.addItemListener(this); f.addItemListener(this); add(p4); } public void paint(Graphics g) { int no,m1,m2,m3,tot; float avg=0.0f; no=m1=m2=m3=tot=0;
try { m1=Integer.parseInt(t3.getText()); m2=Integer.parseInt(t4.getText()); m3=Integer.parseInt(t5.getText()); } catch(Exception e) { } tot=m1+m2+m3; avg= tot/3; s1=String.valueOf(tot); s2=String.valueOf(avg); } public boolean action(Event e,Object o) { repaint(); return true; } public void actionPerformed(ActionEvent e) { s3=e.getActionCommand(); if(s3.equals("Total")) t6.setText(s1);
if(s3.equals("Average")) t7.setText(s2); repaint(); } public void itemStateChanged(ItemEvent e) { repaint(); } }
Output:-
Program 10(b) : Design a calculator based on AWT application. import java.awt.*; import java.awt.event.*; import java.applet.*; // public class CALCULATOR extends Applet implements ActionListener { TextField t1; Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0; Button add,sub,mul,div, eql, dot; String msg="",tmp; int a, b; public void init() { setLayout(null); t1=new TextField(20); b1=new Button("1"); b2=new Button("2"); b3=new Button("3"); b4=new Button("4"); b5=new Button("5"); b6=new Button("6"); b7=new Button("7");
b8=new Button("8"); b9=new Button("9"); b0=new Button("0"); add=new Button("+"); sub=new Button("-"); div=new Button("/"); mul=new Button("*"); dot=new Button("."); eql=new Button("="); add(t1); add(b7); add(b8); add(b9); add(div); add(b4); add(b5); add(b6); add(mul); add(b1); add(b2); add(b3); add(sub); add(dot); add(b0);
add(eql); add(add); t1.setBounds(30,30,200,40); b7.setBounds(30,80,44,44); b8.setBounds(82,80,44,44); b9.setBounds(134,80,44,44); b4.setBounds(30,132,44,44); b5.setBounds(82,132,44,44); b6.setBounds(134,132,44,44); b1.setBounds(30,184,44,44); b2.setBounds(82,184,44,44); b3.setBounds(134,184,44,44); dot.setBounds(30,236,44,44); b0.setBounds(82,236,44,44); eql.setBounds(134,236,44,44); add.setBounds(186,236,44,44); sub.setBounds(186,184,44,44); mul.setBounds(186,132,44,44); div.setBounds(186,80,44,44); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this);
b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); //b0.addActionListener(this); //b0.addActionListener(this); div.addActionListener(this); mul.addActionListener(this); add.addActionListener(this); sub.addActionListener(this); eql.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if (str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/")) { String str1 = t1.getText(); tmp=str; a = Integer.parseInt(str1); msg=""; } else if(str.equals("="))
{ String str2 = t1.getText(); b = Integer.parseInt(str2); int sum=0; if(tmp=="+") sum=a+b; else if(tmp=="-") sum=a-b; else if(tmp=="*") sum=a*b; else if(tmp=="/") sum=a/b; String str1=String.valueOf(sum); t1.setText(""+str1); msg=""; } else { //String ae.getActionCommand(); //str += ae.getActionCommand(); msg+=str; t1.setText(""+msg); } }
public void paint(Graphics g) { g.setColor(Color.cyan); g.fillRect(20,20,220,270); } }
OUTPUT :-
Program 10(c) :Design an AWT application to generate result marks sheet.
import java.awt.*;
import java.applet.*; import java.awt.event.*; /* */ public class Marksheet extends Applet implements ActionListener,ItemListener { String s1,s2,s3; TextField t3,t4,t5,t6,t7; Button tot,avg; Checkbox c1,c2,c3,c4,m,f; CheckboxGroup cbg; Panel p1,p2,p3,p4; public void init() { s3=" "; tot=new Button("Total"); avg=new Button("Average"); c1=new Checkbox("MCA",true); c2=new Checkbox("Msc Comp"); c3=new Checkbox("MSIT"); c4=new Checkbox("MSIS"); cbg=new CheckboxGroup(); m=new Checkbox("Male",cbg,false); f=new Checkbox("Female",cbg,true);
p1=new Panel(); p1.setLayout(new GridLayout(2,2)); p1.add(new Label("Student Number ")); p1.add(new TextField(5)); p1.add(new Label("Student Name ")); p1.add(new TextField(15)); add(p1); p2=new Panel(); p2.setLayout(new GridLayout(1,3)); p2.add(new Label("Gender")); p2.add(m); p2.add(f); add(p2); p3=new Panel(); p3.setLayout(new GridLayout(1,5)); p3.add(new Label("Degree")); p3.add(c1); p3.add(c2);
p3.add(c3);
p3.add(c4);
add(p3); p4=new Panel(); p4.setLayout(new GridLayout(6,2)); p4.add(new Label("Marks in JAVA")); t3=new TextField(3); p4.add(t3); p4.add(new Label("Marks in VB .Net")); t4=new TextField(3); p4.add(t4); p4.add(new Label("Marks In C")); t5=new TextField(3); p4.add(t5); p4.add(new Label("Total "));
t6=new TextField(3); p4.add(t6); p4.add(new Label(" Average")); t7=new TextField(3); p4.add(t7); p4.add(tot); p4.add(avg); tot.addActionListener(this); avg.addActionListener(this); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); c4.addItemListener(this); m.addItemListener(this); f.addItemListener(this); add(p4); } public void paint(Graphics g) { int no,m1,m2,m3,tot; float avg=0.0f; no=m1=m2=m3=tot=0; try { m1=Integer.parseInt(t3.getText()); m2=Integer.parseInt(t4.getText()); m3=Integer.parseInt(t5.getText());
} catch(Exception e) { } tot=m1+m2+m3; avg= tot/3; s1=String.valueOf(tot); s2=String.valueOf(avg); } public boolean action(Event e,Object o) { repaint(); return true; } public void actionPerformed(ActionEvent e) { s3=e.getActionCommand(); if(s3.equals("Total")) t6.setText(s1); if(s3.equals("Average")) t7.setText(s2); repaint(); }
Output