You are on page 1of 35

JavaPrograms 1.

Write a java program that accepts a string from command line and display on separate line in reverse order. class Revstring { public static void main(String args[]) { int i=0; String name=args[0]; int a=name.length(); System.out.println(String length is +a); char ch[]=new char[name.length()]; for(char ch1:name.toCharArray()) { ch[i]=ch1; i++; } for(int j=name.length()-1;j>=0;j) { System.out.println(ch[j]); } } } Output: C:\javap>java Revstring kuldeep String length is 7 p e e d l u k 2. Write a java program that accepts 5 numbers from command line. If of the number is odd then throw custom exception odd Exception and count such invalid number. import java.lang.Exception; class OddException extends Exception { OddException(String message,int a) { System.out.println(message); System.out.println(invalid number is + a); } } class Oddnumber { public static void main(String args[]) { MuthayammalEngineeringCollege each character

JavaPrograms Integer n[]=new Integer[5]; int j=0; for(int i=0;i<5;i++) { try { n[i]=Integer.valueOf(args[i]); if(n[i]%2!=0) { j++; throw new OddException(Number is odd,n[i]); } } catch(OddException e) { System.out.println(Caught my exception); } } System.out.println(Invalid numbers are: + j); } } Output: C:\javap>java Oddnumber 1 2 3 4 5 Number is odd invalid number is1 Caught my exception Number is odd invalid number is3 Caught my exception Number is odd invalid number is5 Caught my exception Invalid numbers are: 3 3. Write a java program that generates 10 random double numbers and store them in a file read the file and display the numbers, sum, avg, max and min. import java.io.*; import java.*; class f1 { public static void main(String args[]) throws Exception { double j,sum=0,avg,min=0,max=0; double a[]=new double[10]; FileWriter fw=new FileWriter(args[0]); FileReader fr=new FileReader(args[0]); for(int i=0;i<10;i++) { MuthayammalEngineeringCollege

JavaPrograms double random = 9*Math.random()+1; a[i]=random; fw.write(random+\n); sum+=random; } fw.close(); avg=sum/10; while((j=fr.read())!=-1) { System.out.print((char)j); } fr.close(); for(int i=0;i<9;i++) { max=a[i]; for(int p=1;p<10;p++) { if(max<a[p]) { max=a[p]; } } } for(int i=0;i<9;i++) { min=a[i]; for(int p=1;p<10;p++) { if(min>a[p]) { min=a[p]; } } } System.out.println(Sum is + sum); System.out.println(Avg is + avg); System.out.println(Max is + max); System.out.println(Min is + min); } } Output: C:\javap>java f1 abc.txt 2.209709886559878 5.984398650931333 3.045257925274372 4.3979117776743095 8.240661111558094 1.9854587871749279 2.1532045098349104 MuthayammalEngineeringCollege

