12 Beginners Java Programs

Program 1: Reverse a number using while Loop

import java.util.Scanner;
class ReverseNumberWhile
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      //While Loop: Logic to find out the reverse number
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of input number is: "+reversenum);
   }
}

Output:

Input your number and press enter: 
145689
Reverse of input number is: 986541

Program 2: calculate area and circumference of circle

In this tutorial we will see how to calculate area and circumference of circle in Java. There are two ways to do this:

1) With user interaction: Program will prompt user to enter the radius of the circle
2) Without user interaction: The radius value would be specified in the program itself.

import java.util.Scanner;
class CircleDemo
{
   static Scanner sc = new Scanner(System.in);
   public static void main(String args[])
   {
      System.out.print("Enter the radius: ");
      /*We are storing the entered radius in double
       * because a user can enter radius in decimals
       */
      double radius = sc.nextDouble();
      //Area = PI*radius*radius
      double area = Math.PI * (radius * radius);
      System.out.println("The area of circle is: " + area);
      //Circumference = 2*PI*radius
      double circumference= Math.PI * 2*radius;
      System.out.println( "The circumference of the circle is:"+circumference) ;
   }
}

Output:

Enter the radius: 1
The area of circle is: 3.141592653589793
The circumference of the circle is:6.283185307179586

Program 3: calculate area of Triangle

Here we will see how to calculate area of triangle. We will see two following programs to do this:
1) Program 1: Prompt user for base-width and height of triangle.
2) Program 2: No user interaction: Width and height are specified in the program itself.

import java.util.Scanner;
class AreaTriangleDemo {
   public static void main(String args[]) {   
      Scanner scanner = new Scanner(System.in);

      System.out.println("Enter the width of the Triangle:");
      double base = scanner.nextDouble();

      System.out.println("Enter the height of the Triangle:");
      double height = scanner.nextDouble();

      //Area = (width*height)/2
      double area = (base* height)/2;
      System.out.println("Area of Triangle is: " + area);      
   }
}

Output:

Enter the width of the Triangle:
2
Enter the height of the Triangle:
2
Area of Triangle is: 2.0


Program 4: sum the elements of an array

In this tutorial we will see how to sum up all the elements of an array.

lass SumOfArray{
   public static void main(String args[]){
      int[] array = {10, 20, 30, 40, 50, 10};
      int sum = 0;
      //Advanced for loop
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

Output:

Sum of array elements is:160

Program 5: Java program to check prime number

This program will prompt user to enter a number and then it will check and display whether the input number is prime or not.

 


import java.util.Scanner;
class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number for check:");
//capture the input in an integer
int num=scan.nextInt();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is Prime Number");
else
System.out.println(num + " is not Prime Number");
}
}

Output:

Enter a number for check:
19
19 is Prime Number




Program 6: check Even or Odd number

import java.util.Scanner;

class CheckEvenOdd
{
  public static void main(String args[])
  {
    int num;
    System.out.println("Enter an Integer number:");

    //The input provided by user is stored in num
    Scanner input = new Scanner(System.in);
    num = input.nextInt();

    /* If number is divisible by 2 then it's an even number
     * else odd number*/
    if ( num % 2 == 0 )
        System.out.println("Entered number is even");
     else
        System.out.println("Entered number is odd");
  }
}

Output 1:

Enter an Integer number:
78
Entered number is even

Output 2:

Enter an Integer number:
77
Entered number is odd


Program 7: linear search – Example

Example Program:

to find out a number among all other numbers entered by user.

 

         
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
//Creating array to store the all the numbers
array = new int[num];
System.out.println("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");
item = input.nextInt();

