Java Examples

Hello World Example

This bare bones program will output “Hello World!”.

public class Example {
    public static void main(String[] args) {
          System.out.println("Hello, World");
    }
}

Simple Math with User Input

Two user inputs will add each other:

import java.util.Scanner;
 
public class Example {
          public static void main(String args[]){
                   int first, second, result;
                   Scanner sc = new Scanner(System.in);
              first = sc.nextInt();
              second = sc.nextInt();
              result = first + second;
              System.out.println("Your result is: " + result);
          }
}

Two user inputs will subtract each other:

import java.util.Scanner;
 
public class Example {
          public static void main(String args[]){
                   int first, second, result;
                   Scanner sc = new Scanner(System.in);
              first = sc.nextInt();
              second = sc.nextInt();
              result = first - second;
              System.out.println("Your result is: " + result);
          }
}

Two user inputs will multiply each other:

import java.util.Scanner;
 
public class Example {
          public static void main(String args[]){
                   int first, second, result;
                   Scanner sc = new Scanner(System.in);
              first = sc.nextInt();
              second = sc.nextInt();
              result = first * second;
              System.out.println("Your result is: " + result);
          }
}

Two user inputs divide each other:

import java.util.Scanner;
 
public class Example {
          public static void main(String args[]){
                   int first, second, result;
                   Scanner sc = new Scanner(System.in);
              first = sc.nextInt();
              second = sc.nextInt();
              result = first / second;
              System.out.println("Your result is: " + result);
          }
}

Two user inputs modulo each other:

import java.util.Scanner;
 
public class Example {
          public static void main(String args[]){
                   int first, second, result;
                   Scanner sc = new Scanner(System.in);
              first = sc.nextInt();
              second = sc.nextInt();
              result = first % second;
              System.out.println("Your result is: " + result);
          }
}

Enumerator Motherboard Size

This enumerator example will output a chosen motherboard form factor. Example.java :

public class Example {
          public static void main(String args[]){
                             OtherExample motherboard = new OtherExample();
                             motherboard.formfactor = OtherExample.motherboard.ATX ;
                             System.out.println("Size: " + motherboard.formfactor);
          }
}

Fizz Buzz

A simple challenge in which a for loop prints integers 1 to 100, but replaces multiples of 3 with ‘Fizz’, multiples of 5 with ‘Buzz’, or both with ‘FizzBuzz’.

public class Example {
          public static void main(String[] args){
                   for(int i= 1; i <= 100; i++){
                             if(i % 15 == 0){
                                      System.out.println("FizzBuzz");
                             } else if (i % 3 == 0){
                                      System.out.println("Fizz");
                             } else if (i % 5 == 0){
                                      System.out.println("Buzz");
                             } else {
                                      System.out.println(i);
                             }
                   }
          }
}

Comments

Comments are used so text can be included in a source code, usually meant to increase visual significance. For example, adding labels to each section of a block in a complicated source code.

public class Example {
          public static void main(String args[]){
                   /* This is a comment
                   The computer will completely ignore all comments
                   The purpose of this is so you can add text to a source code in which you can label stuff! */
          }
}

Serial Code Selector

This simple program will scan through numbers until it matches the variable.

package test;
 
public class Example {
          public static void main(String args[]){
                   int serialnumber = 103;
                   switch (serialnumber){
                             case 100:
                                      System.out.println("Cucumbers selected!");
                    break;
                             case 101:
                                      System.out.println("Avocado selected!");
                    break;
                             case 102:
                                      System.out.println("Pineapple selected!");
                    break;
                             case 103:
                                      System.out.println("Potato selected!");
                    break;
                             case 104:
                                      System.out.println("Strawberries selected!");
                    break;
                             case 105:
                                      System.out.println("Watermelon selected!");
                    break;
                             case 106:
                                      System.out.println("Tomatoes selected!");
                    break;
                             default:
                                      System.out.println("Invalid Serial!");
                   }
          }
}

Reading File Strings

This simple program will read the text inside a .txt file.

