Java Basic Programming : Exercises, Practice, Solution
Java Basic Exercises [150 exercises with solution]
[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]
1. Hello and Name Printer
Write a Java program to print 'Hello' on screen and your name on a separate line.
Expected Output :
Hello
Alexandra Abramov
2. Sum of Two Numbers
Write a Java program to print the sum of two numbers.
Test Data:
74 + 36
Expected Output :
110
3. Division of Two Numbers
Write a Java program to divide two numbers and print them on the screen.
Test Data :
50/3
Expected Output :
16
4. Arithmetic Operations
Write a Java program to print the results of the following operations.
Test Data:
a. -5 + 8 * 6
b. (55+9) % 9
c. 20 + -3*5 / 8
d. 5 + 15 / 3 * 2 - 8 % 3
Expected Output :
43
1
19
13
5. Product of Two Numbers
Write a Java program that takes two numbers as input and displays the product of two numbers.
Test Data:
Input first number: 25
Input second number: 5
Expected Output :
25 x 5 = 125
6. Basic Arithmetic Operations
Write a Java program to print the sum (addition), multiply, subtract, divide and remainder of two numbers.
Test Data:
Input first number: 125
Input second number: 24
Expected Output :
125 + 24 = 149
125 - 24 = 101
125 x 24 = 3000
125 / 24 = 5
125 mod 24 = 5
7. Multiplication Table
Write a Java program that takes a number as input and prints its multiplication table up to 10.
Test Data:
Input a number: 8
Expected Output :
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
...
8 x 10 = 80
8. Pattern Display: JAVA
Write a Java program to display the following pattern.
Sample Pattern :
J a v v a J a a v v a a J J aaaaa V V aaaaa JJ a a V a a
9. Expression Evaluation
Write a Java program to compute the specified expressions and print the output.
Test Data:
((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5))
Expected Output
2.138888888888889
10. Formula Computation
Write a Java program to compute a specified formula.
Specified Formula :
4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11))
Expected Output
2.9760461760461765
11. Circle: Area and Perimeter
Write a Java program to print the area and perimeter of a circle.
Test Data:
Radius = 7.5
Expected Output
Perimeter is = 47.12388980384689
Area is = 176.71458676442586
12. Average of Three Numbers
Write a Java program that takes three numbers as input to calculate and print the average of the numbers.
Click me to see the solution
13. Rectangle: Area and Perimeter
Write a Java program to print the area and perimeter of a rectangle.
Test Data:
Width = 5.5
Height = 8.5
Expected Output
Area is 5.6 * 8.5 = 47.60
Perimeter is 2 * (5.6 + 8.5) = 28.20
14. American Flag Display
Write a Java program to print an American flag on the screen.
Expected Output
* * * * * * ================================== * * * * * ================================== * * * * * * ================================== * * * * * ================================== * * * * * * ================================== * * * * * ================================== * * * * * * ================================== * * * * * ================================== * * * * * * ================================== ============================================== ============================================== ============================================== ============================================== ============================================== ==============================================
15. Swap Variables
Write a Java program to swap two variables.
Click me to see the solution
16. Face Printer
Write a Java program to print a face.
Expected Output
+"""""+ [| o o |] | ^ | | '-' | +-----+
17. Binary Addition
Write a Java program to add two binary numbers.
Input Data:
Input first binary number: 10
Input second binary number: 11
Expected Output
Sum of two binary numbers: 101
18. Binary Multiplication
Write a Java program to multiply two binary numbers.
Input Data:
Input the first binary number: 10
Input the second binary number: 11
Expected Output
Product of two binary numbers: 110
19. Decimal to Binary Converter
Write a Java program to convert an integer number to a binary number.
Input Data:
Input a Decimal Number : 5
Expected Output
Binary number is: 101
20. Decimal to Hexadecimal Converter
Write a Java program to convert a decimal number to a hexadecimal number.
Input Data:
Input a decimal number: 15
Expected Output
Hexadecimal number is : F
21. Decimal to Octal Converter
Write a Java program to convert a decimal number to an octal number.
Input Data:
Input a Decimal Number: 15
Expected Output
Octal number is: 17
22. Binary to Decimal Converter
Write a Java program to convert a binary number to a decimal number.
Input Data:
Input a binary number: 100
Expected Output
Decimal Number: 4
23. Binary to Hexadecimal Converter
Write a Java program to convert a binary number to a hexadecimal number.
Input Data:
Input a Binary Number: 1101
Expected Output
HexaDecimal value: D
24. Binary to Octal Converter
Write a Java program to convert a binary number to an octal number.
Input Data:
Input a Binary Number: 111
Expected Output
Octal number: 7
25. Octal to Decimal Converter
Write a Java program to convert a octal number to a decimal number.
Input Data:
Input any octal number: 10
Expected Output
Equivalent decimal number: 8
26. Octal to Binary Converter
Write a Java program to convert a octal number to a binary number.
Input Data:
Input any octal number: 7
Expected Output
Equivalent binary number: 111
27. Octal to Hexadecimal Converter
Write a Java program to convert a octal number to a hexadecimal number.
Input Data:
Input a octal number : 100
Expected Output
Equivalent hexadecimal number: 40
28. Hexadecimal to Decimal Converter
Write a Java program to convert a hexadecimal value into a decimal number.
Input Data:
Input a hexadecimal number: 25
Expected Output
Equivalent decimal number is: 37
29. Hexadecimal to Binary Converter
Write a Java program to convert a hexadecimal number into a binary number.
Input Data:
Enter Hexadecimal Number : 37
Expected Output
Equivalent Binary Number is: 110111
30. Hexadecimal to Octal Converter
Write a Java program to convert a hexadecimal value into an octal number.
Input Data:
Input a hexadecimal number: 40
Expected Output
Equivalent of octal number is: 100
31. Check Java Installation
Write a Java program to check whether Java is installed on your computer.
Expected Output
Java Version: 1.8.0_71 Java Runtime Version: 1.8.0_71-b15 Java Home: /opt/jdk/jdk1.8.0_71/jre Java Vendor: Oracle Corporation Java Vendor URL: http://Java.oracle.com/ Java Class Path: .
32. Compare Two Numbers
Write a Java program to compare two numbers.
Input Data:
Input first integer: 25
Input second integer: 39
Expected Output
25 != 39 25 < 39 25 <= 39
33. Sum of Digits
Write a Java program and compute the sum of an integer's digits.
Input Data:
Input an integer: 25
Expected Output
The sum of the digits is: 7
34. Hexagon Area
Write a Java program to compute hexagon area.
Area of a hexagon = (6 * s^2)/(4*tan(π/6))
where s is the length of a side
Input Data:
Input the length of a side of the hexagon: 6
Expected Output
The area of the hexagon is: 93.53074360871938
35. Polygon Area
Write a Java program to compute the area of a polygon.
Area of a polygon = (n*s^2)/(4*tan(π/n))
where n is n-sided polygon and s is the length of a side
Input Data:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Expected Output
The area is: 130.82084798405722
36. Distance Between Two Points
Write a Java program to compute the distance between two points on the earth's surface.
Distance between the two points [ (x1,y1) & (x2,y2)]
d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2))
Radius of the earth r = 6371.01 Kilometers
Input Data:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 35.5
Input the longitude of coordinate 2: 25.5
Expected Output
The distance between those points is: 1480.0848451069087 km
37. Reverse a String
Write a Java program to reverse a string.
Input Data:
Input a string: The quick brown fox
Expected Output
Reverse string: xof nworb kciuq ehT
38. Count Characters in String
Write a Java program to count letters, spaces, numbers and other characters in an input string.
Expected Output
The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33 letter: 23 space: 9 number: 10 other: 6
39. Unique Three-Digit Numbers
Write a Java program to create and display a unique three-digit number using 1, 2, 3, 4. Also count how many three-digit numbers are there.
Expected Output
123 124 ... 431 432 Total number of the three-digit-number is 24
40. List Available Charsets
Write a Java program to list the available character sets in charset objects.
Expected Output
List of available character sets: Big5 Big5-HKSCS CESU-8 EUC-JP EUC-KR GB18030 GB2312 GBK ... x-SJIS_0213 x-UTF-16LE-BOM X-UTF-32BE-BOM X-UTF-32LE-BOM x-windows-50220 x-windows-50221 x-windows-874 x-windows-949 x-windows-950 x-windows-iso2022jp
41. ASCII Value Finder
Write a Java program to print the ASCII value of a given character.
Expected Output
The ASCII value of Z is :90
42. Input and Display Password
Write a Java program to input and display your password.
Expected Output
Input your Password: Your password was: abc@123
43. Twinkle Poem Formatter
Write a Java program to print the following string in a specific format (see output).
Sample Output
Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are
44. Compute n+nn+nnn
Write a Java program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample Output:
Input number: 5 5 + 55 + 555
45. File Size Finder
Write a Java program to find the size of a specified file.
Sample Output:
/home/students/abc.txt : 0 bytes /home/students/test.txt : 0 bytes
46. Display System Time
Write a Java program to display system time.
Sample Output:
Current Date time: Fri Jun 16 14:17:40 IST 2017
47. Formatted Date and Time
Write a Java program to display the current date and time in a specific format.
Sample Output:
Now: 2017/06/16 08:52:03.066
48. Print Odd Numbers (1-99)
Write a Java program to print odd numbers from 1 to 99. Prints one number per line.
Sample Output:
1 3 5 7 9 11 .... 91 93 95 97 99
49. Check Even or Odd
Write a Java program to accept a number and check whether the number is even or not. Prints 1 if the number is even or 0 if odd.
Sample Output:
Input a number: 20 1
50. Divisible by 3, 5, Both
Write a Java program to print numbers between 1 and 100 divisible by 3, 5 and both.
Sample Output:
Divided by 3: 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57 , 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, Divided by 5: 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, Divided by 3 & 5: 15, 30, 45, 60, 75, 90,
51. String to Integer Conversion
Write a Java program to convert a string to an integer.
Sample Output:
Input a number(string): 25 The integer value is: 25
52. Sum Equals Third Integer
Write a Java program to calculate the sum of two integers and return true if the sum is equal to a third integer.
Sample Output:
Input the first number : 5 Input the second number: 10 Input the third number : 15 The result is: true
53. Number Comparison Logic
Write a Java program that accepts three integers from the user. It returns true if the second number is higher than the first number and the third number is larger than the second number. If "abc" is true, the second number does not need to be larger than the first number.
Sample Output:
Input the first number : 5 Input the second number: 10 Input the third number : 15 The result is: true
54. Same Rightmost Digit Check
Write a Java program that accepts three integers from the user and returns true if two or more of them (integers) have the same rightmost digit. The integers are non-negative.
Sample Output:
Input the first number : 5 Input the second number: 10 Input the third number : 15 The result is: true
55. Seconds to Time Conversion
Write a Java program to convert seconds to hours, minutes and seconds.
Sample Output:
Input seconds: 86399 23:59:59
56. Count Divisibles in Range
Write a Java program to find the number of values in a given range divisible by a given value.
For example x = 5, y=20 and p =3, find the number of integers within the range x..y and that are divisible by p i.e. { i :x ≤ i ≤ y, i mod p = 0 }
Sample Output:
5
57. Count Factors of Integer
Write a Java program to accept an integer and count the factors of the number.
Sample Output:
Input an integer: 25 3
58. Capitalize Each Word
Write a Java program to capitalize the first letter of each word in a sentence.
Sample Output:
Input a Sentence: the quick brown fox jumps over the lazy dog. The Quick Brown Fox Jumps Over The Lazy Dog.
59. Convert to Lowercase
Write a Java program to convert a string into lowercase.
Sample Output:
Input a String: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. the quick brown fox jumps over the lazy dog.
60. Find Penultimate Word
Write a Java program to find the penultimate (next to the last) word in a sentence.
Sample Output:
Input a String: The quick brown fox jumps over the lazy dog. Penultimate word: lazy
61. Reverse Word
Write a Java program to reverse a word.
Sample Output:
Input a word: dsaf Reverse word: fasd
62. Check Subtraction Difference
Write a Java program that accepts three integer values and returns true if one is 20 or more less than the others' subtractions.
Sample Output:
Input the first number : 15 Input the second number: 20 Input the third number : 25 false
63. Largest or Smallest Value
Write a Java program that accepts two integer values from the user and returns the largest value. However if the two values are the same, return 0 and find the smallest value if the two values have the same remainder when divided by 6.
Sample Output:
Input the first number : 12 Input the second number: 13 Result: 13
64. Common Digit in Numbers
Write a Java program that accepts two integer values between 25 and 75 and returns true if there is a common digit in both numbers.
Sample Output:
Input the first number : 35 Input the second number: 45 Result: true
65. Custom Modulus
Write a Java program to calculate the modules of two numbers without using any inbuilt modulus operator.
Sample Output:
Input the first number : 19 Input the second number: 7 5
66. Sum of 100 Primes
Write a Java program to compute the sum of the first 100 prime numbers.
Sample Output:
Sum of the first 100 prime numbers: 24133
67. Insert Word in Middle
Write a Java program to insert a word in the middle of another string.
Insert "Tutorial" in the middle of "Python 3.0", so the result will be Python Tutorial 3.0.
Sample Output:
Python Tutorial 3.0
68. Repeat Last 3 Characters
Write a Java program to create another string of 4 copies of the last 3 characters of the original string. The original string length must be 3 and above.
Sample Output:
3.03.03.03.0
69. Extract First Half
Write a Java program to extract the first half of a even string.
Test Data: Python
Sample Output:
Pyt
70. Short + Long + Short String
Write a Java program to create a string in the form of short_string + long_string + short_string from two strings. The strings must not have the same length.
Test Data: Str1 = Python
Str2 = Tutorial
Sample Output:
PythonTutorialPython
71. Remove First Char and Concatenate
Write a Java program to create the concatenation of the two strings except removing the first character of each string. The length of the strings must be 1 and above.
Test Data: Str1 = Python
Str2 = Tutorial
Sample Output:
ythonutorial
72. First 3 Chars or #
Write a Java program to create a string taking the first three characters from a given string. If the string length is less than 3 use "#" as substitute characters.
Test Data: Str1 = " "
Sample Output:
###
73. First and Last Char Combo
Write a Java program to create a string taking the first and last characters from two given strings. If the length of each string is 0 use "#" for missing characters.
Test Data: str1 = "Python"
str2 = " "
Sample Output:
P#
74. 10 as First or Last in Array
Write a Java program to test if 10 appears as the first or last element of an array of integers. The array length must be broader than or equal to 2.
Sample Output:
Test Data: array = 10, -20, 0, 30, 40, 60, 10
true
75. First and Last Element Same
Write a Java program to test if the first and last elements of an array of integers are the same. The array length must be broader than or equal to 2.
Test Data: array = 50, -20, 0, 30, 40, 60, 10
Sample Output:
false
76. First and Last of Two Arrays
Write a Java program to test if the first and last element of two integer arrays are the same. The array length must be greater than or equal to 2.
Test Data: array1 = 50, -20, 0, 30, 40, 60, 12
array2 = 45, 20, 10, 20, 30, 50, 11
Sample Output:
false
77. New Array with Ends of Two Arrays
Write a Java program to create an array of length 2 from two integer arrays with three elements. The newly created array will contain the first and last elements from the two arrays.
Test Data: array1 = 50, -20, 0
array2 = 5, -50, 10
Sample Output:
Array1: [50, -20, 0] Array2: [5, -50, 10] New Array: [50, 10]
78. Contains 4 or 7
Write a Java program to test that a given array of integers of length 2 contains a 4 or a 7.
Sample Output:
Original Array: [5, 7] true
79. Rotate Array Left
Write a Java program to rotate an array (length 3) of integers in the left direction.
Sample Output:
Original Array: [20, 30, 40] Rotated Array: [30, 40, 20]
80. Largest of First or Last Element
Write a Java program to get the largest value between the first and last elements of an array (length 3) of integers.
Sample Output:
Original Array: [20, 30, 40] Larger value between first and last element: 40
81. Swap First and Last Elements
Write a Java program to swap the first and last elements of an array (length must be at least 1) and create another array.
Sample Output:
Original Array: [20, 30, 40] New array after swaping the first and last elements: [40, 30, 20]
82. Largest of First, Last, Middle
Write a Java program to find the largest element between the first, last, and middle values in an array of integers (even length).
Sample Output:
Original Array: [20, 30, 40, 50, 67] Largest element between first, last, and middle values: 67
83. Multiply Array Elements
Write a Java program to multiply the corresponding elements of two integer arrays.
Sample Output:
Array1: [1, 3, -5, 4] Array2: [1, 4, -5, -2] Result: 1 12 25 -8
84. Add Last 3 Chars to Both Ends
Write a Java program to take the last three characters from a given string. It will add the three characters at both the front and back of the string. String length must be greater than three and more.
Test data: "Python" will be "honPythonhon"
Sample Output:
honPythonhon
85. String Starts with Word
Write a Java program to check if a string starts with a specified word.
Sample Data: string1 = "Hello how are you?"
Sample Output:
true
86. Collatz Conjecture Simulation
Write a Java program starting with an integer n, divide it by 2 if it is even, or multiply it by 3 and add 1 if it is odd. Repeat the process until n = 1.
87. Digit Sum in Words
Write a Java program that then reads an integer and calculates the sum of its digits and writes the number of each digit of the sum in English.
88. System Environment and Properties
Write a Java program to get the current system environment and system properties.
Click me to see the solution
89. Check Security Manager
Write a Java program to check whether a security manager has already been established for the current application or not.
Click me to see the solution
90. Environment Variables
Write a Java program to get the value of environment variables PATH, TEMP, USERNAME.
Click me to see the solution
91. Code Execution Time in Nanoseconds
Write a Java program to measure how long code executes in nanoseconds.
Click me to see the solution
92. Count Even and Odd in Array
Write a Java program to count the number of even and odd elements in a given array of integers.
Click me to see the solution
93. Check Adjacent 10s or 20s
Write a Java program to test if an array of integers contains an element 10 next to 10 or an element 20 next to 20, but not both.
Click me to see the solution
94. Rearrange Odd and Even Numbers
Write a Java program to rearrange all the elements of a given array of integers so that all the odd numbers come before all the even numbers.
Click me to see the solution
95. Create String Array 0 to N-1
Write a Java program to create an array (length # 0) of string values. The elements will contain "0", "1", "2" … through ... n-1.
Click me to see the solution
96. 10 Before 20 Check
Write a Java program to check if there is a 10 in an array of integers with a 20 somewhere later on.
Click me to see the solution
97. Number Adjacent or Separated by One
Write a Java program to check if an array of integers contains a specified number next to each other or two same numbers separated by one element.
Click me to see the solution
98. 20 Appears Thrice Non-Consecutively
Write a Java program to check if the value 20 appears three times and no 20's are next to each other in the array of integers.
Click me to see the solution
99. Specified Number in Adjacent Pairs
Write a Java program that checks if a specified number appears in every pair of adjacent integers of a given array of integers.
Click me to see the solution
100. Count Elements Differ by 1
Write a Java program to count the elements that differ by 1 or less between two given arrays of integers with the same length.
Click me to see the solution
101. Check 10 Exceeds 20 in Array
Write a Java program to determine whether the number 10 in a given array of integers exceeds 20.
Click me to see the solution
102. Contains 10 or 30
Write a Java program to check if a specified array of integers contains 10 or 30.
Click me to see the solution
103. Array After Last 10
Write a Java program to create an array from a given array of integers. The newly created array will contain elements from the given array after the last element value is 10.
Click me to see the solution
104. Array Before Last 10
Write a Java program to create an array from a given array of integers. The newly created array will contain the elements from the given array before the last element value of 10.
Click me to see the solution
105. Group Match Start and End
Write a Java program to check if a group of numbers (l) at the start and end of a given array are the same.
Click me to see the solution
106. Left Shift Array
Write a Java program to create an array left shifted from a given array of integers.
Click me to see the solution
107. Three Increasing Adjacent Numbers
Write a Java program to check if an array of integers contains three increasing adjacent numbers.
Click me to see the solution
108. Sum Digits to Single Digit
Write a Java program to add all the digits of a given positive integer until the result has a single digit.
Click me to see the solution
109. Staircase Coins
Write a Java program to form a staircase shape of n coins where every k-th row must have exactly k coins.
Click me to see the solution
110. Check Power of 4
Write a Java program to check whether the given integer is a power of 4 or not.
Given num = 64, return true. Given num = 6, return false.
Click me to see the solution
111. Add Without Operators
Write a Java program to add two numbers without arithmetic operators.
Given x = 10 and y = 12; result = 22
Click me to see the solution
112. Trailing Zeros in Factorial
Write a Java program to compute the number of trailing zeros in a factorial.
7! = 5040, therefore the output should be 1
Click me to see the solution
113. Merge Two Sorted Arrays
Write a Java program to merge two given sorted arrays of integers and create another sorted array.
array1 = [1,2,3,4]
array2 = [2,5,7, 8]
result = [1,2,2,3,4,5,7,8]
Click me to see the solution
114. Rotate String by Offset
Write a Java program that rotates a string by an offset (rotate from left to right.
Click me to see the solution
115. Check Palindrome Number
Write a Java program to check if a positive number is a palindrome or not.
Input a positive integer: 151
Is 151 is a palindrome number?
true
Click me to see the solution
116. FizzBuzz 1 to 100
Write a Java program that iterates integers from 1 to 100. For multiples of three print "Fizz" instead of the number and print "Buzz" for five. When the number is divided by three and five, print "fizz buzz".
Click me to see the solution
117. Square Root Calculation
Write a Java program to compute the square root of a given number.
Input a positive integer: 25
Square root of 25 is: 5
Click me to see the solution
118. First Occurrence in String
Write a Java program to get the first occurrence (Position starts from 0.) of a string within a given string.
Click me to see the solution
119. First Occurrence in Array
Write a Java program to get the first occurrence (Position starts from 0.) of an element of a given array.
Click me to see the solution
120. Search Value in Matrix
Write a Java program that searches for a value in an m x n matrix.
Click me to see the solution
121. Reverse Linked List
Write a Java program to reverse a linked list.
Example: For linked list 20->40->60->80, the reversed linked list is 80->60->40->20
Click me to see the solution
122. Max Subarray Sum
Write a Java program to find a contiguous subarray with the largest sum from a given array of integers.
Note: In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum. For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.
The subarray should contain one integer at least. Click me to see the solution
123. Min Subarray Sum
Write a Java program to find the subarray with smallest sum from a given array of integers.
Click me to see the solution
124. Insert Index in Sorted Array
Write a Java program to find the index of a value in a sorted array. If the value does not find return the index where it would be if it were inserted in order.
Example:
[1, 2, 4, 5, 6] 5(target) -> 3(index)
[1, 2, 4, 5, 6] 0(target) -> 0(index)
[1, 2, 4, 5, 6] 7(target) -> 5(index)
Click me to see the solution
125. Preorder Binary Tree Traversal
Write a Java program to get the preorder traversal of the values of the nodes in a binary tree.
Example:
10 / \ 20 30 / \ 40 50Expected output: 10 20 40 50 30
Click me to see the solution
126. Inorder Binary Tree Traversal
Write a Java program to get the in-order traversal of its nodes' values in a binary tree.
10 / \ 20 30 / \ 40 50Example:{10, 20, 30, 40, 50}
Output: 40 20 50 10 30
Click me to see the solution
127. Postorder Binary Tree Traversal
Write a Java program to get the Postorder traversal of its nodes' values in a binary tree.
10 / \ 20 30 / \ 40 50Click me to see the solution
128. Median of Array
Write a Java program to calculate the median of a non-sorted array of integers.
Original array: [10, 2, 38, 22, 38, 23]
Median of the said array of integers: 30
Original array: [10, 2, 38, 23, 38, 23, 21]
Median of the said array of integers: 23
Click me to see the solution
129. Single Occurrence Number
Write a Java program to find a number that appears only once in a given array of integers. All numbers occur twice.
Source Array : [10, 20, 10, 20, 30, 40, 40, 30, 50]
50 appears only once
Click me to see the solution
130. Max Depth of Binary Tree
Write a Java program to find the maximum depth of a given binary tree.
Sample Output:
The Maximum depth of the binary tree is: 3
Click me to see the solution
131. Remove Duplicates in Sorted Array
Write a Java program to find the updated length of a sorted array where each element appears only once (remove duplicates).
Original array: [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7]
The length of the original array is: 11
After removing duplicates, the new length of the array is: 7
Click me to see the solution
132. Remove Duplicates (At Most Twice)
Write a Java program to find the updated length of a given sorted array where duplicate elements appear at most twice.
Original array: [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7, 7]
The length of the original array is: 13
After removing duplicates, the new length of the array is: 10
Click me to see the solution
133. Min Path Sum in Grid
Write a Java program to find a path from top left to bottom in the right direction which minimizes the sum of all numbers along its path.
Note: Move either down or right at any point in time.
Sample Output: Sum of all numbers along its path: 13
Click me to see the solution
134. Distinct Ways to Climb Stairs
Write a Java program to find distinct ways to climb to the top (n steps to reach the top) of stairs. Each time you climb, you can climb 1 or 2 steps.
Example: n = 5
a) 1+1+1+1+1 = 5 b) 1+1+1+2 = 5 c) 1+2+2 = 5 d) 2+2+1 = 5 e) 2+1+1+1 = 5 f) 2+1+2 = 5 g) 1+2+1+1 = 5 h) 1+1+2+1 = 5
Sample Output: Distinct ways can you climb to the top: 8
Click me to see the solution
135. Remove Duplicates in Linked List
Write a Java program to remove duplicates from a sorted linked list.
Original List with duplicate elements:
12->12->13->14->15->15->16->17->17
After removing duplicates from the said list:
12->13->14->15->16->17
Click me to see the solution
136. Unique Paths in Grid
Write a Java program to find possible distinct paths from the top-left corner to the bottom-right corner of a given grid (m x n).
Note: You can move either down or right at any point in time.
Sample Output: Unique paths from top-left corner to bottom-right corner of the said grid: 3
Click me to see the solution
137. Unique Paths with Obstacles
Write a Java program to find possible unique paths considering some obstacles, from top-left corner to bottom-right corner of a given grid (m x n).
Note: You can move either down or right at any point in time and an obstacle and empty space is marked as 1 and 0 respectively in the grid.
Sample grid:
int[][] obstacle_Grid ={
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
};
Sample Output: Unique paths from top-left corner to bottom-right corner of the said grid (considering some obstacles): 2
Click me to see the solution
138. Longest Word in Dictionary
Write a Java program to find the longest words in a dictionary.
Example-1:
{
"cat",
"flag",
"green",
"country",
"w3resource"
}
Result: "w3resource"
Example-2:
{
"cat",
"dog",
"red",
"is",
"am"
}
Result: "cat", "dog", "red"
Click me to see the solution
139. Subarray with Zero Sum
Write a Java program to get the index of the first and the last number of a subarray where the sum of numbers is zero. This is from a given array of integers.
Original Array : [1, 2, 3, -6, 5, 4]
Index of the subarray of the said array where the sum of numbers is zero: [0, 3]
Click me to see the solution
140. Merge Overlapping Intervals
Write a Java program to merge all overlapping intervals from a given collection of intervals.
Sample Output: 1 6
8 10
15 20
Click me to see the solution
141. Check Distinct Characters
Write a Java program to check if a given string has all distinct characters.
Sample Output: Original String : xyyz
String has all unique characters: false
Click me to see the solution
142. Check Anagrams
Write a Java program to check if two strings are anagrams or not.
According to Wikipedia "An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram can be rearranged into nag a ram, or the word binary into brainy."
Sample Output: String-1 : wxyz
String-2 : zyxw
Check if two given strings are anagrams or not?: true
Click me to see the solution
143. Merge Two Sorted Linked Lists
Write a Java program to merge the two sorted linked lists.
Sample Output:
Merge Two Sorted ListsT:
1 2 3 7 9 13 40
Click me to see the solution
144. Remove Element in Array
Write a Java program to remove all occurrences of a specified value in a given array of integers. Return the updated array length.
Sample Output:
Original array: [1, 4, 6, 7, 6, 2]
The length of the new array is: 4
Click me to see the solution
145. Remove Nth Element from End
Write a Java program to remove the nth element from the end of a given list.
Sample Output:
Original node:
1 2 3 4 5
After removing 2nd element from end:
1 2 3 5
Click me to see the solution
146. Array to Minimal Height BST
Write a Java program to convert an array of sorted items into a binary search tree. Maintain the minimal height of the tree.
Sample Output:
2
1
4
6
5
3
Click me to see the solution
147. Bits to Flip Between Integers
Write a Java program to find the number of bits required to flip to convert two given integers.
Sample Output:
2
Click me to see the solution
148. First Unique Character Index
Write a Java program to find the index of the first unique character in a given string. Assume that there is at least one unique character in the string.
Sample Output:
Original String: wresource
First unique character of the above: 0
Click me to see the solution
149. Check String Permutation
Write a Java program to check if a given string is a permutation of another given string.
Sample Output:
Original strings: xxyz yxzx
true
Click me to see the solution
150. Check Subtree in Binary Tree
Write a Java program to test if a binary tree is a subtree of another binary tree.
Sample Output:
Original strings: xxyz yxzx
true
Click me to see the solution
Java Code Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/index.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics