+ All Categories
Home > Documents > Java Examples

Java Examples

Date post: 16-Oct-2014
Category:
Upload: venucseindiatimescom
View: 77 times
Download: 0 times
Share this document with a friend
23
Java Examples 1. /* 2. Calculate Circle Area using Java Example 3. This Calculate Circle Area using Java Example shows how to calculate 4. area of circle using it's radius. 5. */ 6. 7. import java.io.BufferedReader; 8. import java.io.IOException; 9. import java.io.InputStreamReader; 10. 11. public class CalculateCircleAreaExample { 12. 13. public static void main(String[] args){ 14. 15. int radius = 0; 16. System.out.println("Please enter radius of a circle"); 17. 18. try 19. { 20. //get the radius from console 21. BufferedReader br = new BufferedReader(newInputStreamReader(System.i n)); 22. radius = Integer.parseInt(br.readLine()); 23. } 24. //if invalid value was entered 25. catch(NumberFormatException ne) 26. { 27. System.out.println("Invalid radius value" + ne); 28. System.exit(0); 29. } 30. catch(IOException ioe) 31. { 32. System.out.println("IO Error :" + ioe); 33. System.exit(0); 34. } 35. 1
Transcript
Page 1: Java Examples

Java Examples

1. /*2.         Calculate Circle Area using Java Example3.         This Calculate Circle Area using Java Example shows how to calculate4.         area of circle using it's radius.5. */6.  7. import java.io.BufferedReader;8. import java.io.IOException;9. import java.io.InputStreamReader;10.  11.public class CalculateCircleAreaExample {12.  13.         public static void main(String[] args) {14.                15.                 int radius = 0;16.                 System.out.println("Please enter radius of a circle");17.                18.                 try19.                 {20.                         //get the radius from console21.                      

BufferedReader br = new BufferedReader(newInputStreamReader(System.in));22.                         radius = Integer.parseInt(br.readLine());23.                 }24.                 //if invalid value was entered25.                 catch(NumberFormatException ne)26.                 {27.                         System.out.println("Invalid radius value" + ne);28.                         System.exit(0);29.                 }30.                 catch(IOException ioe)31.                 {32.                         System.out.println("IO Error :" + ioe);33.                         System.exit(0);34.                 }35.                36.                 /*37.                  * Area of a circle is38.                  * pi * r * r39.                  * where r is a radius of a circle.40.                  */41.                42.                 //NOTE : use Math.PI constant to get value of pi43.                 double area = Math.PI * radius * radius;44.                45.                 System.out.println("Area of a circle is " + area);46.         }47. }

1

Page 2: Java Examples

48.  49. /*50.Output of Calculate Circle Area using Java Example would be51.Please enter radius of a circle52.1953.Area of a circle is 1134.114947945915254.*/

1. /*2.         Calculate Rectangle Area using Java Example3.         This Calculate Rectangle Area using Java Example shows how to calculate4.         area of Rectangle using it's length and width.5. */6.  7. import java.io.BufferedReader;8. import java.io.IOException;9. import java.io.InputStreamReader;10.  11.public class CalculateRectArea {12.  13.         public static void main(String[] args) {14.                15.                 int width = 0;16.                 int length = 0;17.                        18.                 try19.                 {20.                         //read the length from console21.                      

BufferedReader br = new BufferedReader(newInputStreamReader(System.in));22.                        23.                         System.out.println("Please enter length of a rectangle");24.                         length = Integer.parseInt(br.readLine());25.  26.                         //read the width from console27.                         System.out.println("Please enter width of a rectangle");28.                         width = Integer.parseInt(br.readLine());29.                        30.                        31.                 }32.                 //if invalid value was entered33.                 catch(NumberFormatException ne)34.                 {35.                         System.out.println("Invalid value" + ne);36.                         System.exit(0);

2

Page 3: Java Examples

37.                 }38.                 catch(IOException ioe)39.                 {40.                         System.out.println("IO Error :" + ioe);41.                         System.exit(0);42.                 }43.                44.                 /*45.                  * Area of a rectangle is46.                  * length * width47.                 */48.                49.                 int area = length * width;50.                51.                 System.out.println("Area of a rectangle is " + area);52.         }53.                54. }55.  56. /*57.Output of Calculate Rectangle Area using Java Example would be58.Please enter length of a rectangle59.1060.Please enter width of a rectangle61.1562.Area of a rectangle is 15063.*/1. /*2.   Even Odd Number Example3.   This Java Even Odd Number Example shows how to check if the given4.   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 numbers12.                 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 is19.                          * even, otherwise it is odd.20.                          */21.                          22.                          if(numbers[i]%2 == 0)23.                                 System.out.println(numbers[i] + " is even number.");

3

Page 4: Java Examples

24.                          else25.                                 System.out.println(numbers[i] + " is odd number.");26.                                27.                 }28.                29.         }30. }31.  32. /*33.Output of the program would be34.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.*/

1. /*2.   Find Largest and Smallest Number in an Array Example3.   This Java Example shows how to find largest and smallest number in an4.   array.5. */6. public class FindLargestSmallestNumber {7.  8.         public static void main(String[] args) {9.                10.                 //array of 10 numbers11.                 int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};12.                

4

Page 5: Java Examples

13.                 //assign first element of an array to largest and smallest14.                 int smallest = numbers[0];15.                 int largetst = numbers[0];16.                17.                 for(int i=1; i< numbers.length; i++)18.                 {19.                         if(numbers[i] > largetst)20.                                 largetst = numbers[i];21.                         else if (numbers[i] < smallest)22.                                 smallest = numbers[i];23.                        24.                 }25.                26.                 System.out.println("Largest Number is : " + largetst);27.                 System.out.println("Smallest Number is : " + smallest);28.         }29. }30.  31. /*32.Output of this program would be33.Largest Number is : 9834.Smallest Number is : 2335.*/

1. /*2.   Java Factorial Example3.   This Java Factorial Example shows how to calculate factorial of4.   a given number using Java.5. */6.  7. public class NumberFactorial {8.  9.         public static void main(String[] args) {10.                11.                 int number = 5;12.                13.                 /*14.                  * Factorial of any number is !n.15.                  * For example, factorial of 4 is 4*3*2*1.16.                 */17.                18.                 int factorial = number;19.                20.                 for(int i =(number - 1); i > 1; i--)21.                 {22.                         factorial = factorial * i;23.                 }24.        25.                 System.out.println("Factorial of a number is " + factorial);

5

Page 6: Java Examples

26.         }27. }28.  29. /*30.Output of the Factorial program would be31.Factorial of a number is 12032.*/

1. /*2.   Reverse Number using Java3.   This Java Reverse Number Example shows how to reverse a given number.4. */5.  6. public class ReverseNumber {7.  8.         public static void main(String[] args) {9.                10.                 //original number11.                 int number = 1234;12.                 int reversedNumber = 0;13.                 int temp = 0;14.                15.                 while(number > 0){16.                        17.                         //use modulus operator to strip off the last digit18.                         temp = number%10;19.                        20.                         //create the reversed number21.                         reversedNumber = reversedNumber * 10 + temp;22.                         number = number/10;23.                          24.                 }25.                26.                 //output the reversed number27.                 System.out.println("Reversed Number is: " + reversedNumber);28.         }29. }30.  31. /*32.Output of this Number Reverse program would be33.Reversed Number is: 432134.*/

6

Page 7: Java Examples

1. /*2.         Swap Numbers Java Example3.         This Swap Numbers Java Example shows how to4.         swap value of two numbers using java.5. */6.  7. public class SwapElementsExample {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 :" + num1);16.                 System.out.println("Value of num2 is :" +num2);17.                18.                 //swap the value19.                 swap(num1, num2);20.         }21.  22.         private static void swap(int num1, int num2) {23.                24.                 int temp = num1;25.                 num1 = num2;26.                 num2 = temp;27.                28.                 System.out.println("After Swapping");29.                 System.out.println("Value of num1 is :" + num1);30.                 System.out.println("Value of num2 is :" +num2);31.                32.         }33. }34.  35. /*36.Output of Swap Numbers example would be37.Before Swapping38.Value of num1 is :1039.Value of num2 is :2040.After Swapping41.Value of num1 is :2042.Value of num2 is :1043.*/

7

Page 8: Java Examples

If else

1. /*2.         Compare Two Numbers Java Example3.         This Compare Two Numbers Java Example shows how to compare two numbers4.         using if else if statements.5. */6.  7. public class CompareTwoNumbers {8.  9.         public static void main(String[] args) {10.                11.                 //declare two numbers to compare12.                 int num1 = 324;13.                 int num2 = 234;14.                15.                 if(num1 > num2){16.                         System.out.println(num1 + " is greater than " + num2);17.                 }18.                 else if(num1 < num2){19.                         System.out.println(num1 + " is less than " + num2);20.                 }21.                 else{22.                         System.out.println(num1 + " is equal to " + num2);23.                 }24.         }25. }26.  27. /*28.Output of Compare Two Numbers Java Example would be29.324 is greater than 23430.*/

1. /*2.         Determine If Year Is Leap Year Java Example3.         This Determine If Year Is Leap Year Java Example shows how to4.         determine whether the given year is leap year or not.5. */6.  7. public class DetermineLeapYearExample {8.  9.         public static void main(String[] args) {10.                11.                 //year we want to check12.                 int year = 2004;13.                

8

Page 9: Java Examples

14.                 //if year is divisible by 4, it is a leap year15.                16.                 if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))17.                         System.out.println("Year " + year + " is a leap year");18.                 else19.                         System.out.println("Year " + year + " is not a leap year");20.         }21. }22.  23. /*24.Output of the example would be25.Year 2004 is a leap year26.*/

1. /*2.   If Else-If statement Example3.   This Java Example shows how to use if else-if statement in Java program.4. */5.  6. public class IfElseIfElseExample {7.  8.   public static void main(String[] args) {9.    10.     /*11.      * If Else-if statement is used to execute multiple of actions based upon12.      * multiple conditions.13.      * Sysntax of If Else-If statement is14.      *15.      * if(<condition1>)16.      *   statement117.      * else if(<condition2>)18.      *   statement219.      * ..20.      * else21.      *   statement322.      *23.      * If <condition1> is true, statement1 will be executed, else if <condition2>24.      * is true statement2 is executed and so on. If no condition is true, then else25.      * statement will be executed.26.      */27.      28.      int i = 10;29.      30.      if(i > 100)31.        System.out.println("i is grater than 100");32.      else if(i > 50)33.        System.out.println("i is grater than 50");34.      else35.        System.out.println("i is less than 50");

9

Page 10: Java Examples

36.   }37. }38.  39. /*40.Output would be41. i is less than 5042.*/

Arrays

1. /*2.   Create List from Java Object Array Example3.   This java example shows how to create a List from an array of type Object using4.   asList method of Arrays class.5. */6.  7. import java.util.Arrays;8. import java.util.List;9. import java.util.Iterator;10.  11.public class CreateListFromObjectArrayExample {12.  13.   public static void main(String[] args) {14.     //create an array of type Object, in this case we will create String array15.     String[] strArray = new String[]{"Object","Array","Converted","To","List"};16.    17.     /*18.       To create List from an array of type Object use,19.       static List asList(Object[] objArray) method of Arrays class.20.      21.       This method returns a fixed sized list backed by original array.22.     */23.    24.     List list = Arrays.asList(strArray);25.    26.     //get an iterator27.     Iterator itr = list.iterator();28.    29.     //iterate through list created from Array30.     System.out.println("List created from an Array of type Object contains,");31.     while(itr.hasNext())32.       System.out.println(itr.next());33.    34.   }35. }36.  37. /*38.Output would be39.List created from an Array of type Object contains,

10

Page 11: Java Examples

40.Object41.Array42.Converted43.To44.List45.*/

Switch Case

1. /*2.         Free Flowing Switch Statement Example3.         This example shows how case statements are executed if break is4.         not used to terminate the execution of the statments.5. */6. public class FreeFlowingSwitchExample {7.  8.         public static void main(String[] args) {9.                10.                 /*11.                  * break statement is used to terminate the flow of12.                  * matching case statements. If break statement is13.                  * not specified, switch statement becomes free flowing and14.                  * all cases following matching case including default15.                  * would be executed.16.                  */17.                  18.                  int i=0;19.                  20.                  switch(i)21.                  {22.                         case 0:23.                                 System.out.println("i is 0");24.                                25.                         case 1:26.                                 System.out.println("i is 1");27.                                28.                         case 2:29.                                 System.out.println("i is 2");30.                                31.                         default:32.                                 System.out.println("Free flowing switch example!");33.                  }34.         }35. }36.  37. /*38.Output would be39. i is 040. i is 1

11

Page 12: Java Examples

41. i is 242.Free flowing switch example!43.*/

1. /*2.         Java Pyramid 1 Example3.         This Java Pyramid example shows how to generate pyramid or triangle like4.         given below using for loop.5.        6.         *7.         **8.         ***9.         ****10.         *****11.*/12.  13.public class JavaPyramid1 {14.  15.         public static void main(String[] args) {16.                17.                 for(int i=1; i<= 5 ;i++){18.                        19.                         for(int j=0; j < i; j++){20.                                 System.out.print("*");21.                         }22.                        23.                         //generate a new line24.                         System.out.println("");25.                 }26.         }27. }28.  29. /*30.Output of the above program would be31.*32.**33.***34.****35.*****36.*/

1. /*2.         Java Pyramid 2 Example3.         This Java Pyramid example shows how to generate pyramid or triangle like4.         given below using for loop.

12

Page 13: Java Examples

5.        6.         *****7.         ****8.         ***9.         **10.         *11.*/12.  13.public class JavaPyramid2 {14.  15.         public static void main(String[] args) {16.                17.                 for(int i=5; i>0 ;i--){18.                        19.                         for(int j=0; j < i; j++){20.                                 System.out.print("*");21.                         }22.                        23.                         //generate a new line24.                         System.out.println("");25.                 }26.         }27. }28.  29. /*30.  31.Output of the example would be32.*****33.****34.***35.**36.*37.  38.*/

1. /*2.         Java Pyramid 3 Example3.         This Java Pyramid example shows how to generate pyramid or triangle like4.         given below using for loop.5.        6.         *7.         **8.         ***9.         ****10.         *****11.         *****12.         ****

13

Page 14: Java Examples

13.         ***14.         **15.         *16.*/17.public class JavaPyramid3 {18.  19.         public static void main(String[] args) {20.                21.                 for(int i=1; i<= 5 ;i++){22.                        23.                         for(int j=0; j < i; j++){24.                                 System.out.print("*");25.                         }26.                        27.                         //generate a new line28.                         System.out.println("");29.                 }30.                31.                 //create second half of pyramid32.                 for(int i=5; i>0 ;i--){33.                        34.                         for(int j=0; j < i; j++){35.                                 System.out.print("*");36.                         }37.                        38.                         //generate a new line39.                         System.out.println("");40.                 }41.  42.         }43. }44.  45. /*46.  47.Output of the example would be48.*49.**50.***51.****52.*****53.*****54.****55.***56.**57.*58.  59.*/

14

Page 15: Java Examples

1. *2.         Java Pyramid 4 Example3.         This Java Pyramid example shows how to generate pyramid or triangle like4.         given below using for loop.5.        6.         17.         128.         1239.         123410.         1234511.  12.*/13.public class JavaPyramid4 {14.  15.         public static void main(String[] args) {16.                17.                 for(int i=1; i<= 5 ;i++){18.                        19.                         for(int j=0; j < i; j++){20.                                 System.out.print(j+1);21.                         }22.                        23.                         System.out.println("");24.                 }25.  26.         }27. }28.  29. /*30.  31.Output of the example would be32.133.1234.12335.123436.1234537.  38.*/

1. /*2.         List Even Numbers Java Example3.         This List Even Numbers Java Example shows how to find and list even4.         numbers between 1 and any given number.5. */6.  7. public class ListEvenNumbers {8.  

15

Page 16: Java Examples

9.         public static void main(String[] args) {10.                11.                 //define limit12.                 int limit = 50;13.                14.                 System.out.println("Printing Even numbers between 1 and " + limit);15.                16.                 for(int i=1; i <= limit; i++){17.                        18.                         // if the number is divisible by 2 then it is even19.                         if( i % 2 == 0){20.                                 System.out.print(i + " ");21.                         }22.                 }23.         }24. }25.  26. /*27.Output of List Even Numbers Java Example would be28.Printing Even numbers between 1 and 5029.2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 5030.*/

1. /*2.         List Odd Numbers Java Example3.         This List Odd Numbers Java Example shows how to find and list odd4.         numbers between 1 and any given number.5. */6.  7. public class ListOddNumbers {8.  9.         public static void main(String[] args) {10.                11.                 //define the limit12.                 int limit = 50;13.                14.                 System.out.println("Printing Odd numbers between 1 and " + limit);15.                16.                 for(int i=1; i <= limit; i++){17.                        18.                         //if the number is not divisible by 2 then it is odd19.                         if( i % 2 != 0){20.                                 System.out.print(i + " ");21.                         }22.                 }23.         }24. }

16

Page 17: Java Examples

25.  26. /*27.Output of List Odd Numbers Java Example would be28.Printing Odd numbers between 1 and 5029.1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 4930.*/

1. /*2.   Simple For loop Example3.   This Java Example shows how to use for loop to iterate in Java program.4. */5.  6. public class SimpleForLoopExample {7.  8.   public static void main(String[] args) {9.    10.     /* Syntax of for loop is11.      *12.      * for(<initialization> ; <condition> ; <expression> )13.      *   <loop body>14.      *15.      * where initialization usually declares a loop variable, condition is a16.      * boolean expression such that if the condition is true, loop body will be17.      * executed and after each iteration of loop body, expression is executed which18.      * usually increase or decrease loop variable.19.      *20.      * Initialization is executed only once.21.      */22.      23.      for(int index = 0; index < 5 ; index++)24.        System.out.println("Index is : " + index);25.        26.      /*27.       * Loop body may contains more than one statement. In that case they should28.       * be in the block.29.       */30.      31.       for(int index=0; index < 5 ; index++)32.       {33.       System.out.println("Index is : " + index);34.       index++;35.       }36.      37.       /*38.        * Please note that in above loop, index is a local variable whose scope39.        * is limited to the loop. It can not be referenced from outside the loop.40.        */

17

Page 18: Java Examples

41.   }42. }43.  44. /*45.Output would be46. Index is : 047. Index is : 148. Index is : 249. Index is : 350. Index is : 451. Index is : 052. Index is : 253. Index is : 454.*/

1. /*2.   Get Size of Java ArrayList and loop through elements Example3.   This Java Example shows how to get size or number of elements currently4.   stored in ArrayList. It also shows how to loop through element of it.5. */6.  7. import java.util.ArrayList;8.  9. public class GetSizeOfArrayListExample {10.  11.   public static void main(String[] args) {12.     //create an ArrayList object13.     ArrayList arrayList = new ArrayList();14.    15.     //Add elements to Arraylist using16.     arrayList.add("1");17.     arrayList.add("2");18.     arrayList.add("3");19.  20.     //To get size of Java ArrayList use int size() method21.     int totalElements = arrayList.size();22.    23.     System.out.println("ArrayList contains...");24.     //loop through it25.     for(int index=0; index < totalElements; index++)26.       System.out.println(arrayList.get(index));27.    28.   }29. }30.  31. /*32.Output would be

18

Page 19: Java Examples

33.ArrayList contains...34.135.236.337.*/

19


Recommended