JavaPrograms 6.015997514603092 3.3560207195291305 1.7869223497040538 Sum is39.175543232844106 Avg is3.9175543232844108 Max is8.240661111558094 Min is1.7869223497040538 4. write java program to take the string from the user interactively (i.e.; by scanning) and check whether it is palindrome or not. import java.io.*; class Palindrome { public static void main(String args[]) throws Exception { DataInputStream di = new DataInputStream(System.in); String s1 = di.readLine(); String s2="; int i=s1.length(); int j=0,p=0; char a[]=new char[i]; char rev[]=new char[i]; for(char ch:s1.toCharArray()) { a[j]=ch; j++; } for(j=i-1;j>=0;j) { rev[p]=a[j]; s2=s2+rev[p]; p++; } System.out.println(s2); if(s1.equals(s2)) { System.out.println(String is palindrome); } else { System.out.println(String is not palindrome); } } } Output: C:\javap>java Palindrome nayan nayan String is palindrome MuthayammalEngineeringCollege

JavaPrograms

5. write a java program that take string from user and validate it. The string should be at least 6 characters long. It must start with alphabet and should contain at least one digit. Display an appropriate validation messages. class Valid { public static void main(String args[]) { String s=args[0]; int len=s.length(); int i=0; char a=s.charAt(0); if(len>6 && Character.isLetter(a)) { for(char ch:s.toCharArray()) { if(Character.isDigit(ch)) { i++; } } if(i>0) { System.out.println(valid string); } else { System.out.println(Enter valid string with digit); } } else { System.out.println(Pls enter valid string); } } } Output: C:\javap>java Valid Kuldeep1 valid string 6. Write JAVA program that creates three different classes in 3 different packages. And access them from default package. All the 3 packages should be at the same level. Package1: package package1; public class classA { public void displayA() MuthayammalEngineeringCollege

JavaPrograms { System.out.println(Class A); } } Package2: package package2; public class classB { public void displayB() { System.out.println(Class B); } } Package3: package package3; public class classC { public void displayC() { System.out.println(Class C); } } Default: import package1.classA; import package2.classB; import package3.classC; class Default { public static void main(String args[]) { classA A=new classA(); classB B=new classB(); classC C=new classC(); A.displayA(); B.displayB(); C.displayC(); } }

Output: C:\javap>java Default Class A Class B Class C MuthayammalEngineeringCollege

JavaPrograms

7. Write JAVA program to scan 3 integer values from users.(Not through Command line). And display the minimum using conditional operator. import java.io.*; class min { public static void main(String args[]) throws Exception { int a[]=new int[3]; int min; for(int i=0;i<3;i++) { DataInputStream di = new DataInputStream(System.in); a[i] = Integer.parseInt(di.readLine()); } min=((a[0]<a[1]) & (a[0]<a[2]))?a[0]:((a[1]<a[2])?a[1]:a[2]); System.out.println(Min is + min); } } Output: C:\javap>java min 10 9 11 Min is 9 8. Write JAVA program to input n integer numbers from the command line, store them in array and sort them. Also handle the different exception possible to be thrown during execution. import java.*; class sortno { public static void main(String args[]) { int size=args.length; double data[]=new double[size]; int i,j; double temp=0; try { for(i=0;i<size;i++) { data[i]=Double.parseDouble(args[i]); } for(i=0;i<size;i++) { for(j=i+1;j<size;j++) MuthayammalEngineeringCollege

JavaPrograms { if(data[i]>data[j]) { temp=data[i]; data[i]=data[j]; data[j]=temp; } } } for(i=0;i<size;i++) { System.out.println(data[i]+ ); } } catch(NumberFormatException e) { System.out.println(Pls enter valid number); } } } Output: C:\javap>java sortno 2.1 3.2 2.19 3.20 2.1 2.19 3.2 3.2 9. Write JAVA program that accepts marks of 5 subjects from command line and display the average. If any value is not between 0 and 100 then throw custom exception RangeException and handle it . import java.lang.Exception; class RangeException extends Exception { RangeException(String message) { System.out.println(message); } } class Result { public static void main(String args[]) { int size=args.length; int i; double m[]=new double[size]; double sum=0,avg; try { MuthayammalEngineeringCollege

JavaPrograms for(i=0;i<size;i++) { m[i]=Double.parseDouble(args[i]); if(m[i]<0 || m[i]>100) { throw new RangeException(Pls enter valid marks in range 0-100); } sum+=m[i]; } avg=sum/5; System.out.println(Average is + avg); } catch(RangeException e) { System.out.println(Exception caught); } } } Output: C:\javap>java Result 12 111 -1 11 11 Pls enter valid marks in range 0-100 Exception caught

10 Write JAVA program to take the directory name as command line argument. Check whether it is valid existing directory or not. It is a valid directory then display the names all files that contains at least one a character in its name. import java.io.*; import java.util.*; class Program10 { public static void main(String args[]) { File s=new File(args[0]); if(s.isDirectory()) { System.out.println(yes); } else { System.out.println(no); } } } Output: C:\javap>java Program10 package1 MuthayammalEngineeringCollege

JavaPrograms Yes

16.Write a java program to scan two strings interactively(i.e. by scanning), and display the result of their comparison.(i.e. smaller, greater or equal). import java.io.*; class Strcompare { public static void main(String args[]) throws Exception { String s1,s2; DataInputStream di = new DataInputStream(System.in); s1=di.readLine(); s2=di.readLine(); if(s1.compareTo(s2)<0) { System.out.println(String1 is smaller than String2); } else if(s1.compareTo(s2)>0) { System.out.println(String2 is smaller than String1); } else { System.out.println(String1 is equal to String2); } } } Output: C:\javap>java Strcompare abcd abc String2 is smaller than String1 17. Write a java applet that draws the pentagon filled with random colour. The co ordinates of the pentagon should be passed as parameters. import java.awt.*; import java.applet.*; public class Poly extends Applet { int x1[]={20,120,220,20}; int y1[]={20,120,20,20}; int n1=4; MuthayammalEngineeringCollege

JavaPrograms int x2[]={120,220,220,120}; int y2[]={120,20,220,120}; int n2=4; public void paint(Graphics g) { g.drawPolygon(x1,y1,n1); g.fillPolygon(x2,y2,n2); } } 18. Write a java program That creates two threads using runnable interface. One thread should display Thread 1 at every thousand milliseconds and other should display Thread 2 at every 3000 milliseconds. class ThreadM extends Thread { public void run() { try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println(ThreadM); } } catch (InterruptedException ex) { ex.printStackTrace(); } } } class ThreadN extends Thread { public void run() { try { for (int i = 0; i < 20; i++) { Thread.sleep(3000); System.out.println(ThreadN); } } catch(InterruptedException ex) { ex.printStackTrace(); } } } class JoinDemo1 { public static void main(String args[]) { ThreadM tm = new ThreadM(); tm.start(); ThreadN tn = new ThreadN(); tn.start(); try { tm.join(); tn.join(); MuthayammalEngineeringCollege

JavaPrograms System.out.println(Both threads have finished); } catch (Exception e) { e.printStackTrace(); } } } Output: C:\javap>java JoinDemo1 ThreadM ThreadM ThreadM ThreadN ThreadM ThreadM ThreadN ThreadN ThreadN ThreadN Both threads have finished 19. Write a java program that accepts two integer numbers from command line and throws custom exceptions FactorException. If second number is not a Factor of 1st number. Also handle all other possible exceptions. import java.lang.Exception; class FactorException extends Exception { FactorException(String message) { System.out.println(message); } } class Fact1 { public static void main(String args[]) { int no=Integer.parseInt(args[0]); int ans=Integer.parseInt(args[1]); int fact=1; while(no>0) { fact=fact*no; no=no-1; } try { if(fact!=ans) { MuthayammalEngineeringCollege

JavaPrograms throw new FactorException(Pls enter valid Factor); } else { System.out.println(correct factor); } } catch(FactorException e) { System.out.println(Exception caught); } } } Output: C:\javap>java Fact1 4 22 Pls enter valid Factor Exception caught 20. Write a JAVA program that reads a text file and create a new text file with each letter convert to a lower case whether it is lower case or upper case. import java.io.*; class Lowercase { public static void main(String args[]) { File inFile=new File(args[0]); File outFile=new File(args[1]); FileReader ins=null; FileWriter outs=null; try { ins=new FileReader(inFile); outs=new FileWriter(outFile); int ch; while((ch=ins.read())!=-1) { ch=Character.toLowerCase(ch); outs.write(ch); } } catch (IOException e) { System.out.println(e); System.exit(-1); } finally { try MuthayammalEngineeringCollege

JavaPrograms { ins.close(); outs.close(); } catch (IOException e){} } } } Output: C:\javap>type abcs.txt KPV C:\javap>java Lowercase abcs.txt def.txt C:\javap>type def.txt kpv 22. Write a JAVA program that scans length of 3 sides of triangle from the user interactively ( Not through Command Line) and check whether it is right angle or not.(that is square of one side should be same as some of square of other two sides). import java.io.*; class Triangle { public static void main(String args[]) throws Exception { DataInputStream di=new DataInputStream(System.in); String s1=di.readLine(); String s2=di.readLine(); String s3=di.readLine(); int ab=Integer.parseInt(s1); int bc=Integer.parseInt(s2); int ac=Integer.parseInt(s3); int acs,abs,bcs; abs=ab*ab; bcs=bc*bc; acs=ac*ac; if(acs==(abs+bcs)) { System.out.println(It is right angle triangle); } else { System.out.println(It is not right angle triangle); } } } Output: C:\javap>java Triangle MuthayammalEngineeringCollege