import java.io.*;
 
public class Example {
          public static void main(String[] args) {
                   File file = new File("PATH HERE INCLUDING FILE & EXTENSION");
                   int ch;
                   StringBuffer strContent = new StringBuffer("");
                   FileInputStream fin = null;
                  
                   try {
                             fin = new FileInputStream(file);
                             while( (ch = fin.read()) != -1)
                                      strContent.append((char)ch);
                             fin.close();
                   } catch(FileNotFoundException e) {
                             System.out.println("File " + file.getAbsolutePath() + "cannot be found.");
                   } catch(IOException ioe) {
                             System.out.println("Cannot read the file." + ioe);
                   }
                   System.out.println("File contents: ");
                   System.out.println(strContent);
          }
}

Letter Grade With Switch

(The following examples will have an inconsistent formatting style, this is because I have changed up my habits in programming)

import java.util.Scanner;

public class LetterGradeSwitch {
   public static void main(String[] args) {
       int  value = 0; // last known user input
       char letter; // stores letter grade
       int[] grades = {0, 0, 0, 0, 0}; // number of grades from F to A
       Scanner in = new Scanner(System.in);
       while (value <= 100)
       {
           System.out.print("Enter a number grade from 0 - 100 (-1 to exit program): ");
           value = in.nextInt();

           // if user input is specifically -1, will stop the entire program and print out results
           if (value == -1)
               break;

           // if-else-if ladder will convert user input to the appropriate grade, then prepares for conversion
           if (value < 70) // F
           {
               System.out.println(value + " is F");
               letter = 'F';
               value = 0;
           }
           else if (value < 76) // D
           {
               System.out.println(value + " is D");
               letter = 'D';
               value = 0;
           }
           else if (value < 85) // C
           {
               System.out.println(value + " is C");
               letter = 'C';
               value = 0;
           }
           else if (value < 93) // B
           {
               System.out.println(value + " is B");
               letter = 'B';
               value = 0;
           }
           else if (value <= 100) // A
           {
               System.out.println(value + " is A");
               letter = 'A';
               value = 0;
           }
           else
           {
               System.out.println("Invalid Entry, please read instruction.");
               letter = 'N';
               value = 0;
           }

           // increments an index of the array 'grades' respective to the grade letter
           switch (letter)
           {
               case 'F':
                   grades[0]++;
                   break;
               case 'D':
                   grades[1]++;
                   break;
               case 'C':
                   grades[2]++;
                   break;
               case 'B':
                   grades[3]++;
                   break;
               case 'A':
                   grades[4]++;
                   break;
               default:
           }
       }

       // outputs grade results
       System.out.println("There are " + grades[4] + " As");
       System.out.println("There are " + grades[3] + " Bs");
       System.out.println("There are " + grades[2] + " Cs");
       System.out.println("There are " + grades[1] + " Ds");
       System.out.println("There are " + grades[0] + " Fs");
   }
}

Temperature Year Bar Graph

Accepts user input for all 12 months in the form of a temperature unit and converts into a bar graph.

package com;

import java.util.Scanner;

public class DataArrayTemp
{

   //Procedure for putting up the bars
   public static void bar(int size, String month)
   {
       System.out.print(month);
       for (int count = 0; count < size / 2; count++)
           System.out.print("*");
       System.out.println();
   }

   //Procedure for getting the monthly temperatures
   public static int getTemp(String month)
   {
       System.out.print("Enter the average Temperature for " + month + ": ");
       Scanner in = new Scanner (System.in);
       return(in.nextInt());
   }

