Simple Java Programs

Filed Under: Java

Simple java programs are good for assessing the coding skills of a programmer. You will find coding related questions in almost any interview.

The idea of these programming questions is to look into the thought process of the candidate. Most of the times the initial solution is not efficient, which calls for further questions and see if interviewee can improve it further or not.

Simple Java Programs

Here are I am providing 10 simple java programs. They are good for coding practice and can be used in interviews. Please try to write the solution yourself before looking at the answer, that will give you more confidence and you can check if your solution is good or not. Note that the solutions can be improved further, so if you got a better approach then please let us know through comments.
Simple Java Programs

Reverse a String


package com.journaldev.javaprograms;

public class JavaReverseString {

	public static void main(String[] args) {
		System.out.println(reverseString("abc"));
		System.out.println(reverseString("123!@#098*"));
	}

	public static String reverseString(String in) {
		if (in == null)
			return null;
		StringBuilder out = new StringBuilder();

		int length = in.length();

		for (int i = length - 1; i >= 0; i--) {
			out.append(in.charAt(i));
		}

		return out.toString();
	}
}
  • Null check to avoid NullPointerException.
  • Using StringBuilder instead of StringBuffer for better performance.
  • Creating a local variable for input string length, rather than having it in if condition. Less number of function calls, better the performance.
  • Could have been improved by taking user input rather than static testing data

Fibonacci Series


package com.journaldev.javaprograms;

public class FibonacciSeries {

	public static void main(String[] args) {
		printFibonacciSeries(10);
	}

	public static void printFibonacciSeries(int count) {
		int a = 0;
		int b = 1;
		int c = 1;
		for (int i = 1; i <= count; i++) {
			System.out.print(a + ", ");
			a = b;
			b = c;
			c = a + b;
		}

	}
}
  • Program can be improved by taking user input for number of integers to print.
  • Notice the use of System.out.print function to print numbers in single line, good job.
  • Fibonacci numbers starts from 0 or 1, above program can be extended to take user input for starting point.
  • Nicely written simple program, good to see no use of recursion or complex coding.

Prime Number Check


package com.journaldev.javaprograms;

import java.util.Scanner;

public class CheckPrimeNumber {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);
		System.out.print("Enter number to check for prime:");
		int n = s.nextInt();
		s.close();
		checkPrime(n);
	}

	private static void checkPrime(int n) {
		if (n == 0 || n == 1) {
			System.out.println(n + " is not a prime number");
			return;
		}
		if (n == 2) {
			System.out.println(n + " is a prime number");
		}
		for (int i = 2; i <= n / 2; i++) {
			if (n % i == 0) {
				System.out.println(n + " is not a prime number");
				return;
			}
		}
		System.out.println(n + " is a prime number");
	}

}
  • Good to see use of Scanner class to take user input.
  • Notice the few if checks to check the numbers where rules are different i.e. 0,1 and 2. 0 and 1 are not prime numbers and 2 is the only even prime number.
  • The division check is done only till i <= n / 2, smart thinking and good for performance.
  • The method will fail incase of negative integers - Either let user know to enter positive integer in the main method Or make the integer positive and then process it.

Check for Palindrome String


package com.journaldev.javaprograms;

import java.util.Scanner;

public class PalindromeString {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter String to check for Palindrome:");
		String str = s.next();
		s.close();

		checkPalindrome(str);
	}

	private static void checkPalindrome(String str) {
		char[] charArray = str.toCharArray();
		StringBuilder sb = new StringBuilder();
		for (int i = charArray.length - 1; i >= 0; i--) {
			sb.append(charArray[i]);
		}
		if (sb.toString().equalsIgnoreCase(str))
			System.out.println(str + " is palindrome.");
		else
			System.out.println(str + " is not palindrome");
	}

}
  • Creating a new string in reverse order using StringBuilder and then checking if its value is same as the original string.
  • Implementation can be improved by comparing the characters from both end. If String length is 5 then it's palindrome if chars at 0th==4th and 1st==3rd. No need to create a separate string. Try to write code for this and post in comments section.

Sort an array programmatically


package com.journaldev.javaprograms;

import java.util.Arrays;

public class JavaArraySort {

	public static void main(String[] args) {
		int[] array = {2,1,5,3,4,6,7};
		
		int[] sortedArray = bubbleSortAscending(array);
		
		System.out.println(Arrays.toString(sortedArray));
	}

	public static int[] bubbleSortAscending(int[] arr){
        int temp;
        for(int i=0; i < arr.length-1; i++){
             
            for(int j=1; j < arr.length-i; j++){
                if(arr[j-1] > arr[j]){
                    temp=arr[j-1];
                    arr[j-1] = arr[j];
                    arr[j] = temp;
                }
            }
            //check that last index has highest value in first loop,
            // second last index has second last highest value and so on
            System.out.println("Array after "+(i+1)+"th iteration:"+Arrays.toString(arr));
        }
        return arr;
    }
}
  • There are many sorting algorithms, bubble sort is easier to implement.
  • Sorting is complex and you should rely on Java API methods for sorting a collection or array for better performance that inventing the wheel again.
  • Also mention the use of Comparable and Comparator in sorting will add bonus points for you.

Read 3 input Strings, concat and print


package com.journaldev.javaprograms;

import java.util.Scanner;

