Practice Java | Java tasks for beginners examples

We have collected for you practical Java programming tasks for beginner developers with examples of solutions. These are simple Java interview tasks that will allow you to practice or prepare yourself for an interview.

Task 1

Write a program that prints the numbers from 1 to 10 on the screen.

The easiest way to solve this Java problem is to use a loop for:

    public class NumbersFromOneToTen {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
    }
}

Task 2

Write a program that finds the sum of all numbers from 1 to 100.

In this case, it is also quite sufficient to calculate the sum in the cycle for:

    public class SumOfNumbers {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println("Сумма чисел от 1 до 100: " + sum);
    }
}

Task 3

Find the factorial of the given number.

The factorial of a number is the product of all natural numbers from 1 to a given number. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.

In Java, a program to find the factorial of a given number can be written using a loop for or recursion. Below is an example program using a loop for:

    public class FactorialCalculator {
    public static void main(String[] args) {
        int number = 5; // Заданное число, для которого мы хотим найти факториал
        int factorial = 1; // Изначально присваиваем факториалу значение 1

        // Используем цикл for для нахождения факториала
        for (int i = 1; i <= number; i++) {
            factorial *= i; // Умножаем текущее значение факториала на текущее значение i
        }

        // Выводим результат
        System.out.println("Факториал числа " + number + " равен " + factorial);
    }
}

When you run this program, you will get the output:

    Факториал числа 5 равен 120

Note that for large values number, the factorial can become a very large number, exceeding the maximum value of the data type. In such cases, it is better to use data types with a large range, such as long or BigInteger.

Task 4

Write a test to see if a given number is prime.

For some reason, with this task in Java, many novice developers have problems at interviews. In fact, the solution to this Java problem is as simple as possible:

    public class PrimeNumberCheck {
    public static void main(String[] args) {
        int number = 17;
        boolean isPrime = true;
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }
        System.out.println(number + " является простым числом: " + isPrime);
    }
}

Task 5

Sort the array by value in ascending and descending order.

To sort an array by value in ascending and descending order in Java, you can use the sort methods available in Java Arrays class. To sort in ascending order, use the method Arrays.sort()and for sorting in descending order, you can use the class Comparator and method Arrays.sort():

    import java.util.Arrays;
import java.util.Comparator;

public class ArraySorting {
    public static void main(String[] args) {
        int[] array = {5, 2, 8, 1, 3};

        // Сортировка массива по возрастанию
        Arrays.sort(array);

        System.out.println("Массив, отсортированный по возрастанию:");
        for (int num : array) {
            System.out.print(num + " ");
        }

        // Сортировка массива по убыванию
        Integer[] boxedArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
        Arrays.sort(boxedArray, Comparator.reverseOrder());

        System.out.println("\nМассив, отсортированный по убыванию:");
        for (int num : boxedArray) {
            System.out.print(num + " ");
        }
    }
}

Task 6

Write a simple Java code that converts an integer to a string, which can be applied to any number system.

Solving this simple Java problem is not difficult. To convert an integer to a string in any number system, you can use the method Integer.toString() or Long.toString()which allow you to specify the base of the number system as the second argument:

    public class NumberToStringConverter {
    public static void main(String[] args) {
        int number = 123;
        int base = 16; // Задаем систему счисления (например, 16 для шестнадцатеричной)

        String numberAsString = convertToString(number, base);
        System.out.println(number + " в системе счисления " + base + ": " + numberAsString);
    }

    public static String convertToString(int number, int base) {
        return Integer.toString(number, base);
    }
}

Task 7

Write a program that inverts an array (reverses the order of elements).

    public class ArrayReverse {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int temp;
        int length = array.length;
        for (int i = 0; i < length / 2; i++) {
            temp = array[i];
            array[i] = array[length - i - 1];
            array[length - i - 1] = temp;
        }
        System.out.print("Инвертированный массив: ");
        for (int element : array) {
            System.out.print(element + " ");
        }
    }
}

Task 8

Sort the dictionary by value in ascending and descending order. Explain the solution.

Yes, this practice task in Java is similar to task five. However!

To sort a dictionary (Map) by value in ascending and descending order in Java you can use the interface Comparator and sorting methods available in the Java Collections Framework. To do this, you need to represent the dictionary as a list of key-value pairs and then sort this list based on the values. Suppose we have a dictionary Map<String, Integer> with names and their ages:

    import java.util.*;

public class DictionarySorting {
    public static void main(String[] args) {
        // Создаем и заполняем словарь имен и возрастов
        Map<String, Integer> dictionary = new HashMap<>();
        dictionary.put("Анна", 25);
        dictionary.put("Петр", 32);
        dictionary.put("Мария", 18);
        dictionary.put("Иван", 40);
        dictionary.put("Елена", 28);

        // Сортировка словаря по значению (возрастанию)
        List<Map.Entry<String, Integer>> sortedAscending = new ArrayList<>(dictionary.entrySet());
        Collections.sort(sortedAscending, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        // Вывод отсортированного словаря (по возрастанию)
        System.out.println("Словарь, отсортированный по возрастанию:");
        for (Map.Entry<String, Integer> entry : sortedAscending) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Сортировка словаря по значению (убыванию)
        List<Map.Entry<String, Integer>> sortedDescending = new ArrayList<>(dictionary.entrySet());
        Collections.sort(sortedDescending, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        // Вывод отсортированного словаря (по убыванию)
        System.out.println("\nСловарь, отсортированный по убыванию:");
        for (Map.Entry<String, Integer> entry : sortedDescending) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

We hope you enjoyed our selection of Java tasks. Write your solutions, as well as the tasks that came across to you at the interviews.

We also recommend solving problems in Python and JavaScript.

Similar Posts

Leave a Reply

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