Java interview questions have been a critical component of technical hiring for decades. If you’re a developer or engineer on the job market, the ability to demonstrate your Java skills in an interview is critical to landing your next role.
To succeed in a Java interview, you’ll need to hone your coding skills and prepare for the styles of problems you might encounter. In this post, we’ll review the Java questions you need to know to land your dream job.
What a Java Interview Looks Like
Java is high-level, class-based, object-oriented programming language used to complete applications. Despite being over two decades old, Java is still one of the most popular languages in the world. In 2019 and 2020, it was the second most widely known programming language.
During a Java interview, candidates are challenged to solve coding problems and answer general questions about the programming language.
Java interview questions can appear in the hiring process for a variety of roles, including software engineers, back-end developers, full-stack developers, and data scientists.
Basic Java Interview Questions
Below are five examples of basic java problems. These questions are simple in nature, testing only one concept. They are meant to be solved in a collaborative integrated development environment (IDE). You can access the sample inputs, sample outputs, and base code for each question by clicking the solve problem links.
Java Loops I
Given an integer, N, print its first 10 multiples. Each multiple N (where 1<= i <=10) should be printed on a new line in the form: N x i = Result.
Input Format: A single integer, N.
Constraint: 2 <= N <= 20
Output Format
Print 10 lines of output; each line i (where 1<= i <=10) contains the result of N x i in the form: N x i = result.
Java Static Initializer Block
Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks. You can read more about the concept here.
You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input.
If B <= 0 or H <= 0, the output should be “java.lang.Exception: Breadth and height must be positive” without quotes.
Input Format
There are two lines of input. The first line contains : the breadth of the parallelogram. The next line contains : the height of the parallelogram.
Constraints
- -100 <= B <= 100
- -100 <= H <= 100
Output Format
If both values are greater than zero, then the main method must output the area of the parallelogram. Otherwise, print “java.lang.Exception: Breadth and height must be positive” without quotes.
Java String Reverse
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.
Given a string A, print Yes if it is a palindrome, print No otherwise.
Constraint: A will have at most 50 lower case English letters.
Sample Input: racecar
Sample Output: Yes
Valid Username Regular Expression
You are updating the username policy on your company’s internal networking platform. According to the policy, a username is considered valid if all the following constraints are satisfied:
- The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
- The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a – z], uppercase characters [A – Z], and digits [0 – 9].
- The first character of the username must be an alphabetic character, i.e., either a lowercase character [a – z] or uppercase character [A – Z].
For example:
- Julia = INVALID; Username length < 8 characters
- Samantha = VALID
- Samantha_21 = VALID
- 1 = INVALID; Username begins with non-alphabetic character
- ? = INVALID; ‘?’ character not allowed
Update the value of regularExpression field in the UsernameValidator class so that the regular expression only matches with valid usernames.
Input Format
The first line of input contains an integer n, describing the total number of usernames. Each of the next n lines contains a string describing the username. The locked stub code reads the inputs and validates the username.
Constraints
- 1 <= n <= 100
- The username consists of any printable characters.
Output Format
For each of the usernames, the locked stub code prints Valid if the username is valid; otherwise Invalid each on a new line.
Exception Handling
Compute the power of a number by implementing a calculator. Create a class MyCalculator which consists of a single method long power(int, int). This method takes two integers, n and p, as parameters and finds np. If either n or p is negative, then the method must throw an exception which says “n or p should not be negative”. Also, if both n and p are zero, then the method must throw an exception which says “n and p should not be zero”
For example, -4 and -5 would result in java.lang.Exception: n or p should not be negative.
Complete the function power in class MyCalculator and return the appropriate result after the power operation or an appropriate exception as detailed above.
Input Format
Each line of the input contains two integers, n and p. The locked stub code in the editor reads the input and sends the values to the method as parameters.
Constraints
- -10 <= n <= 10
- -10 <= p <= 10
Output Format
Each line of the output contains the result np, if both n and p are positive. If either n or p is negative, the output contains “n and p should be non-negative”. If both n and p are zero, the output contains “n and p should not be zero.” This is printed by the locked stub code in the editor.
Sample Input 0
- 3 5
- 2 4
- 0 0
- -1 -2
- -1 3
Sample Output 0
- 243
- 16
- java.lang.Exception: n and p should not be zero.
- java.lang.Exception: n or p should not be negative.
- java.lang.Exception: n or p should not be negative.
Explanation 0
- In the first two cases, both n and p are positive. So, the power function returns the answer correctly.
- In the third case, both n and p are zero. So, the exception, “n and p should not be zero.”, is printed.
- In the last two cases, at least one out of n and p is negative. So, the exception, “n or p should not be negative.”, is printed for these two cases.
Intermediate-Level Java Interview Questions
Below are five examples of more challenging java interview problems, with difficulties ranging from medium to advanced. These questions cover more specific concepts and language-specific knowledge, and are also meant to be solved in a collaborative IDE. You can access the sample inputs, sample outputs, and base code for each question by clicking the solve problem links.
Java Regex
Write a class called MyRegex which will contain a string pattern. You need to write a regular expression and assign it to the pattern such that it can be used to validate an IP address.
Use the following definition of an IP address:
- IP address is a string in the form “A.B.C.D”, where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can’t be greater than 3.
Some valid IP addresses:
- 000.12.12.034
- 121.234.12.12
- 23.45.12.56
Some invalid IP addresses:
- 000.12.234.23.23
- 666.666.23.23
- .213.123.23.32
- 23.45.22.32.
- I.Am.not.an.ip
In this problem you will be provided strings containing any combination of ASCII characters. You have to write a regular expression to find the valid IPs.
Just write the MyRegex class which contains a String pattern. The string should contain the correct regular expression.
(MyRegex class MUST NOT be public)
Sample Input
000.12.12.034
121.234.12.12
23.45.12.56
00.12.123.123123.123
122.23
Hello.IP
Sample Output
true
true
true
false
false
false
Tag Content Extractor
In a tag-based language like XML or HTML, contents are enclosed between a start tag and an end tag like <tag>contents</tag>. Note that the corresponding end tag starts with a /.
Given a string of text in a tag-based language, parse this text and retrieve the contents enclosed within sequences of well-organized tags meeting the following criterion:
- The name of the start and end tags must be the same. The HTML code <h1>Hello World</h2> is not valid, because the text starts with an h1 tag and ends with a non-matching h2 tag.
- Tags can be nested, but content between nested tags is considered not valid. For example, in <h1><a>contents</a>invalid</h1>, contents is valid but invalid is not valid.
Tags can consist of any printable characters.
Input Format
The first line of input contains a single integer, N (the number of lines).
The N subsequent lines each contain a line of text.
Constraints
1 <= N <= 100
Each line contains a maximum of 104 printable characters.
The total number of characters in all test cases will not exceed 106.
Lambda Expressions
Write the following methods that return a lambda expression performing a specified action:
- PerformOperation isOdd(): The lambda expression must return true if a number is odd or false if it is even.
- PerformOperation isPrime(): The lambda expression must return true if a number is prime or false if it is composite.
- PerformOperation isPalindrome(): The lambda expression must return true if a number is a palindrome or false if it is not.
Input Format
Input is handled for you by the locked stub code in your editor.
Output Format
The locked stub code in your editor will print T lines of output.
Sample Input
The first line contains an integer, T (the number of test cases).
The T subsequent lines each describe a test case in the form of 2 space-separated integers:
The first integer specifies the condition to check for (1 for Odd/Even,2 for Prime, or 3 for Palindrome). The second integer denotes the number to be checked.
- 5
- 1 4
- 2 5
- 3 898
- 1 3
- 2 12
Sample Output
EVEN
PRIME
PALINDROME
ODD
COMPOSITE
Java SHA-256
Cryptographic hash functions are mathematical operations run on digital data. By comparing the computed hash (i.e., the output produced by executing a hashing algorithm) to a known and expected hash value, a person can determine the data’s integrity.
For example, computing the hash of a downloaded file and comparing the result to a previously published hash result can show whether the download has been modified or tampered with. In addition, cryptographic hash functions are extremely collision-resistant; in other words, it should be extremely difficult to produce the same hash output from two different input values using a cryptographic hash function.
Secure Hash Algorithm 2 (SHA-2) is a set of cryptographic hash functions designed by the National Security Agency (NSA). It consists of six identical hashing algorithms (i.e., SHA-256, SHA-512, SHA-224, SHA-384, SHA-512/224, SHA-512/256) with a variable digest size. SHA-256 is a 256-bit ( byte) hashing algorithm which can calculate a hash code for an input of up to 264 – 1 bits. It undergoes 64 rounds of hashing and calculates a hash code that is a 64-digit hexadecimal number.
Given a string, s, print its SHA-256 hash value.
Input Format
A single alphanumeric string denoting s.
Constraints
- 6 <= |s| <= 20
- String s consists of English alphabetic letters [a – zA – Z] and/or decimal digits [0 – 9] only.
Output Format
Print the SHA-256 encryption value of s on a new line.
Sample Input 0
HelloWorld
Sample Output 0
872e4e50ce9990d8b041330c47c9ddd11bec6b503ae9386a99da8584e9bb12c4
Sample Input 1
Javarmi123
Sample Output 1
f1d5f8d75bb55c777207c251d07d9091dc10fe7d6682db869106aacb4b7df678
Can You Access?
You are given a class Solution and an inner class Inner.Private. The main method of class Solution takes an integer num as input. The powerof2 in class Inner.Private checks whether a number is a power of 2. Call the method powerof2 of the class Inner.Private from the main method of the class Solution.
Constraints
1 <= num <= 230
Sample Input
8
Sample Output
8 is power of 2
An instance of class: Solution.Inner.Private has been created