public class ReadStringAndConcat {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter number of Strings to Concatenate:");
		int n = scanner.nextInt();
		
		String[] input = new String[n];
		for(int i=0; i<n; i++) {
			System.out.println("Please enter String number "+n+" and press enter:");
			input[i] = scanner.next();
		}
		//close Scanner and avoid resource leak
		scanner.close();
		String output = concat(input);
		System.out.println("Concatenation Result = "+output);
	}

	private static String concat(String[] input) {
		StringBuilder sb = new StringBuilder();
		for(String s : input) sb.append(s);
		return sb.toString();
	}

}
  • Program is flexible to concat any number of strings, that shows thinking to code reuse and keeping it flexible.
  • Proper messages to guide the user when someone runs the program.
  • Use of StringBuilder rather than String + operator for concatenation.
  • Closing resources as soon as we are done with it, hence avoiding memory leak. Shows good programming habits.

Remove odd numbers from integer array


package com.journaldev.javaprograms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class RemoveOddNumbers {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter comma separated numbers for input int array, for example '1,2,3,4'");
		String input = scanner.next();
		scanner.close();
		//convert to int array
		String[] inArray = input.split(",");
		int [] intArray = new int[inArray.length];
		int index = 0;
		for(String s : inArray) {
			intArray[index] = Integer.parseInt(s.trim());
			index++;
		}
		//call a function to remove odd numbers
		Integer[] result = removeOddNumbers(intArray);
		
		System.out.println(Arrays.toString(result));
	}

	private static Integer[] removeOddNumbers(int[] intArray) {
		//we will have to use list because we don't know exact size of the result array
		List<Integer> list = new ArrayList<>();
		for(int i : intArray) {
			if(i%2 == 0) list.add(i);
		}
		
		return list.toArray(new Integer[list.size()]);
	}

}

If you are reading this code, you should see that it adheres to all the points mentioned above. Try to write clean and simple code, follow best practices, naming conventions for methods and variables and you will be good.

Delete all matching elements from a list


package com.journaldev.javaprograms;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class DeleteFromList {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter comma separated list of Strings. For example 'a,b,c,b,a'");
		String input = scanner.next();
		System.out.println("Enter String to remove from the input list.");
		String strToDelete = scanner.next();
		scanner.close();

		List<Object> inputList = new ArrayList<>();
		String[] inputStrings = input.split(",");
		for (String s : inputStrings)
			inputList.add(s.trim());
		
		inputList = removeAll(inputList, strToDelete);
		System.out.println("Result List = "+inputList);
	}

	private static List<Object> removeAll(List<Object> inputList, Object objToDelete) {
		Iterator<Object> it = inputList.iterator();
		while(it.hasNext()) {
			Object obj = it.next();
			if(obj.equals(objToDelete)) it.remove();
		}
		return inputList;
	}

}
  • Notice the removeAll method is created for list of objects, so it will work with any type of list. This is how we write reusable code.
  • Using iterator to remove the element from the list.
  • Trimming the input to remove any accidental white spaces from input strings.

Average of numbers with rounding half-up and scale 2


package com.journaldev.javaprograms;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

public class AverageOfNumbers {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Please enter the total number of integers.");
		int count = scanner.nextInt();

		int sum = 0;

		for (int i = 0; i < count; i++) {
			System.out.println("Please enter number " + (i + 1) + ":");
			sum += scanner.nextInt();
		}
		System.out.println("Sum=" + sum + ",Count=" + count);

		BigDecimal average = new BigDecimal((double) sum / count);
		average = average.setScale(2, RoundingMode.HALF_UP);
		System.out.println("Average of entered numbers = " + average);
		scanner.close();
	}

}

java basic programs, java interview programs

Swapping two numbers


package com.journaldev.javaprograms;

import java.util.Scanner;

public class SwappingNumbers {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("Enter the first number:");
		int first = scanner.nextInt();
		System.out.println("Enter the second number:");
		int second = scanner.nextInt();
		scanner.close();

		System.out.println("Initial value of numbers are: "+first+" and "+second);
		
		first = first + second;
		second = first -second;
		first = first - second;
		
		System.out.println("Value of numbers after swapping are: "+first+" and "+second);

	}

}

We can easily swap numbers using a temporary variable. But if you can do it without that, then it's awesome.

That's all for simple java programs for interviews. Go through them and try to learn the best ways to write code and impress the interviewer.

Reference: Really Big Index for Java

Comments

  1. Nidhi says:

    public static void checkPalindrome(String str){
    char[] ch= str.toCharArray();
    int length= ch.length;
    boolean flag=true;

    for(int i=0, j=length-1;i<length; i++, j–){
    if(ch[i]==ch[j]){
    continue;
    }else{
    flag= false;
    }
    }

    if(flag){
    System.out.println("palindrome");
    }
    else{
    System.out.println("not a palindrome");
    }

    }

  2. Nivetha says:

    For Pallindrom position based check is suitable for odd length only .
    Eg: string STR=madam -length 5
    If(STR.charAt(0)==STR.charAt(4) && STR.charAt(1)==STR.charAt(3))
    S.o.p(“Pallindrom”);

    Whether it’s an effective way????

    1. Pankaj says:

      You can simply write code based on whether string length is odd or even.

  3. Nisha says:

    I am very much satiesfied with this blog, you explained each and every steps clearly. Good platform to enhance our career.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages