Java examples and tasks

Java Programming Exercises, Practice, Solution

Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and services.

The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. A sample solution is provided for each exercise. It is recommended to do these exercises by yourself first before checking the solution.

Hope, these exercises help you to improve your Java programming coding skills. Currently, following sections are available, we are working hard to add more exercises . Happy Coding!

List of Java Exercises:

  • Basic Exercises Part-I [ 150 Exercises with Solution ]
  • Basic Exercises Part-II [ 99 Exercises with Solution ]
  • Data Types Exercises [ 15 Exercises with Solution ]
  • Conditional Statement Exercises [ 32 Exercises with Solution ]
  • Java recursive method Exercises [ 15 Exercises with Solution ]
  • Java Enum Types Exercises [ 5 Exercises with Solution ]
  • Exercises on handling and managing exceptions in Java [ 7 Exercises with Solution ]
  • Array [ 77 Exercises with Solution ]
  • Java Inheritance Exercises [ 9 exercises with solution ]
  • Java Abstract Classes Exercises [ 12 exercises with solution ]
  • Java Thread Exercises [ 7 exercises with solution ]
  • Java Miltithreading Exercises [ 10 exercises with solution ]
  • Java Lambda expression Exercises [ 25 exercises with solution ]
  • Java Generic Methods Exercises [ 7 exercises with solution ]
  • Object-Oriented Programming [ 19 Exercises with Solution ]
  • Java Interface Exercises [ 11 exercises with solution ]
  • Java Encapsulation Exercises [ 7 exercises with solution ]
  • Java Polymorphism Exercises [ 12 exercises with solution ]
  • Stack [ 29 Exercises with Solution ]
  • String [ 107 Exercises with Solution ]
  • Streams [ 8 Exercises with Solution ]
  • Date Time [ 44 Exercises with Solution ]
  • Methods [ 23 Exercises with Solution ]
  • Numbers [ 28 Exercises with Solution ]
  • Input-Output-File-System [ 18 Exercises with Solution ]
  • Collection [ 126 Exercises with Solution ]
  • Math [ 27 Exercises with Solution ]
  • Sorting [ 19 Exercises with Solution ]
  • Search [ 7 Exercises with Solution ]
  • Regular Expression [ 30 Exercises with Solution ]
  • More..

Note: If you are not habituated with Java programming you can learn from the following :

More to Come !

Popularity of Programming Language Worldwide, July 2023 compared to a year ago:

`

Rank Change Language Share Trend
1 Python 27.43 % -0.2 %
2 Java 16.19 % -1.0%
3 Javascript 9.4 % -0.1%
4 C# 6.77 % -0.3%
5 C/C++ 6.44 % +0.2 %
6 PHP 5.03 % -0.4 %
7 R 4.45% +0.1%
8 TypeScript 3.02 % +0.3%
9 up arrow Swift 2.42 % +0.4%
10 up arrow Rust 2.15% +0.6%
11 down arrow Objective-C 2.13% +0.0%
12 down arrow Go 2.01% +0.0%
13 down arrow Kotlin 1.79 % +0.0%
14 Matlab 1.59 % +0.0%
15 Ruby 1.1% -0.0%
16 up arrow Ada 1.06 % +0.3 %
17 up arrow Powershell 1.06 % +0.2 %
18 down arrow VBA 0.91 % -0.1 %
19 down arrow Dart 0.86 % -0.0 %
20 up arrow Lua 0.64 % +0.0 %
21 Visual Basic 0.58 % -0.0 %
22 up arrow Abap 0.57 % +0.1 %
23 down arrow Scala 0.57 % -0.2 %
24 down arrow Julia 0.42 % -0.1 %
25 Groovy 0.42 % -0.0 %
26 up arrow Haskell 0.3 % +0.0 %
27 down arrow Perl 0.29 % -0.0 %
28 Cobol 0.24 % -0.0 %
29 Delphi/Pascal 0.16 % +0.2 %
Читайте также:  Java tar to zip

TIOBE Index for July 2023

July 2023 July 2022 Change Programming Language Ratings Change
1 1 Python 13.42% -0.01%
2 2 C 11.56% -1.57%
3 4 up arrow C++ 10.80% +0.79%
4 3 down arrow Java 10.50% -1.09%
5 5 C# 6.87% +1.21%
6 7 JavaScript 3.11% +1.34%
7 6 down arrow Visual Basic 2.90% -2.07%
8 9 up arrow SQL 1.48% -0.16%
9 11 up arrow PHP 1.41% +0.21%
10 20 up arrow MATLAB 1.26% +0.53%
11 18 up arrow Fortran 1.25% +0.49%
12 21 up arrow Scratch 1.07% +0.35%
13 12 down arrow Go 1.07% -0.07%
14 8 down arrow Assembly language 1.01% -0.64%
15 14 down arrow Delphi/Object Pascal 0.98% -0.08%
16 15 down arrow Ruby 0.91% -0.08%
17 29 up arrow Rust 0.89% +0.47%
18 10 down arrow Swift 0.88% -0.39%
19 19 R 0.87% +0.11%
20 26 up arrow COBOL 0.86% +0.33%

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution
[ Want to contribute to Java exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

How to call getClass() from a static method in Java?

Just use TheClassName.class instead of getClass()

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

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.

Читайте также:  Bytearray from hex python

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

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 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 // Выводим результат 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 > 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 = ; // Сортировка массива по возрастанию 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.

Читайте также:  Import custom module in python

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 = ; 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 with names and their ages:

import java.util.*; public class DictionarySorting < public static void main(String[] args) < // Создаем и заполняем словарь имен и возрастов Mapdictionary = new HashMap<>(); dictionary.put("Анна", 25); dictionary.put("Петр", 32); dictionary.put("Мария", 18); dictionary.put("Иван", 40); dictionary.put("Елена", 28); // Сортировка словаря по значению (возрастанию) List sortedAscending = new ArrayList<>(dictionary.entrySet()); Collections.sort(sortedAscending, new Comparator() < @Override public int compare(Map.Entryo1, Map.Entry o2) < return o1.getValue().compareTo(o2.getValue()); >>); // Вывод отсортированного словаря (по возрастанию) System.out.println("Словарь, отсортированный по возрастанию:"); for (Map.Entry entry : sortedAscending) < System.out.println(entry.getKey() + ": " + entry.getValue()); >// Сортировка словаря по значению (убыванию) List sortedDescending = new ArrayList<>(dictionary.entrySet()); Collections.sort(sortedDescending, new Comparator() < @Override public int compare(Map.Entryo1, Map.Entry o2) < return o2.getValue().compareTo(o1.getValue()); >>); // Вывод отсортированного словаря (по убыванию) System.out.println("\nСловарь, отсортированный по убыванию:"); for (Map.Entry 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.

Источник

Оцените статью