JavaPrograms 5 12 13 It is right angle triangle 23. Write a JAVA program to take the string from the user interactively ( That is by scanning)and count total no. of upper case and lower case characters in it. import java.io.*; class Count { public static void main(String args[]) throws Exception { DataInputStream di=new DataInputStream(System.in); String s1=di.readLine(); int i=0,l=0,u=0; for(char ch:s1.toCharArray()) { if(Character.isUpperCase(ch)) { u++; } else { l++; } i++; } System.out.println(Upper cases are:+u); System.out.println(Lower cases are:+l); } } Output: C:\javap>java Count kulDEEP Upper cases are:4 Lower cases are:3 24. Write a java program to input n integer numbers from the command line and display highest and second highest number. Also handle the different exception possible to be thrown during execution. class Highest1 { public static void main(String args[]) { int i,j,max=0,max1=0; int size=args.length; int a[]=new int[size]; MuthayammalEngineeringCollege

JavaPrograms try { for(i=0;i<size;i++) { a[i]=Integer.parseInt(args[i]); } for(i=0;i<size;i++) { if(max<a[i]) { max=a[i]; } } for(i=0;i<size;i++) { if(max1<a[i] && a[i]<max) { max1=a[i]; } } System.out.println(max); System.out.println(max1); } catch(Exception e) { System.out.println(Pls enter valid values); } } } Output: C:\javap>java Highest 11 99 22 55 33 44 Maximum is99 Second maximum is55 25. Write a java program which takes 2 arguments a string and its length from command line. If the length of the string is not according to given one then throw the user defined LengthMatchException and handle it appropriately class LengthMatchException extends Exception { LengthMatchException(String message) { System.out.println(message); } } class Strlen { public static void main(String args[]) { String s1=args[0]; MuthayammalEngineeringCollege

JavaPrograms int len=Integer.parseInt(args[1]); int slen=s1.length(); try { if(slen!=len) { throw new LengthMatchException(Pls enter valid length for a String); } else { System.out.println(correct length); } } catch(LengthMatchException e) { System.out.println(Exception caught); } } } Output: C:\javap>java Strlen kpv 4 Pls enter valid length for a String Exception caught 26. Write a Java program to prompt the user for entering the name of the city. The string entered should be Ahmedabad. If user has entered valid string then program should terminate saying Good Bye. If user has not entered the valid string and then 2 more attempts are given. The comparison should not be case sensitive. import java.io.*; class Stringcomp { public static void main(String args[]) throws Exception { DataInputStream di=new DataInputStream(System.in); String s2=Ahmedabad; int i; for(i=0;i<2;i++) { String s1=di.readLine(); if(s1.equalsIgnoreCase(s2)) { System.out.println(Good bye); System.exit(1); } else { System.out.println(Pls enter valid string); } MuthayammalEngineeringCollege

JavaPrograms } } } Output: C:\javap>java Stringcomp ahmedabad Good bye

