0% found this document useful (0 votes)
4 views3 pages

Java Coding Interview Questions

Uploaded by

styles7001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Java Coding Interview Questions

Uploaded by

styles7001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

1. Reverse a string.

String str = "hello";


String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}
System.out.println(rev);

2. Check if a string is a palindrome.


String str = "madam";
boolean isPalindrome = true;
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
System.out.println(isPalindrome);

3. Print Fibonacci series up to N terms.


int n = 10, a = 0, b = 1;
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
}

4. Check if a number is prime.


int num = 7;
boolean isPrime = num > 1;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime);

5. Find factorial of a number.


int num = 5;
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println(fact);

6. Find the largest element in an array.


int[] arr = {4, 2, 7, 1};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
System.out.println(max);

7. Find the second largest element in an array.


int[] arr = {4, 2, 7, 1};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
System.out.println(second);

8. Count vowels and consonants in a string.


String str = "hello";
int vowels = 0, consonants = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
if ("aeiouAEIOU".indexOf(ch) != -1) vowels++;
else consonants++;
}
}
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);

9. Reverse an integer.
int num = 1234, rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
System.out.println(rev);

10. Check if two strings are anagrams.


String a = "listen", b = "silent";
if (a.length() != b.length()) {
System.out.println("Not Anagram");
} else {
int[] count = new int[256];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i)]++;
count[b.charAt(i)]--;
}
boolean isAnagram = true;
for (int i = 0; i < 256; i++) {
if (count[i] != 0) {
isAnagram = false;
break;
}
}
System.out.println(isAnagram ? "Anagram" : "Not Anagram");
}

You might also like