Vous êtes sur la page 1sur 26

# Java lab Program 1

1. /* 2. Even Odd Number Example 3. This Java Even Odd Number Example shows how to check if the given 4. number is even or odd. 5. */ 6. 7. public class FindEvenOrOddNumber { 8. 9. public static void main(String[] args) { 10. 11. //create an array of 10 numbers 12. int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10}; 13. 14. for(int i=0; i < numbers.length; i++){ 15. 16. /* 17. * use modulus operator to check if the number is even or odd. 18. * If we divide any number by 2 and reminder is 0 then the number is 19. * even, otherwise it is odd. 20. */ 21. 22. if(numbers[i]%2 == 0) 23. System.out.println(numbers[i] + " is even number."); 24. else 25. System.out.println(numbers[i] + " is odd number."); 26. 27. } 28. 29. } 30. } 31. 32. /* 33. Output of the program would be 34. 1 is odd number. 35. 2 is even number. 36. 3 is odd number. 37. 4 is even number. 38. 5 is odd number. 39. 6 is even number. 40. 7 is odd number. 41. 8 is even number. 42. 9 is odd number. 43. 10 is even number. 44. */

Program 2
/* Reverse Number using Java This Java Reverse Number Example shows how to reverse a given number. */ public class ReverseNumber { public static void main(String[] args) { //original number int number = 1234; int reversedNumber = 0; int temp = 0; while(number > 0){ //use modulus operator to strip off the last digit temp = number%10; //create the reversed number reversedNumber = reversedNumber * 10 + temp; number = number/10; } //output the reversed number System.out.println("Reversed Number is: " + reversedNumber); } /* }

Program 3
/* Java Factorial Using Recursion Example This Java example shows how to generate factorial of a given number using recursive function. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class JavaFactorialUsingRecursion { public static void main(String args[]) throws NumberFormatException, IOException{ System.out.println("Enter the number: ");

//get input from the user BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(br.readLine()); //call the recursive function to generate factorial int result= fact(a); System.out.println("Factorial of the number is: " + result); } static int fact(int b) { if(b <= 1) //if the number is 1 then return 1 return 1; else //else call the same function with the value - 1 return b * fact(b-1); } } /*

Program 4
1. /* 2. Swap Numbers Without Using Third Variable Java Example 3. This Swap Numbers Java Example shows how to 4. swap value of two numbers without using third variable 5. */ 6. 7. public class SwapElementsWithoutThirdVariableExample { 8. 9. public static void main(String[] args) { 10. 11. int num1 = 10; 12. int num2 = 20; 13. 14. System.out.println("Before Swapping"); 15. System.out.println("Value of num1 is :" 16. System.out.println("Value of num2 is :" 17. 18. //add both the numbers and assign it to 19. num1 = num1 + num2; 20. num2 = num1 - num2; 21. num1 = num1 - num2; 22. 23. System.out.println("Before Swapping"); 24. System.out.println("Value of num1 is :" 25. System.out.println("Value of num2 is :"

using java.

## + num1); +num2); first

+ num1); +num2);

26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39.

} } /* Output of Swap Numbers Without Using Third Variable example would be Before Swapping Value of num1 is :10 Value of num2 is :20 Before Swapping Value of num1 is :20 Value of num2 is :10 */

Program 5
1. /* 2. Java Bubble Sort Descending Order Example 3. This Java bubble sort example shows how to sort an array of int in descending 4. order using bubble sort algorithm. 5. */ 6. 7. public class BubbleSortDescendingOrder { 8. 9. public static void main(String[] args) { 10. 11. //create an int array we want to sort using bubble sort algorithm 12. int intArray[] = new int[]{5,90,35,45,150,3}; 13. 14. //print array before sorting using bubble sort algorithm 15. System.out.println("Array Before Bubble Sort"); 16. for(int i=0; i < intArray.length; i++){ 17. System.out.print(intArray[i] + " "); 18. } 19. 20. //sort an array in descending order using bubble sort algorithm 21. bubbleSort(intArray); 22. 23. System.out.println(""); 24. 25. //print array after sorting using bubble sort algorithm 26. System.out.println("Array After Bubble Sort"); 27. for(int i=0; i < intArray.length; i++){ 28. System.out.print(intArray[i] + " "); 29. } 30. 31. } 32. 33. private static void bubbleSort(int[] intArray) { 34.

## /* * In bubble sort, we basically traverse the array from

* to array_length - 1 position and compare the element with the next one. 38. * Element is swapped with the next element if the next element is smaller. 39. * 40. * Bubble sort steps are as follows. 41. * 42. * 1. Compare array[0] & array[1] 43. * 2. If array[0] < array [1] swap it. 44. * 3. Compare array[1] & array[2] 45. * 4. If array[1] < array[2] swap it. 46. * ... 47. * 5. Compare array[n-1] & array[n] 48. * 6. if [n-1] < array[n] then swap it. 49. * 50. * After this step we will have smallest element at the last index. 51. * 52. * Repeat the same steps for array[1] to array[n-1] 53. * 54. */ 55. 56. int n = intArray.length; 57. int temp = 0; 58. 59. for(int i=0; i < n; i++){ 60. for(int j=1; j < (n-i); j++){ 61. 62. if(intArray[j-1] < intArray[j]){ 63. //swap the elements! 64. temp = intArray[j-1]; 65. intArray[j-1] = intArray[j]; 66. intArray[j] = temp; 67. } 68. 69. } 70. } 71. 72. } 73. } 74. 75. /* 76. Output of the Bubble Sort Descending Order Example would be 77. 78. Array Before Bubble Sort 79. 5 90 35 45 150 3 80. Array After Bubble Sort 81. 150 90 45 35 5 3 82. 83. */

Program 6

1. /* 2. Java boolean Example 3. This Java Example shows how to declare and use Java primitive boolean variable 4. inside a java class. 5. */ 6. 7. public class JavaBooleanExample { 8. 9. public static void main(String[] args) { 10. 11. /* 12. * boolean is simple Java type which can have only of two values; true or false. 13. * All rational expressions retrun this type of value. 14. * 15. * Declare boolean varibale as below 16. * 17. * boolean <variable name> = <default value>; 18. * 19. * here assigning default value is optional. 20. */ 21. 22. boolean b1 = true; 23. boolean b2 = false; 24. boolean b3 = (10 > 2)? true:false; 25. 26. System.out.println("Value of boolean variable b1 is :" + b1); 27. System.out.println("Value of boolean variable b2 is :" + b2); 28. System.out.println("Value of boolean variable b3 is :" + b3); 29. } 30. } 31. 32. /* 33. Output would be 34. Value of boolean variable b1 is :true 35. Value of boolean variable b2 is :false 36. Value of boolean variable b3 is :true 37. */

Program 7
1. /* 2. Java byte Example 3. This Java Example shows how to declare and use Java primitive byte variable 4. inside a java class. 5. */ 6. 7. public class JavaByteExample { 8. 9. public static void main(String[] args) {

10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.

/* * byte is smallest Java integer type. * byte is 8 bit signed type ranges from 128 to 127. * byte is mostly used when dealing with raw data like * binary file. * * Declare byte varibale as below * * byte <variable name> = <default value>; * * here assigning default value is optional. */ byte b1 = 100; byte b2 = 20;

b1); b2); } }

## System.out.println("Value of byte variable b1 is :" + System.out.println("Value of byte variable b1 is :" +

/* Output would be Value of byte variable b1 is :100 Value of byte variable b1 is :20 */

Program 8
1. /* 2. Java Final variable example 3. This Java Example shows how to declare and use final variable 4. a java class. 5. */ 6. 7. 8. public class FinalVariableExample { 9. 10. public static void main(String[] args) { 11. 12. /* 13. * Final variables can be declared using final 14. * Once created and initialized, its value can changed. 15. */ 16. final int hoursInDay=24; 17. 18. //This statement will not compile. Value can't changed. 19. //hoursInDay=12; 20. in

keyword. not be

be

5); } }

## /* Output would be Hours in 5 days = 120 */

Program 9
//Program for counting no. of Chars, Words and Lines in a file. import java.lang.*; import java.io.*; import java.util.*; class WordCount { public static void main(String arg[]) throws Exception { int char_count=0; int word_count=0; int line_count=0; String s; StringTokenizer st; BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter filename : "); s=buf.readLine(); buf=new BufferedReader(new FileReader(s)); while((s=buf.readLine())!=null) {

line_count++; st=new StringTokenizer(s," ,;:."); while(st.hasMoreTokens()) { word_count++; s=st.nextToken(); char_count+=s.length(); } } System.out.println("Character Count : "+char_count); System.out.println("Word Count : "+word_count); System.out.println("Line Count : "+line_count); buf.close(); } }

Program 10 //Program to check the input characcter for uppercase, lowercase, no. of digits and
other characters.

import java.io.*;

class InputDiagnosis{

## public static void main(String args[]) throws IOException {

char ch; int digit=0; int upper=0; int lower=0; int other=0;

System.out.println("

do{

## }while(ch !=' ');

System.out.println("No Of Digits:" +digit); System.out.println("No Of Uppercase Characters:" +upper); System.out.println("No Of Lowercase Characters:" +lower); System.out.println("No Of Other Characters:" +other);

} }

Program 11 //Set the foreground and background color to the text area.
import java.awt.*; import java.awt.event.*; import java.applet.*;

class colopat extends Frame { Checkbox r,g,b; Checkbox m,y,gr,p,w,bl,c; TextArea ta; Checkbox r1,g1,b1; Checkbox m1,y1,gr1,p1,w1,bl1,c1; Label ba,fo; Panel pa1,p2,p3;

colopat() { setSize(800,600);

## CheckboxGroup cbg=new CheckboxGroup();

r=new Checkbox("red",cbg,false); g=new Checkbox("green",cbg,false); b=new Checkbox("blue",cbg,false); m=new Checkbox("megenta",cbg,false); y=new Checkbox("yellow",cbg,false); gr=new Checkbox("grey",cbg,false); p=new Checkbox("pink",cbg,false); w=new Checkbox("white",cbg,false);

## bl=new Checkbox("black",cbg,true); c=new Checkbox("cyan",cbg,false); ba=new Label("BACKGROUND COLORS",Label.CENTER); ba.setBackground(Color.pink);

CheckboxGroup cbg1=new CheckboxGroup(); r1=new Checkbox("red",cbg1,false); g1=new Checkbox("green",cbg1,false); b1=new Checkbox("blue",cbg1,false); m1=new Checkbox("megenta",cbg1,false); y1=new Checkbox("yellow",cbg1,false); gr1=new Checkbox("grey",cbg1,false); p1=new Checkbox("pink",cbg1,false); w1=new Checkbox("white",cbg1,false); bl1=new Checkbox("black",cbg1,true); c1=new Checkbox("cyan",cbg1,false); fo=new Label("FOREGROUND COLORS"); fo.setBackground(Color.pink);

setVisible(true); }

## class CheckBoxHandler implements ItemListener { colopat cp;

CheckBoxHandler(colopat cp) { this.cp=cp; } public void itemStateChanged(ItemEvent ie) { if(cp.r.getState()) cp.ta.setBackground(Color.red); else if(cp.g.getState()) cp.ta.setBackground(Color.green); else if(cp.b.getState()) cp.ta.setBackground(Color.blue); else if(cp.m.getState()) cp.ta.setBackground(Color.magenta); else if(cp.y.getState()) cp.ta.setBackground(Color.yellow); else if(cp.gr.getState()) cp.ta.setBackground(Color.lightGray); else if(cp.bl.getState()) cp.ta.setBackground(Color.black); else if(cp.w.getState()) cp.ta.setBackground(Color.white); else if(cp.p.getState()) cp.ta.setBackground(Color.pink); else cp.ta.setBackground(Color.cyan);

if(cp.r1.getState()) cp.ta.setForeground(Color.red); else if(cp.g1.getState()) cp.ta.setForeground(Color.green); else if(cp.b1.getState()) cp.ta.setForeground(Color.blue); else if(cp.m1.getState()) cp.ta.setForeground(Color.magenta); else if(cp.y1.getState()) cp.ta.setForeground(Color.yellow); else if(cp.gr1.getState()) cp.ta.setForeground(Color.lightGray); else if(cp.bl1.getState()) cp.ta.setForeground(Color.black); else if(cp.w1.getState()) cp.ta.setForeground(Color.white); else if(cp.p1.getState()) cp.ta.setForeground(Color.pink); else cp.ta.setForeground(Color.cyan); } }

## this.cp=cp; } public void windowClosing(WindowEvent e) { System.exit(0); } }

Program 12
be /* Read File Using Java BufferedInputStream Example. This example shows how to read a file using available and read methods of Java BufferedInputStream.

*/ import java.io.*; public class ReadFileUsingBufferedInputStream { public static void main(String[] args) { //create file object File file = new File("C://FileIO//ReadFile.txt"); BufferedInputStream bin = null; try { //create FileInputStream object FileInputStream fin = new FileInputStream(file); //create object of BufferedInputStream bin = new BufferedInputStream(fin); /* * BufferedInputStream has ability to buffer input into * internal buffer array. * * available() method returns number of bytes that can * read from underlying stream without blocking. */ //read file using BufferedInputStream while( bin.available() > 0 ){ } } System.out.print((char)bin.read());

catch(FileNotFoundException e) { System.out.println("File not found" + e); } catch(IOException ioe) { System.out.println("Exception while reading the file " + ioe); } finally { //close the BufferedInputStream using close method try{ if(bin != null) bin.close(); }catch(IOException ioe) { System.out.println("Error while closing the stream : " + ioe); } } } } /*

Program 13

1. /* 2. Read int from file using DataInputStream 3. This Java example shows how to read a Java integer primitive value from file using 4. readInt method of Java DataInputStream class. 5. */ 6. 7. import java.io.DataInputStream; 8. import java.io.FileInputStream; 9. import java.io.FileNotFoundException; 10. import java.io.IOException; 11. 12. public class ReadIntFromFile { 13. 14. public static void main(String[] args) { 15. 16. String strFilePath = "C://FileIO//readInt.txt"; 17. 18. try 19. { 20. //create FileInputStream object 21. FileInputStream fin = new FileInputStream(strFilePath); 22.

23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. } 57. }

/* * To create DataInputStream object, use * DataInputStream(InputStream in) constructor. */ DataInputStream din = new DataInputStream(fin); /* * To read a Java integer primitive from file, use * byte readInt() method of Java DataInputStream class. * * This method reads 4 bytes and returns it as a int value. */ int i = din.readInt(); System.out.println("int : " + i); /* * To close DataInputStream, use * void close() method. */ din.close(); } catch(FileNotFoundException fe) { System.out.println("FileNotFoundException : " + fe); } catch(IOException ioe) { System.out.println("IOException : " + ioe); }

Program 14
1. /* 2. Read file using FileInputStream 3. This example shows how to read a file using Java FileInputStream class. 4. FileInputStream is used to read binary content of the file and 5. return bytes of data. 6. */ 7. import java.io.*; 8. 9. public class ReadStringFromFile { 10. 11. public static void main(String[] args) { 12. 13. //create file object 14. File file = new File("C://FileIO//ReadString.txt"); 15. 16. int ch;

## 72. 73. 74. 75. 76. 77. 78.

/* Output would be File contents : This file is a demonstration of how to read a file using Java FileInputStream. 79. */

Program 15
1. /* 2. Create Number counter in an Applet using Thread Example 3. This Java example shows how to create number counter using Java Thread and 4. Applet classes. 5. */ 6. 7. 8. import java.applet.Applet; 9. import java.awt.Dimension; 10. import java.awt.Font; 11. import java.awt.FontMetrics; 12. import java.awt.Graphics; 13. 14. /* 15. <applet code = "UsingRepaintAndThreadExample" width = 500 height = 300> 16. </applet> 17. */ 18. 19. /* 20. Using paint() method we can draw strings, shapes or images. 21. But when applets that use threads commonly need to update the display 22. (ex. Animation or simulation). 23. 24. You cannot invoke the paint method directly to update the display. 25. The reason is that the JVM schedules a number of important tasks. Updating 26. the dispaly is one of these. The JVM decides when the screen can be updated. 27. 28. Therefore, your applet must invoke the repaint() method to request 29. an update of the applet display. When the JVM determines that it is 30. appropriate to perform this work, it calls the update method. 31. 32. The default implementation of the update() method clears the applet 33. display with the background color and then invokes the paint() method.

34. */ 35. 36. public class UsingRepaintAndThreadExample extends Applet implements Runnable{ 37. int counter; 38. Thread t; 39. 40. public void init(){ 41. 42. counter = 0; 43. t = new Thread(this); 44. t.start(); 45. } 46. 47. public void run(){ 48. 49. try{ 50. 51. while(true){ 52. repaint(); 53. Thread.sleep(1000); 54. ++counter; 55. } 56. } 57. catch(Exception e){ 58. } 59. } 60. 61. public void paint(Graphics g){ 62. 63. g.setFont(new Font("Serif",Font.BOLD,30)); 64. FontMetrics fm = g.getFontMetrics(); 65. String s = "" + counter; 66. Dimension d = getSize(); 67. int x = d.width/2 - fm.stringWidth(s)/2; 68. int y = d.height/2; 69. g.drawString(s,x,y); 70. } 71. }

Program 16
1. /* 2. Draw 3D Rectangle & Square in Applet Window Example 3. This java example shows how to draw 3-D rectangles and squares in an applet 4. window using draw3DRect method of Graphics class. It also shows how to 5. draw a filled 3-D rectangles and squares. 6. */ 7. 8. /* 9. <applet code="Draw3DRectanglesExample" width=200 height=200> 10. </applet> 11. */ 12.

13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Draw3DRectanglesExample extends Applet{ public void paint(Graphics g){

g.setColor(Color.green); /* * To draw a 3-D rectangle in an applet window use, * void draw3DRect(int x1,int y1, int width, int height, boolean raised) 26. * method. 27. * 28. * This method draws a 3-D rectangle of specified width and 29. * height at (x1,y1) 30. */ 31. 32. //this will draw a 3-D rectangle of width 50 & height 100 at (10,10) 33. g.draw3DRect(10,10,50,100,true); 34. 35. /* 36. * If you speficy same width and height, the draw3DRect method 37. * will draw a 3-D square! 38. */ 39. 40. //this will draw a 3-D square 41. g.draw3DRect(100,100,50,50,true); 42. 43. g.setColor(Color.orange); 44. 45. /* 46. * To draw a filled 3-D rectangle in an applet window use, 47. * void fill3DRect(int x1,int y1, int width, int height, boolean raised) 48. * method. 49. * 50. * This method draws a filled 3-D rectangle of specified width and 51. * height at (x1,y1) 52. */ 53. 54. //this will draw a filled 3-D rectangle of width 50 & height 100 at (10,10) 55. g.fill3DRect(10,150,50,100,true); 56. 57. /* 58. * If you speficy same width and height, the fill3DRect method 59. * will draw a filled 3-D square! 60. */

## //this will draw a filled 3-D square g.fill3DRect(100,200,50,50,true); }

Program 18
1. /* 2. Display Image in an Applet Example 3. This Java example shows how to display an image using drawImage method 4. of an Java Graphics class. 5. */ 6. 7. 8. import java.applet.Applet; 9. import java.awt.Graphics; 10. import java.awt.Image; 11. 12. /* 13. <applet code = "DisplayImageExample" width = 500 height = 300> 14. <param name = "Image1" value = "one.jpg"> 15. <param name = "Image2" value = "two.jpg"> 16. </applet>

17. */ 18. 19. public class DisplayImageExample extends Applet 20. { 21. Image img1, img2; 22. 23. public void init(){ 24. 25. img1 = getImage(getDocumentBase(), getParameter("Image1")); 26. img2 = getImage(getDocumentBase(), getParameter("Image2")); 27. } 28. 29. public void paint(Graphics g){ 30. 31. //display an image using drwaImage method of Graphics class. 32. g.drawImage(img1, 0,0,this); 33. g.drawImage(img2, 100,100,this); 34. } 35. 36. }