   public static void main(String[] args)
   {
       //Declare an array with the months name (abbreviated)
       String[] shortMonths = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
       //Declare an array with the months name
       String[] longMonths = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
       int[] temps; //Array of integers for temperatures
       String mon; //Input value for month
       int temp, count, stars; //Values for looping
//        Scanner in = new Scanner(System.in);
       temps = new int[12];
       for (count = 0; count < 12; count++) //Loop for entering the temps into the array
       {
//            System.out.print("Enter the average Temperature for " + longMonths[count] + ": ");
//            temp = in.nextInt();
           temps[count] = getTemp (longMonths[count]);
       }
       for (count = 0; count < 12; count++) //Loop for outputting data
       {
//            System.out.print(shortMonths[count]);
//            for (stars = 0; stars < temps[count] / 2 ; stars++) //Loop for outputting "bar graph"
//                System.out.print("*");
           bar (temps[count], shortMonths[count]);
//            System.out.println();
       }
   }
}
<pre>

== Improved Temperature Year Bar Graph
An alternative to the Temperature Bar Graph, will convert temperature units for the user and will include customs symbols for bar graph.

<pre>
package com;

import java.util.Scanner;

public class weekDays {
   public static void main(String []args) {
       Scanner in = new Scanner(System.in); // initializes a scanner
       String convDecision, tempType = "0", barGraphSymbol;
       String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; // initializes an array containing all 12 months
       String[] monthsShorthand = {"Jan", "Feb", "Mar", "May", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Nov", "Dec"}; // initializes an array of all 12 month shorthands
       float[] temp = new float[12]; // 12 temperature elements for 12 months

       // section of code to prompt for the average temperature of every month
       for (int x = 0; x < 12; x++) // increments from 0 to 11 so we can go through array 'months' and stores input in a 'temp' array
       {
           System.out.print("Input the Average Temperature of " + months[x] + ": "); // the text prompt to ask for user input for that month
           temp[x] = in.nextFloat(); // asks for user input that the respective month
       }

       // section of code to have temperature values converted based on user decision
       System.out.println(); // returns to a new line
       System.out.print("Do you wish to convert and print out temperatures? (Y for yes, or anything else for No): ");
       convDecision = in.next().toUpperCase(); // prompts user for conversion. Data parsed will always be capital since it's case sensitive
       if (convDecision.equals("Y")) // if user input equals to "Y", then conversion will start
       {
               for (int x = 0; x < 12; x++) // increments x from 0 until it reaches 12
                   System.out.println(months[x] + ": " + temp[x] + " °F = " + ((temp[x] - 32) * 5 / 9) + " °C");
           else
               for (int x = 0; x < 12; x++)
                   System.out.println(months[x] + ": " + temp[x] + " °C = " + (temp[x] * 9 / 5 + 32) + " °F");
   }
}

Randomized Card/Deck Generator

Populates and generates a card deck, then sorts it

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Random;

class main
{
    public static void main (String[] args)
    {
                int cards = 52, columns = 3, cardsPerSuit = 13, inner = 0, outer = 0, count = 0, randIndex = 0, tempCard = 0, tempSuit = 0, tempIndex = 0;
        boolean cardSet = false, swap = true;
        int[][] deck = new int[cards][columns];
        Random randCards = new Random();

        // since theres 4 suits and 13 cards in a deck, inner can just simply be added on top of the multiplication of outer and 13 cards
        for (outer = 0; outer < 4; outer++)
        {
            for (inner = 0; inner < cardsPerSuit; inner++)
            {
                deck [cardsPerSuit * outer + inner][0] = inner + 1;
                deck [cardsPerSuit * outer + inner][1] = outer;
                deck [cardsPerSuit * outer + inner][2] = -1;
            }
        }
               
        // uses the for loops count to set as the placement of a card. Uses a random number from 0 through 51 to index the third column, if its not a -1, then redo random generation on same element
        for (count = 0; count < cards; count++)
        {
            if (deck[randIndex][2] == -1)
                deck[randIndex][2] = count + 1;
            else
                count -= 1;
}
    
        
        //bubbles sorts the shuffled deck's placement from lowest to highest while preserving the actual 'cards' number and suit
        swap = true;
        while (swap)
        {
            swap = false;
            for (count = 0; count < cards - 1; count++)
                if (deck[count][2] > deck[count + 1][2])
                {
                    tempCard = deck[count][0];
                    tempSuit = deck[count][1];
                    tempIndex = deck[count][2];
                    deck[count][0] = deck[count + 1][0];
                    deck[count][1] = deck[count + 1][1];
                    deck[count][2] = deck[count + 1][2];
                    deck[count + 1][0] = tempCard;
                    deck[count + 1][1] = tempSuit;
                    deck[count + 1][2] = tempIndex;
                    swap = true;
                }
        }

        // actively uses switches statements to output the literal meaning of the number on the fly to output the shuffled card
        for (count = 0; count < cards; count++)
        {
            switch (deck[count][0])
            {
                case 1: System.out.print("A");
                        break;
                case 11: System.out.print("J");
                        break;
                case 12: System.out.print("Q");
                        break;
                case 13: System.out.print("K");
                        break;
                default: System.out.print(deck[count][0]);
        }
 
        switch (deck[count][1])
        {
            case 0: System.out.print(" Hearts");
                    break;
            case 1: System.out.print(" Spades");
                    break;
            case 2: System.out.print(" Diamonds");
                    break;
            case 3: System.out.print(" Clubs");
                    break;
        }
        System.out.println(" " + deck[count][2]);
        }
    }
}

Here is a possible generation of the program

8 Diamonds 7, , 2 Spades 26, , J Diamonds 24, , A Spades 13, , K Hearts 48, , 10 Spades 33, , K Diamonds 12, , 2 Diamonds 45, , K Hearts 43, , A Spades 9, , A Diamonds 1, , K Diamonds 11, , 2 Clubs 35, , 5 Hearts 9, , 9 Hearts 32, , 10 Clubs 15, , 9 Hearts 32, , 7 Diamonds 33, , Q Spades 44, , Q Hearts 51, , 7 Spades 14, , 8 Diamonds 7, , J Hearts 31, , A Diamonds 33, , 10 Hearts 13, , 7 Hearts 10, , 2 Spades 1, , 5 Clubs 4, , 4 Hearts 32, , 3 Clubs 30, , K Clubs 19, , 7 Diamonds 16, , 3 Clubs 40, , J Spades 6, , 7 Diamonds 31, , Q Spades 8, , Q Hearts 8, , 8 Spades 28, , Q Clubs 42, , 4 Diamonds 21, , 9 Clubs 5, , 5 Clubs 36, , Q Hearts 51, , 4 Diamonds 2, , 8 Hearts 41

Minimum, Maximum and Average Program with Procedures

This program will ask for user input for a specific set of numbers, and attempt to determine which number is the smallest, the biggest and find the average of all of them.

package com;

import java.util.Scanner;

public class MinMaxAvgProcedures {
   public static int min(int min, int value)
   {
       if (min < value) return min; // Return the parsed min value if min is less than user input
       else return value; // Return the user input if min is not less than user input
   }

   public static int max(int value, int max)
   {
       if (max > value) return max; // Return parsed max value if max is less than user input
       else return value; // Return the user input if max is not less than user input
   }

   public static float avg(float avg, int value)
   {
       return avg + value;
   }

   public static void main(String []args) {
       int input, limit = 5, min = 0, max = 0; // Initializes integer variables
       float avg = 0; // initializes float variable 'avg', since we'll need a decimal after finding the average
       Scanner in = new Scanner(System.in); // Initializes scanner

//      Prompts user for a integer to be used for the amount of numbers to input
       System.out.print("Enter the amount of numbers you wish to input: ");
       limit = in.nextInt();

//      Until the limit, will prompt for number input to be calculated
       for (int inputCount = 0; inputCount < limit; inputCount++)
       {
           System.out.print("Enter entry #" + (inputCount + 1) + ": ");
           input = in.nextInt();
//          On first time, set every variable to user input so that they can be compared
           if (inputCount == 0)
           {
               min = input;
               max = input;
               avg = input;
           }
           else
           {
               min = min(min, input); // calls 'min' procedure with previous variables and user input parameters
               max = max(max, input); // calls 'max' procedure with previous variables and user input parameters
//              If the loop is on last cycle, then do divisor for average. Else, just add previous 'avg' values with current user input
               if (inputCount == limit - 1) avg = avg(avg, input) / limit;
               else avg = avg(avg, input);
           }
       }

       System.out.println("Min is " + min);
       System.out.println("Max is " + max);
       System.out.println("Average is " + avg);
   }
}

Random Bubble Sorter

Generates a random list of numbers to sort them using a bubble sort algorithm

package com;

import java.util.Random;
import java.util.Scanner;

public class BubbleSortRandom
{
    public static void main(String[] args)
    {
        int randNum, temp, count, capital, offset;
        boolean swap = true;
        int[] numbers = new int[30]; // Initializes an array with 30 elements
        Random randomGenerator = new Random(); // Initializes a Random object
        Scanner in = new Scanner(System.in); // Initializes a Scanner

        // Prompts the user for capital casing
        System.out.print("Would you like to use Capital Case Letters? (1 for Yes, 0 for No): ");
        capital = in.nextInt();

        // Ternary operator decides the lower limit of the random generation range depending on user input
        offset = (capital == 1) ? 65 : 97;

        // Outputs all 30 randomly generated values without any sort
        System.out.println("Unsorted Numbers: ");
        for (count = 0; count < 30; count++) {
            randNum = (randomGenerator.nextInt(26) + offset);
            numbers[count] = randNum;
            System.out.print((char) numbers[count] + " ");
        }

        // Sorts array elements from Low to High, in order to achieve A through Z
        System.out.println();
        System.out.println("A through Z Numbers: ");
        while (swap)
        {
            swap = false;
            for (count = 0; count < 29; count++)
            {
                if (numbers[count] > numbers[count + 1])
                {
                    temp = numbers[count];
                    numbers[count] = numbers[count + 1];
                    numbers[count + 1] = temp;
                    swap = true;
                }
            }
        }

        for (count = 0; count < 30; count++)
            System.out.print((char) numbers[count] + " ");

        // Resets swap to true so that the next while loop can run, sorts array elements from Z through A
        swap = true;
        System.out.println();
        System.out.println("Z through A Numbers: ");
        while (swap)
        {
            swap = false;
            for (count = 0; count < 29; count++)
            {
                if (numbers[count] < numbers[count + 1])
                {
                    temp = numbers[count];
                    numbers[count] = numbers[count + 1];
                    numbers[count + 1] = temp;
                    swap = true;
                }
            }
        }

        for (count = 0; count < 30; count++)
            System.out.print((char) numbers[count] + " ");
    }
}

Inefficient Letter Grade Converter

Takes in multiple grades and converts them into letter grades

package com;

import java.util.Scanner;

public class LetterGradeSwitch {
    public static void main(String[] args) {
        int  value = 0; // last known user input
        float gpa; // calculated GPA
        int[] grades = {0, 0, 0, 0, 0}; // number of grades from A to F
        Scanner in = new Scanner(System.in);
        while (value <= 100)
        {
            System.out.print("Enter a number grade from 0 - 100 (-1 to exit program): ");
            value = in.nextInt();

            // if user input is specifically -1, will stop the entire program and print out results
            if (value <= -1)
                break;

            // switch statement to find case for 'value', default is assumed to be F
            // increments an index of the array 'grades' respective to the grade letter
            switch (value)
            {
                case 100:
                case 99:
                case 98:
                case 97:
                case 96:
                case 95:
                case 94:
                case 93:
                    grades[0]++;
                    System.out.println(value + " is A!!!");
                    value = 0;
                    break;
                case 92:
                case 91:
                case 90:
                case 89:
                case 88:
                case 87:
                case 86:
                case 85:
                    grades[1]++;
                    System.out.println(value + " is B!!");
                    value = 0;
                    break;
                case 84:
                case 83:
                case 82:
                case 81:
                case 80:
                case 79:
                case 78:
                case 77:
                case 76:
                    grades[2]++;
                    System.out.println(value + " is C!");
                    value = 0;
                    break;
                case 75:
                case 74:
                case 73:
                case 72:
                case 71:
                case 70:
                    grades[3]++;
                    System.out.println(value + " is D");
                    value = 0;
                    break;
                default:
                    grades[4]++;
                    System.out.println(value + " is F");
                    value = 0;
                    break;
            }
        }

        // calculates GPA by taking in the number of As, Bs, Cs, Ds and multiplies by 4, 3, 2, 1 respectively
        // divides that by number of As, Bs, Cs and Ds
        gpa = (float) ((grades[0] * 4) + (grades[1] * 3) + (grades[2] * 2) + (grades[3])) / (grades[0] + grades[1] + grades[2] + grades[3] + grades[4]);

        // outputs Grade(s) and GPA results
        System.out.println("There are " + grades[0] + " As");
        System.out.println("There are " + grades[1] + " Bs");
        System.out.println("There are " + grades[2] + " Cs");
        System.out.println("There are " + grades[3] + " Ds");
        System.out.println("There are " + grades[4] + " Fs");
        System.out.println("The GPA is: " + gpa);
    }
}
There are 2 As There are 2 Bs There are 2 Cs There are 2 Ds There are 2 Fs The GPA is 4.2

For Loop Char

Uses a for loop to convert its variable into the char variable type equilvalent

package com;

import java.util.Scanner;

public class ForLoopChar {
    public static void main(String[] args){
        int start, end;
        Scanner in = new Scanner(System.in);

        // prompts user for starting point of ascii table
        System.out.print("Enter starting value: ");
        start = in.nextInt();
        // prompts user for ending point of ascii table
        System.out.print("Enter end value: ");
        end = in.nextInt();

        // for loop to print out the ASCII table
        for (int count = start; count <= end; count++)
        {
            // prints out ASCII table by converting 'count' into a char
            System.out.print(count + " = " + (char)count + "   █   ");
            // carriage return every 10 prints
            if ((count % 10) == 0) System.out.println();
        }
    }
}

Min Max Avg Array with Procedures

The same program of the above code except with procedures to return values of the Minimum, Maximum and Average value

package com;

import java.util.Scanner;

public class MinMaxAvgProcedures {
    public static int min(int min, int value)
    {
        if (min < value) return min; // Return the parsed min value if min is less than user input
        else return value; // Return the user input if min is not less than user input
    }

    public static int max(int value, int max)
    {
        if (max > value) return max; // Return parsed max value if max is less than user input
        else return value; // Return the user input if max is not less than user input
    }

    public static float avg(float avg, int value)
    {
        return avg + value;
    }

    public static void main(String []args) {
        int input, limit = 5, min = 0, max = 0; // Initializes integer variables
        float avg = 0; // initializes float variable 'avg', since we'll need a decimal after finding the average
        Scanner in = new Scanner(System.in); // Initializes scanner

//      Prompts user for a integer to be used for the amount of numbers to input
        System.out.print("Enter the amount of numbers you wish to input: ");
        limit = in.nextInt();

//      Until the limit, will prompt for number input to be calculated
        for (int inputCount = 0; inputCount < limit; inputCount++)
        {
            System.out.print("Enter entry #" + (inputCount + 1) + ": ");
            input = in.nextInt();
//          On first time, set every variable to user input so that they can be compared
            if (inputCount == 0)
            {
                min = input;
                max = input;
                avg = input;
            }
            else
            {
                min = min(min, input); // calls 'min' procedure with previous variables and user input parameters
                max = max(max, input); // calls 'max' procedure with previous variables and user input parameters
//              If the loop is on last cycle, then do divisor for average. Else, just add previous 'avg' values with current user input
                if (inputCount == limit - 1)
                    avg = avg(avg, input) / limit;
                else
                    avg = avg(avg, input);
            }
        }

        System.out.println("Min is " + min);
        System.out.println("Max is " + max);
        System.out.println("Average is " + avg);
    }
}

Programming


QR Code
QR Code java_example (generated for current page)