You are on page 1of 19

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.in)); 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. 36. /* 37. * Area of a circle is 38. * pi * r * r 39. * where r is a radius of a circle. 40. */ 41. 42. //NOTE : use Math.PI constant to get value of pi 43. double area = Math.PI * radius * radius; 44. 45. System.out.println("Area of a circle is " + area); 46. } 47. }
1

48. 49. /* 50. Output of Calculate Circle Area using Java Example would be 51. Please enter radius of a circle 52. 19 53. Area of a circle is 1134.1149479459152 54. */

1. /* 2. Calculate Rectangle Area using Java Example 3. This Calculate Rectangle Area using Java Example shows how to calculate 4. 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. try 19. { 20. //read the length from console 21. 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 console 27. System.out.println("Please enter width of a rectangle"); 28. width = Integer.parseInt(br.readLine()); 29. 30. 31. } 32. //if invalid value was entered 33. catch(NumberFormatException ne) 34. { 35. System.out.println("Invalid value" + ne); 36. System.exit(0);
2

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 is 46. * length * width 47. */ 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 be 58. Please enter length of a rectangle 59. 10 60. Please enter width of a rectangle 61. 15 62. Area of a rectangle is 150 63. */ 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.");
3

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. */

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

13. //assign first element of an array to largest and smallest 14. 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 be 33. Largest Number is : 98 34. Smallest Number is : 23 35. */ 1. /* 2. Java Factorial Example 3. This Java Factorial Example shows how to calculate factorial of 4. 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

26. } 27. } 28. 29. /* 30. Output of the Factorial program would be 31. Factorial of a number is 120 32. */

1. /* 2. Reverse Number using Java 3. 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 number 11. 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 digit 18. temp = number%10; 19. 20. //create the reversed number 21. reversedNumber = reversedNumber * 10 + temp; 22. number = number/10; 23. 24. } 25. 26. //output the reversed number 27. System.out.println("Reversed Number is: " + reversedNumber); 28. } 29. } 30. 31. /* 32. Output of this Number Reverse program would be 33. Reversed Number is: 4321 34. */
6

1. /* 2. Swap Numbers Java Example 3. This Swap Numbers Java Example shows how to 4. 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 value 19. 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 be 37. Before Swapping 38. Value of num1 is :10 39. Value of num2 is :20 40. After Swapping 41. Value of num1 is :20 42. Value of num2 is :10 43. */
7

If else 1. /* 2. Compare Two Numbers Java Example 3. This Compare Two Numbers Java Example shows how to compare two numbers 4. 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 compare 12. 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 be 29. 324 is greater than 234 30. */

1. /* 2. Determine If Year Is Leap Year Java Example 3. This Determine If Year Is Leap Year Java Example shows how to 4. 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 check 12. int year = 2004; 13.
8

14. //if year is divisible by 4, it is a leap year 15. 16. if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) 17. System.out.println("Year " + year + " is a leap year"); 18. else 19. System.out.println("Year " + year + " is not a leap year"); 20. } 21. } 22. 23. /* 24. Output of the example would be 25. Year 2004 is a leap year 26. */ 1. /* 2. If Else-If statement Example 3. 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 upon 12. * multiple conditions. 13. * Sysntax of If Else-If statement is 14. * 15. * if(<condition1>) 16. * statement1 17. * else if(<condition2>) 18. * statement2 19. * .. 20. * else 21. * statement3 22. * 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 else 25. * 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. else 35. System.out.println("i is less than 50");
9

36. } 37. } 38. 39. /* 40. Output would be 41. i is less than 50 42. */ Arrays 1. /* 2. Create List from Java Object Array Example 3. This java example shows how to create a List from an array of type Object using 4. 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 array 15. 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 iterator 27. Iterator itr = list.iterator(); 28. 29. //iterate through list created from Array 30. 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 be 39. List created from an Array of type Object contains,
10

40. Object 41. Array 42. Converted 43. To 44. List 45. */ Switch Case 1. /* 2. Free Flowing Switch Statement Example 3. This example shows how case statements are executed if break is 4. 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 of 12. * matching case statements. If break statement is 13. * not specified, switch statement becomes free flowing and 14. * all cases following matching case including default 15. * 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 be 39. i is 0 40. i is 1
11

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

1. /* 2. Java Pyramid 1 Example 3. This Java Pyramid example shows how to generate pyramid or triangle like 4. 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 line 24. System.out.println(""); 25. } 26. } 27. } 28. 29. /* 30. Output of the above program would be 31. * 32. ** 33. *** 34. **** 35. ***** 36. */

