简单java程序





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

简单的Java程序非常适合评估程序员的编码技能。 您几乎可以在任何面试中找到与编码相关的问题。

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.




接手一个特别复杂的Java项目 复杂java程序_接手一个特别复杂的Java项目


我在这里提供10个简单的Java程序。 它们非常适合编码实践,可以在访谈中使用。 在查看答案之前,请尝试自己编写解决方案,这将使您更有信心,并且可以检查您的解决方案是否良好。 请注意,可以进一步改善解决方案,因此,如果您有更好的方法,请通过评论告知我们。

(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. 空检查以避免NullPointerException
  • Using StringBuilder instead of StringBuffer for better performance. 使用StringBuilder而不是StringBuffer可获得更好的性能。
  • 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. 注意,使用System.out.print函数可以单行打印数字,这很不错。
  • 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. 很高兴看到使用Scanner类接受用户输入。
  • 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. 仅在i <= n / 2之前进行除法检查,思维敏锐且对性能有益。
  • 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. 还要提及在排序中使用Comparable和Comparator会为您增加奖励积分。

(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();
	}

}

(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.

这就是简单的Java面试程序。 仔细研究它们,尝试学习编写代码并打动面试官的最佳方法。

Reference: Really Big Index for Java

参考: Java的真正大索引

翻译自: https://www.journaldev.com/17757/simple-java-programs

简单java程序