for (counter = 0; counter < num; counter++)
{
if (array[counter] == item)
{
System.out.println(item+" is present at location "+(counter+1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
}
}

Output 1:

Enter number of elements:
6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3

Output 2:

Enter number of elements:
4
Enter 4 integers
11
22
4
5
Enter the search value:
99
99 doesn't exist in array.


Program 8: program to perform binary search

import java.util.Scanner;
class BinarySearchExample
{
   public static void main(String args[])
   {
      int counter, num, item, array[], first, last, middle;
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 

      //Creating array to store the all the numbers
      array = new int[num];

      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
          array&#91;counter&#93; = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();
      first = 0;
      last = num - 1;
      middle = (first + last)/2;

      while( first <= last )
      {
         if ( array&#91;middle&#93; < item ) first = middle + 1; else if ( array&#91;middle&#93; == item ) { System.out.println(item + " found at location " + (middle + 1) + "."); break; } else { last = middle - 1; } middle = (first + last)/2; } if ( first > last )
          System.out.println(item + " is not found.n");
   }
}

Output 1:

Enter number of elements:
7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

Output 2:

Enter number of elements:
5
Enter 5 integers
12
3
77
890
23
Enter the search value:
99
99 is not found.

Program 9: Generate random number

import java.util.*;
class GenerateRandomNumber {
   public static void main(String[] args) {
      int counter;
      Random rnum = new Random();
      /* Below code would generate 5 random numbers
       * between 0 and 200.
       */
      System.out.println("Random Numbers:");
      System.out.println("***************");
      for (counter = 1; counter <= 5; counter++) {
         System.out.println(rnum.nextInt(200));
      }
   }
}
&#91;/code&#93;

<h1 class="headline">Java program to generate random number – Example</h1>
<div class="byline"><span class="post_cats"> <a href="http://beginnersbook.com/category/java-examples/" rel="category tag">JAVA EXAMPLES</a></span></div>
<div class="post_content">
<h4>Example Program to generate random numbers</h4>
In the below program, we are using the <code>nextInt()</code> method of <code>Random</code> class to serve our purpose.
<pre class="prettyprint prettyprinted"><span class="com">/* Program: Random number generator
 * Written by: Chaitanya from beginnersbook.com
 * Input: None
 * Output:Random number between o and 200*/</span>
<span class="kwd">import</span><span class="pln"> java</span><span class="pun">.</span><span class="pln">util</span><span class="pun">.*;</span>
<span class="kwd">class</span> <span class="typ">GenerateRandomNumber</span> <span class="pun">{</span>
   <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">void</span><span class="pln"> main</span><span class="pun">(</span><span class="typ">String</span><span class="pun">[]</span><span class="pln"> args</span><span class="pun">)</span> <span class="pun">{</span>
      <span class="kwd">int</span><span class="pln"> counter</span><span class="pun">;</span>
      <span class="typ">Random</span><span class="pln"> rnum </span><span class="pun">=</span> <span class="kwd">new</span> <span class="typ">Random</span><span class="pun">();</span>
      <span class="com">/* Below code would generate 5 random numbers
       * between 0 and 200.
       */</span>
      <span class="typ">System</span><span class="pun">.</span><span class="kwd">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"Random Numbers:"</span><span class="pun">);</span>
      <span class="typ">System</span><span class="pun">.</span><span class="kwd">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"***************"</span><span class="pun">);</span>
      <span class="kwd">for</span> <span class="pun">(</span><span class="pln">counter </span><span class="pun">=</span> <span class="lit">1</span><span class="pun">;</span><span class="pln"> counter </span><span class="pun">&lt;=</span> <span class="lit">5</span><span class="pun">;</span><span class="pln"> counter</span><span class="pun">++)</span> <span class="pun">{</span>
         <span class="typ">System</span><span class="pun">.</span><span class="kwd">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="pln">rnum</span><span class="pun">.</span><span class="pln">nextInt</span><span class="pun">(</span><span class="lit">200</span><span class="pun">));</span>
      <span class="pun">}</span>
   <span class="pun">}</span>
<span class="pun">}</span></pre>
Output:
<pre class="prettyprint prettyprinted"><span class="typ">Random</span> <span class="typ">Numbers</span><span class="pun">:</span>
<span class="pun">***************</span>
<span class="lit">135</span>
<span class="lit">173</span>
<span class="lit">5</span>
<span class="lit">17</span>
<span class="lit">15</span></pre>
</div>
<h3 id="using-while">Program 10: Find duplicate characters in a String</h3>
&nbsp;