1. /* 2. 3. 4.

Java Pyramid 2 Example This Java Pyramid example shows how to generate pyramid or triangle like given below using for loop.
12

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 line 24. System.out.println(""); 25. } 26. } 27. } 28. 29. /* 30. 31. Output of the example would be 32. ***** 33. **** 34. *** 35. ** 36. * 37. 38. */

1. /* 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

Java Pyramid 3 Example This Java Pyramid example shows how to generate pyramid or triangle like given below using for loop. * ** *** **** ***** ***** ****
13

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 line 28. System.out.println(""); 29. } 30. 31. //create second half of pyramid 32. 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 line 39. System.out.println(""); 40. } 41. 42. } 43. } 44. 45. /* 46. 47. Output of the example would be 48. * 49. ** 50. *** 51. **** 52. ***** 53. ***** 54. **** 55. *** 56. ** 57. * 58. 59. */

14

1. * 2. Java Pyramid 4 Example 3. This Java Pyramid example shows how to generate pyramid or triangle like 4. given below using for loop. 5. 6. 1 7. 12 8. 123 9. 1234 10. 12345 11. 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 be 32. 1 33. 12 34. 123 35. 1234 36. 12345 37. 38. */

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

9. public static void main(String[] args) { 10. 11. //define limit 12. 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 even 19. if( i % 2 == 0){ 20. System.out.print(i + " "); 21. } 22. } 23. } 24. } 25. 26. /* 27. Output of List Even Numbers Java Example would be 28. Printing Even numbers between 1 and 50 29. 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 30. */

1. /* 2. List Odd Numbers Java Example 3. This List Odd Numbers Java Example shows how to find and list odd 4. 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 limit 12. 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 odd 19. if( i % 2 != 0){ 20. System.out.print(i + " "); 21. } 22. } 23. } 24. }
16

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

1. /* 2. Simple For loop Example 3. 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 is 11. * 12. * for(<initialization> ; <condition> ; <expression> ) 13. * <loop body> 14. * 15. * where initialization usually declares a loop variable, condition is a 16. * boolean expression such that if the condition is true, loop body will be 17. * executed and after each iteration of loop body, expression is executed which 18. * 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 should 28. * 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 scope 39. * is limited to the loop. It can not be referenced from outside the loop. 40. */
17

41. } 42. } 43. 44. /* 45. Output would be 46. Index is : 0 47. Index is : 1 48. Index is : 2 49. Index is : 3 50. Index is : 4 51. Index is : 0 52. Index is : 2 53. Index is : 4 54. */

1. /* 2. Get Size of Java ArrayList and loop through elements Example 3. This Java Example shows how to get size or number of elements currently 4. 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 object 13. ArrayList arrayList = new ArrayList(); 14. 15. //Add elements to Arraylist using 16. arrayList.add("1"); 17. arrayList.add("2"); 18. arrayList.add("3"); 19. 20. //To get size of Java ArrayList use int size() method 21. int totalElements = arrayList.size(); 22. 23. System.out.println("ArrayList contains..."); 24. //loop through it 25. for(int index=0; index < totalElements; index++) 26. System.out.println(arrayList.get(index)); 27. 28. } 29. } 30. 31. /* 32. Output would be
18

33. ArrayList contains... 34. 1 35. 2 36. 3 37. */

19