27. Create a program with overloading of area method which finds area of square and triangle. Crate necessary constructor too. class Square { int length,sqarea,ans; Square(int l) { length=l; ans=area(length); System.out.println(Area of square+ ans); } int area(int length) { sqarea=4*length; return(sqarea); } } class Triangle { int len,height,triarea,ans; Triangle(int l,int h) { len=l; height=h; ans=area(len,height); System.out.println(Area of triangle+ans); } int area(int len,int height) { triarea=(2*len)+height; return(triarea); } } class Area1 { MuthayammalEngineeringCollege

JavaPrograms public static void main(String args[]) { Square s=new Square(10); Triangle t=new Triangle(10,5); } } Output: C:\javap>java Area1 Area of square 40 Area of triangle 25

28. Write java program that generate 10 integer numbers and store them in file. It should also display last number by accessing directly. import java.io.*; import java.*; class f2 { public static void main(String args[]) throws Exception { int j; Integer a[]=new Integer[10]; FileWriter fw=new FileWriter(args[0]); FileReader fr=new FileReader(args[0]); for(int i=0;i<10;i++) { int random = (int)(10*Math.random()+1); a[i]=random; fw.write(random+\n); } fw.close(); while((j=fr.read())!=-1) { System.out.print((char)j); } fr.close(); } } Output: C:\javap>java f2 abc.txt 6 8 3 2 MuthayammalEngineeringCollege

