Java
Java Coding Questions
- How to reverse a String
Check Null String
Convert String to Char Array by toCharArray method
loop to string array from last index to first index and keep appending to new output String
2. How to swap two numbers without using a third variable?
3.Java Program to check if a vowel is present in the string?
First Approach:
loop through each character in string
compare with all 5 vowels as an "OR" condition.
Second Approach:
Use Regular expression:
return input.toLowerCase().matches(".*[aeiou].*");
4. Check if given number is Prime?
A prime number is a whole number greater than 1 whose only factors are 1 and itself.
First check if number is 0 or 1 then it's not prime.
Also check for number 2. this is prime.
for remaining numbers keep dividing from 2 to n/2 if its reminder equal to 0 then it's not prime.
5. Fibonacci Series
Using Recursion:
check if input number is less then 1. if yes then return number or call function recursively by adding fibonacci(n - 1) + fibonacci(n - 2)
without Recursion
create three variables with 0,1,1 value then loop from 1 to <= count a=b, b=c, c=a+b;
6. Check Palindrome String
Start from index 0 to length/2 and in each iteration compare charAt(i) to charAt(length-i-1)
7. Remove white spaces from String
Convert string to string array and loop and compare each char to whitespace by isWhitespace method
if not, a whitespace then appends to new string builder.
8. How to remove leading and trailing white spaces
Java String class contains two methods to remove leading and trailing whitespaces - trim(), and strip().
The strip() method was added to the String class in Java 11.
The Strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.