import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Details {
 
  public void countDupChars(String str){
 
    //Create a HashMap 
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 
 
    //Convert the String to char array
    char[] chars = str.toCharArray();
 
    /* logic: char are inserted as keys and their count
     * as values. If map contains the char already then
     * increase the value by 1
     */
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }
 
    //Obtaining set of keys
    Set<Character> keys = map.keySet();
 
    /* Display count of chars if it is
     * greater than 1. All duplicate chars would be 
     * having value greater than 1.
     */
    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println("Char "+ch+" "+map.get(ch));
      }
    }
  }
 
  public static void main(String a[]){
    Details obj = new Details();
    System.out.println("String: BeginnersBook.com");
    System.out.println("-------------------------");
    obj.countDupChars("BeginnersBook.com");
  
    System.out.println("nString: ChaitanyaSingh");
    System.out.println("-------------------------");
    obj.countDupChars("ChaitanyaSingh");
 
    System.out.println("nString: #@$@!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@$@!#$%!!%@");
  }
}

Output:

String: BeginnersBook.com
-------------------------
Char e 2
Char B 2
Char n 2
Char o 3

String: ChaitanyaSingh
-------------------------
Char a 3
Char n 2
Char h 2
Char i 2

String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2

Program 11: Binary to decimal conversion

Method 1: Binary to Decimal conversion using Integer.parseInt() method

import java.util.Scanner;
class BinaryToDecimal {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter a binary number: ");
       String binaryString =input.nextLine();
       System.out.println("Output: "+Integer.parseInt(binaryString,2));
    }
}

Output:

Enter a binary number: 1101
Output: 13

Method 2: Conversion without using parseInt

public class Details {
 
  public int BinaryToDecimal(int binaryNumber){
 
    int decimal = 0;
    int p = 0;
    while(true){
      if(binaryNumber == 0){
        break;
      } else {
          int temp = binaryNumber%10;
          decimal += temp*Math.pow(2, p);
          binaryNumber = binaryNumber/10;
          p++;
       }
    }
    return decimal;
  }
 
  public static void main(String args[]){
    Details obj = new Details();
    System.out.println("110 --> "+obj.BinaryToDecimal(110));
    System.out.println("1101 --> "+obj.BinaryToDecimal(1101));
    System.out.println("100 --> "+obj.BinaryToDecimal(100));
    System.out.println("110111 --> "+obj.BinaryToDecimal(110111));
  }
}

Output:

110 --> 6
1101 --> 13
100 --> 4
110111 --> 55

Program 12: Get input from user

In this tutorial we are gonna see how to accept input from user. We are using Scanner class to get the input. In the below example we are getting input String, integer and a float number. For this we are using following methods:
1) public String nextLine(): For getting input String
2) public int nextInt(): For integer input
3) public float nextFloat(): For float input

import java.util.Scanner;

class GetInputData
{
  public static void main(String args[])
  {
     int num;
     float fnum;
     String str;
 
     Scanner in = new Scanner(System.in);
 
     //Get input String
     System.out.println("Enter a string: ");
     str = in.nextLine();
     System.out.println("Input String is: "+str);
 
     //Get input Integer
     System.out.println("Enter an integer: ");
     num = in.nextInt();
     System.out.println("Input Integer is: "+num);
 
     //Get input float number
     System.out.println("Enter a float number: ");
     fnum = in.nextFloat();
     System.out.println("Input Float number is: "+fnum); 
  }
}

Output:

Enter a string: 
Chaitanya
Input String is: Chaitanya
Enter an integer: 
27
Input Integer is: 27
Enter a float number: 
12.56
Input Float number is: 12.56