JavaPrograms 2 10 9 9 7 4 29. Write a java program to scan a string from a command line and check whether string is lower case or not. class Lower { public static void main(String args[]) { String s; s=args[0]; int a=0; for(char ch:s.toCharArray()) { if(Character.isUpperCase(ch)) { System.out.println(Its not lower case string); System.exit(1); } else { a=1; } } if(a==1) { System.out.println(Its lower case string); } } } Output: C:\javap>java Lower kuldeep Its lower case string 30. Write a java program to find sum of 2 matrices A (3, 3) and B (3, 3). import java.io.*; class Addition { public static void main(String args[]) throws Exception { Integer a[][]=new Integer[3][3]; Integer b[][]=new Integer[3][3]; Integer ans[][]=new Integer[3][3]; int i,j; MuthayammalEngineeringCollege

JavaPrograms for(i=0;i<3;i++) { for(j=0;j<3;j++) { System.out.print(Enter a["+i+"]["+j+"]= ); DataInputStream di=new DataInputStream(System.in); a[i][j]=Integer.parseInt(di.readLine()); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { System.out.print(Enter b["+i+"]["+j+"]= ); DataInputStream di=new DataInputStream(System.in); b[i][j]=Integer.parseInt(di.readLine()); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { ans[i][j]=a[i][j]+b[i][j]; System.out.print(ans[i][j]+ ); } System.out.println(); } } } Output: C:\javap>java Addition Enter a[0][0]= 1 Enter a[0][1]= 5 Enter a[0][2]= 2 Enter a[1][0]= 3 Enter a[1][1]= 4 Enter a[1][2]= 1 Enter a[2][0]= 5 Enter a[2][1]= 2 Enter a[2][2]= 3 Enter b[0][0]= 4 Enter b[0][1]= 1 Enter b[0][2]= 5 Enter b[1][0]= 2 Enter b[1][1]= 3 Enter b[1][2]= 4 Enter b[2][0]= 1 Enter b[2][1]= 5 Enter b[2][2]= 2 567 MuthayammalEngineeringCollege

JavaPrograms 575 675 31. The abstract vehicle class has three sub class scooter, car, and truck. Each vehicle has different capacity, different numbers of tires and different colors. Instantiate different types of vehicle and their members. abstract class Vehicle { abstract void capacity(); abstract void nooftires(); abstract void colors(); } class scooter extends Vehicle { void capacity() { System.out.println(Scooter: capacity-100cc); } void nooftires() { System.out.println(Scooter: No of tires-2); } void colors() { System.out.println(Scooter: Colors-Blue,Black); } } class car extends Vehicle { void capacity() { System.out.println(Car: capacity-1100cc); } void nooftires() { System.out.println(Car: No of tires-4); } void colors() { System.out.println(Car: Colors-Red,Black); } } class truck extends Vehicle { void capacity() { System.out.println(Truck: capacity-6000cc); } void nooftires() { MuthayammalEngineeringCollege

JavaPrograms System.out.println(Truck: No of tires-8); } void colors() { System.out.println(Truck: Colors-Blue,Brown); } } class Vehi { public static void main(String args[]) { scooter s=new scooter(); car c=new car(); truck t=new truck(); s.capacity(); s.nooftires(); s.colors(); c.capacity(); c.nooftires(); c.colors(); t.capacity(); t.nooftires(); t.colors(); } } Output: C:\javap>java Vehi Scooter: capacity-100cc Scooter: No of tires-2 Scooter: Colors-Blue,Black Car: capacity-1100cc Car: No of tires-4 Car: Colors-Red,Black Truck: capacity-6000cc Truck: No of tires-8 Truck: Colors-Blue,Brown 32.Write a java program thread and using thread priority. class A extends Thread { public void run() { System.out.println(threadA started); for(int i=1;i<=2;i++) { System.out.println(\tFrom thread A : i= +i); } System.out.println(Exit from A); } } MuthayammalEngineeringCollege

JavaPrograms class B extends Thread { public void run() { System.out.println(threadB started); for(int j=1;j<=2;j++) { System.out.println(\tFrom thread B : j= +j); } System.out.println(Exit from B); } } class C extends Thread { public void run() { System.out.println(threadC started); for(int k=1;k<=2;k++) { System.out.println(\tFrom thread C : = +k); } System.out.println(Exit from C); } } class ThreadPriority { public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C(); threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority( )+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println(Start thread A); threadA.start(); System.out.println(Start thread B); threadB.start(); System.out.println(Start thread C); threadC.start(); System.out.println(end of main thread); } } Output: C:\javap>java ThreadPriority MuthayammalEngineeringCollege

JavaPrograms Start thread A Start thread B threadA started Start thread C threadB started From thread A : i= 1 threadC started end of main thread From thread B : j= 1 From thread A : i= 2 From thread C : = 1 From thread B : j= 2 Exit from A From thread C : = 2 Exit from B Exit from C

A Revised Version of Hello World


import java.io.*; class MyFirstProgram { /** Print a hello message */ public static void main(String[] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = "Instructor"; System.out.print("Give your name: "); try {name = in.readLine();} catch(Exception e) { System.out.println("Caught an exception!"); } System.out.println("Hello " + name + "!"); } }

A Java Program with Looping


class Fibonacci { // Print out the Fibonacci sequence for values < 50 public static void main(String[] args) { int lo = 1; int hi = 1; System.out.println(lo); while (hi < 50) { System.out.print(hi); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo)

MuthayammalEngineeringCollege

JavaPrograms
i.e., the old hi */ } }

A Java Class
class Point { public double x, y; public static Point origin = new Point(0,0); // This always refers to an object at (0,0) Point(double x_value, double y_value) { x = x_value; y = y_value; } public void clear() { this.x = 0; this.y = 0; } public double distance(Point that) { double xDiff = x - that.x; double yDiff = y - that.y; return Math.sqrt(xDiff * xDiff + yDiff * yDiff); } }

Extending a Class: Inheritance


class Pixel extends Point { Color color; public void clear() { super.clear(); color = null; } }

Interfaces
interface Lookup { /** Return the value associated with the name, or * null if there is no such value */ Object find(String name); } void processValues(String[] names, Lookup table) { for (int i = 0; i ! names.length; i++) { Object value = table.find(names[i]); if (value != null) processValue(names[i], value); } }

MuthayammalEngineeringCollege

JavaPrograms
class SimpleLookup implements Lookup { private String[] Names; private Object[] Values; public Object find(String name) { for (int i = 0; i < Names.length; i++) { if (Names[i].equals(name)) return Values[i]; } return null; // not found } // ... }

Creating Threads in Java


public class PingPONG extends Thread { private String word; // What word to print private int delay; // how long to pause public PingPONG(String whatToSay, int delayTime) { word = whatToSay; delay = delayTime; } public void run() { try { for (;;) { System.out.print(word + " "); sleep(delay); // wait until next time } } catch (InterruptedException e) { return; // end this thread; } } public static void main(String[] args) { new PingPONG("Ping", 33).start(); // 1/30 second new PingPONG("PONG",100).start(); // 1/10 second } }

Two Synchronization Methods


class Account { private double balance; Public Account(double initialDeposit) { balance = initialDeposit; } public synchronized double getBalance() { return balance; } public synchronized viod deposit(double amount) { balance += amont; } }

MuthayammalEngineeringCollege

JavaPrograms

/** make all elements in the array non-negative */ public static void abs(int[] values) { synchronized (values) { for (int i = 0; i < values.length; i++) { if (values[i] < 0) values[i] = -values[i]; } } }

Display Triangle as follow 1 24 369 4 8 12 16 ... N (indicates no. of Rows) */ class Output3{ public static void main(String args[]){ int n = Integer.parseInt(args[0]); for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ System.out.print((i*j)+" "); }
MuthayammalEngineeringCollege

JavaPrograms

System.out.print("\n"); } } }

Display Triangle as follow 0 10 101 0 1 0 1 */ class Output2{ public static void main(String args[]){ for(int i=1;i<=4;i++){ for(int j=1;j<=i;j++){ System.out.print(((i+j)%2)+" "); } System.out.print("\n"); } } }

Display Triangle as follow : BREAK DEMO. 1


MuthayammalEngineeringCollege

JavaPrograms

23 456 7 8 9 10 ... N */ class Output1{ public static void main(String args[]){ int c=0; int n = Integer.parseInt(args[0]); loop1: for(int i=1;i<=n;i++){ loop2: for(int j=1;j<=i;j++){ if(c!=n){ c++; System.out.print(c+" "); } else break loop1; } System.out.print("\n"); } } }

Write a program to find average of consecutive N Odd no. and Even no. */ class EvenOdd_Avg{
MuthayammalEngineeringCollege

JavaPrograms

public static void main(String args[]){ int n = Integer.parseInt(args[0]); int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0; while(n > 0){ if(n%2==0){ cntEven++; sumEven = sumEven + n; } else{ cntOdd++; sumOdd = sumOdd + n; } n--; } int evenAvg,oddAvg; evenAvg = sumEven/cntEven; oddAvg = sumOdd/cntOdd; System.out.println("Average of first N Even no is "+evenAvg); System.out.println("Average of first N Odd no is "+oddAvg);

} }

MuthayammalEngineeringCollege

JavaPrograms

Write a program to generate Harmonic Series. Example : Input - 5 Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */ class HarmonicSeries{ public static void main(String args[]){ int num = Integer.parseInt(args[0]); double result = 0.0; while(num > 0){ result = result + (double) 1 / num; num--; } System.out.println("Output of Harmonic Series is "+result); } }

switch case demo Example : Input - 124 Output - One Two Four */

class SwitchCaseDemo{
MuthayammalEngineeringCollege

JavaPrograms

public static void main(String args[]){ try{ int num = Integer.parseInt(args[0]); int n = num; //used at last time check int reverse=0,remainder; while(num > 0){ remainder = num % 10; reverse = reverse * 10 + remainder; num = num / 10; } String result=""; //contains the actual output while(reverse > 0){ remainder = reverse % 10; reverse = reverse / 10; switch(remainder){ case 0 : result = result + "Zero "; break; case 1 : result = result + "One "; break; case 2 : result = result + "Two ";

MuthayammalEngineeringCollege

JavaPrograms

break; case 3 : result = result + "Three "; break; case 4 : result = result + "Four "; break; case 5 : result = result + "Five "; break; case 6 : result = result + "Six "; break; case 7 : result = result + "Seven "; break; case 8 : result = result + "Eight "; break; case 9 : result = result + "Nine "; break; default:

MuthayammalEngineeringCollege

JavaPrograms

result=""; } } System.out.println(result); }catch(Exception e){ System.out.println("Invalid Number Format"); } } }

MuthayammalEngineeringCollege

You might also like