500-java-programs
500-java-programs
to Advanced
Total Questions: 600 | Solutions: Complete | Difficulty: Beginner → Ad-
vanced
Table of Contents
1. Beginner Level (1-200)
2. Intermediate Level (201-400)
3. Advanced Level (401-600)
1
[Link]("Difference: " + (a - b));
}
}
Q4: Multiply Two Numbers
public class Multiply {
public static void main(String[] args) {
int a = 5, b = 4;
[Link]("Product: " + (a * b));
}
}
Q5: Divide Two Numbers
public class Divide {
public static void main(String[] args) {
int a = 20, b = 4;
[Link]("Division: " + (a / b));
}
}
Q6: Modulus Operation
public class Modulus {
public static void main(String[] args) {
int a = 17, b = 5;
[Link]("Remainder: " + (a % b));
}
}
Q7: Average of Three Numbers
public class Average {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int avg = (a + b + c) / 3;
[Link]("Average: " + avg);
}
}
Q8: Area of Rectangle
public class AreaRectangle {
public static void main(String[] args) {
int length = 10, width = 5;
[Link]("Area: " + (length * width));
}
}
Q9: Area of Circle
2
public class AreaCircle {
public static void main(String[] args) {
double radius = 5;
double area = [Link] * radius * radius;
[Link]("Area: " + area);
}
}
Q10: Perimeter of Circle
public class PerimeterCircle {
public static void main(String[] args) {
double radius = 5;
double perimeter = 2 * [Link] * radius;
[Link]("Perimeter: " + perimeter);
}
}
Q11: Temperature Conversion (Celsius to Fahrenheit)
public class TemperatureConversion {
public static void main(String[] args) {
double celsius = 25;
double fahrenheit = (celsius * 9/5) + 32;
[Link]("Fahrenheit: " + fahrenheit);
}
}
Q12: Simple Interest Calculation
public class SimpleInterest {
public static void main(String[] args) {
double principal = 1000, rate = 5, time = 2;
double si = (principal * rate * time) / 100;
[Link]("Simple Interest: " + si);
}
}
Q13: Compound Interest Calculation
public class CompoundInterest {
public static void main(String[] args) {
double principal = 1000, rate = 5, time = 2;
double ci = principal * [Link](1 + rate/100, time) - principal;
[Link]("Compound Interest: " + ci);
}
}
Q14: ASCII Value of Character
3
public class ASCIIValue {
public static void main(String[] args) {
char ch = 'A';
[Link]("ASCII value: " + (int)ch);
}
}
Q15: Swap Two Numbers Without Temporary Variable
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
[Link]("a: " + a + ", b: " + b);
}
}
Q16: Check Even or Odd
public class EvenOdd {
public static void main(String[] args) {
int num = 7;
if (num % 2 == 0)
[Link]("Even");
else
[Link]("Odd");
}
}
Q17: Find Larger Between Two Numbers
public class Larger {
public static void main(String[] args) {
int a = 10, b = 20;
[Link]("Larger: " + [Link](a, b));
}
}
Q18: Find Largest Among Three Numbers
public class Largest {
public static void main(String[] args) {
int a = 10, b = 20, c = 15;
int max = [Link]([Link](a, b), c);
[Link]("Largest: " + max);
}
}
4
Q19: Check Positive, Negative, or Zero
public class CheckNumber {
public static void main(String[] args) {
int num = -5;
if (num > 0)
[Link]("Positive");
else if (num < 0)
[Link]("Negative");
else
[Link]("Zero");
}
}
Q20: Absolute Value
public class AbsoluteValue {
public static void main(String[] args) {
int num = -15;
[Link]("Absolute: " + [Link](num));
}
}
Q21: Check Vowel or Consonant
public class VowelConsonant {
public static void main(String[] args) {
char ch = 'a';
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
[Link]("Vowel");
else
[Link]("Consonant");
}
}
Q22: Leap Year Check
public class LeapYear {
public static void main(String[] args) {
int year = 2020;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
[Link]("Leap Year");
else
[Link]("Not Leap Year");
}
}
Q23: Grade Based on Marks
public class Grade {
5
public static void main(String[] args) {
int marks = 75;
if (marks >= 90)
[Link]("A");
else if (marks >= 80)
[Link]("B");
else if (marks >= 70)
[Link]("C");
else
[Link]("F");
}
}
Q24: Day of Week Using Switch
public class DayOfWeek {
public static void main(String[] args) {
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
}
}
}
Q25: Ternary Operator Example
public class TernaryOp {
public static void main(String[] args) {
int a = 10, b = 20;
String result = (a > b) ? "a is greater" : "b is greater";
[Link](result);
}
}
Q26: Logical AND Example
public class LogicalAND {
public static void main(String[] args) {
boolean a = true, b = false;
[Link]("AND: " + (a && b));
}
}
6
Q27: Logical OR Example
public class LogicalOR {
public static void main(String[] args) {
boolean a = true, b = false;
[Link]("OR: " + (a || b));
}
}
Q28: Bitwise AND
public class BitwiseAND {
public static void main(String[] args) {
int a = 5, b = 3;
[Link]("AND: " + (a & b));
}
}
Q29: Bitwise OR
public class BitwiseOR {
public static void main(String[] args) {
int a = 5, b = 3;
[Link]("OR: " + (a | b));
}
}
Q30: Bitwise XOR
public class BitwiseXOR {
public static void main(String[] args) {
int a = 5, b = 3;
[Link]("XOR: " + (a ^ b));
}
}
Loops (31-60)
Q31: Print Numbers 1 to 10 Using For Loop
public class ForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
[Link](i + " ");
}
}
}
Q32: Print Numbers 1 to N Using While Loop
7
public class WhileLoop {
public static void main(String[] args) {
int n = 10, i = 1;
while (i <= n) {
[Link](i + " ");
i++;
}
}
}
Q33: Do-While Loop Example
public class DoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
[Link](i + " ");
i++;
} while (i <= 5);
}
}
Q34: Factorial of N
public class Factorial {
public static void main(String[] args) {
int n = 5;
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
[Link]("Factorial: " + fact);
}
}
Q35: Sum of First N Numbers
public class SumNNumbers {
public static void main(String[] args) {
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
[Link]("Sum: " + sum);
}
}
Q36: Sum of Squares
8
public class SumSquares {
public static void main(String[] args) {
int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}
[Link]("Sum of Squares: " + sum);
}
}
Q37: Multiplication Table
public class MultiplicationTable {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= 10; i++) {
[Link](n + " * " + i + " = " + (n * i));
}
}
}
Q38: Print Pattern (1 to N)
public class Pattern1 {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](j + " ");
}
[Link]();
}
}
}
Q39: Star Pattern (Triangle)
public class StarPattern {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
}
}
Q40: Pyramid Pattern
9
public class PyramidPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
[Link](" ");
}
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
}
}
Q41: Check Prime Number
public class PrimeNumber {
public static void main(String[] args) {
int num = 17;
boolean prime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
if (prime)
[Link]("Prime");
else
[Link]("Not Prime");
}
}
Q42: Fibonacci Series
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
[Link](a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
[Link](" " + c);
a = b;
b = c;
}
}
10
}
Q43: Reverse a Number
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
[Link]("Reversed: " + reversed);
}
}
Q44: Palindrome Number
public class PalindromeNumber {
public static void main(String[] args) {
int num = 121;
int original = num;
int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
if (original == reversed)
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}
Q45: Armstrong Number
public class ArmstrongNumber {
public static void main(String[] args) {
int num = 153;
int sum = 0;
int original = num;
while (num != 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if (original == sum)
[Link]("Armstrong");
else
11
[Link]("Not Armstrong");
}
}
Q46: Count Digits in a Number
public class CountDigits {
public static void main(String[] args) {
int num = 12345;
int count = 0;
while (num != 0) {
count++;
num /= 10;
}
[Link]("Digits: " + count);
}
}
Q47: Sum of Digits
public class SumDigits {
public static void main(String[] args) {
int num = 12345;
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
[Link]("Sum: " + sum);
}
}
Q48: Break Statement Example
public class BreakStatement {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5)
break;
[Link](i + " ");
}
}
}
Q49: Continue Statement Example
public class ContinueStatement {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5)
12
continue;
[Link](i + " ");
}
}
}
Q50: GCD of Two Numbers
public class GCD {
public static void main(String[] args) {
int a = 12, b = 8;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
[Link]("GCD: " + a);
}
}
Methods (51-80)
Q51: Simple Method
public class SimpleMethod {
static void greet() {
[Link]("Hello!");
}
13
static int multiply(int a, int b) {
return a * b;
}
14
return a + b;
}
15
[Link]("Power: " + power(2, 5));
}
}
Q60: LCM of Two Numbers
public class LCM {
static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
Arrays (61-100)
Q61: Array Declaration and Initialization
public class ArrayBasics {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) {
[Link](num + " ");
}
}
}
Q62: Array Sum
public class ArraySum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : arr) {
sum += num;
}
[Link]("Sum: " + sum);
16
}
}
Q63: Array Average
public class ArrayAverage {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : arr) {
sum += num;
}
[Link]("Average: " + (sum / [Link]));
}
}
Q64: Find Maximum in Array
public class ArrayMax {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
int max = arr[0];
for (int num : arr) {
if (num > max)
max = num;
}
[Link]("Max: " + max);
}
}
Q65: Find Minimum in Array
public class ArrayMin {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
int min = arr[0];
for (int num : arr) {
if (num < min)
min = num;
}
[Link]("Min: " + min);
}
}
Q66: Reverse an Array
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = [Link] - 1; i >= 0; i--) {
17
[Link](arr[i] + " ");
}
}
}
Q67: Copy Array
public class CopyArray {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
copy[i] = original[i];
}
[Link]("Copied: " + [Link](copy));
}
}
Q68: Linear Search
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {1, 5, 3, 8, 2};
int target = 8;
for (int i = 0; i < [Link]; i++) {
if (arr[i] == target) {
[Link]("Found at index: " + i);
break;
}
}
}
}
Q69: Binary Search
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
int target = 5;
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
[Link]("Found at index: " + mid);
break;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
18
}
}
}
}
Q70: Sort Array (Bubble Sort)
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]([Link](arr));
}
}
Q71: Selection Sort
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
for (int i = 0; i < [Link] - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < [Link]; j++) {
if (arr[j] < arr[minIdx])
minIdx = j;
}
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
[Link]([Link](arr));
}
}
Q72: Insertion Sort
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
for (int i = 1; i < [Link]; i++) {
int key = arr[i];
19
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
[Link]([Link](arr));
}
}
Q73: Remove Duplicates from Array
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 3, 3, 4};
[Link]("Unique: ");
for (int i = 0; i < [Link]; i++) {
if (i == 0 || arr[i] != arr[i - 1])
[Link](arr[i] + " ");
}
}
}
Q74: Merge Two Arrays
public class MergeArrays {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] merged = new int[[Link] + [Link]];
[Link](arr1, 0, merged, 0, [Link]);
[Link](arr2, 0, merged, [Link], [Link]);
[Link]([Link](merged));
}
}
Q75: Rotate Array
public class RotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int d = 2;
d = d % [Link];
int[] rotated = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
rotated[(i + d) % [Link]] = arr[i];
}
[Link]([Link](rotated));
20
}
}
Q76: 2D Array Declaration
public class Array2D {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int[] row : matrix) {
for (int num : row) {
[Link](num + " ");
}
[Link]();
}
}
}
Q77: Matrix Addition
public class MatrixAddition {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
for (int[] row : c) {
[Link]([Link](row));
}
}
}
Q78: Matrix Multiplication
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
}
}
for (int[] row : c) {
[Link]([Link](row));
21
}
}
}
Q79: Transpose Matrix
public class TransposeMatrix {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
int[][] transpose = new int[3][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
transpose[j][i] = matrix[i][j];
}
}
for (int[] row : transpose) {
[Link]([Link](row));
}
}
}
Q80: Find Pair with Sum
public class PairSum {
public static void main(String[] args) {
int[] arr = {1, 5, 7, 2, 8, 4};
int target = 10;
for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (arr[i] + arr[j] == target) {
[Link]("Pair: " + arr[i] + ", " + arr[j]);
}
}
}
}
}
Strings (81-120)
Q81: String Concatenation
public class StringConcat {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
String s3 = s1 + " " + s2;
[Link](s3);
}
22
}
Q82: String Length
public class StringLength {
public static void main(String[] args) {
String str = "Hello";
[Link]("Length: " + [Link]());
}
}
Q83: Character at Index
public class CharAtIndex {
public static void main(String[] args) {
String str = "Hello";
[Link]("Char at 0: " + [Link](0));
}
}
Q84: String Reverse
public class ReverseString {
public static void main(String[] args) {
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
[Link]("Reversed: " + reversed);
}
}
Q85: Palindrome String
public class PalindromeString {
public static void main(String[] args) {
String str = "racecar";
String reversed = new StringBuilder(str).reverse().toString();
if ([Link](reversed))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}
Q86: Check if Two Strings are Equal
public class StringEquality {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
[Link]("Equal: " + [Link](s2));
23
}
}
Q87: Case Conversion
public class CaseConversion {
public static void main(String[] args) {
String str = "Hello";
[Link]("Upper: " + [Link]());
[Link]("Lower: " + [Link]());
}
}
Q88: Substring
public class Substring {
public static void main(String[] args) {
String str = "Hello World";
[Link]([Link](0, 5));
}
}
Q89: Check Character in String
public class CheckChar {
public static void main(String[] args) {
String str = "Hello";
[Link]("Contains 'e': " + [Link]("e"));
}
}
Q90: String Comparison
public class StringComparison {
public static void main(String[] args) {
String s1 = "apple";
String s2 = "banana";
[Link]("CompareTo: " + [Link](s2));
}
}
Q91: Count Occurrence of Character
public class CountCharacter {
public static void main(String[] args) {
String str = "hello";
char ch = 'l';
int count = 0;
for (char c : [Link]()) {
if (c == ch)
count++;
24
}
[Link]("Count: " + count);
}
}
Q92: Remove Spaces
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Hello World";
String result = [Link](" ", "");
[Link](result);
}
}
Q93: Replace Character
public class ReplaceChar {
public static void main(String[] args) {
String str = "hello";
String result = [Link]('l', 'x');
[Link](result);
}
}
Q94: Split String
public class SplitString {
public static void main(String[] args) {
String str = "Hello,World,Java";
String[] parts = [Link](",");
for (String part : parts) {
[Link](part);
}
}
}
Q95: Find Index of Character
public class IndexOf {
public static void main(String[] args) {
String str = "Hello";
[Link]("Index of 'l': " + [Link]('l'));
}
}
Q96: Check Anagram
public class Anagram {
public static void main(String[] args) {
String s1 = "listen";
25
String s2 = "silent";
char[] c1 = [Link]();
char[] c2 = [Link]();
[Link](c1);
[Link](c2);
[Link]("Anagram: " + [Link](c1, c2));
}
}
Q97: Vowel Count
public class VowelCount {
public static void main(String[] args) {
String str = "hello";
int count = 0;
for (char c : [Link]()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
[Link]("Vowels: " + count);
}
}
Q98: Consonant Count
public class ConsonantCount {
public static void main(String[] args) {
String str = "hello";
int count = 0;
for (char c : [Link]()) {
if ([Link](c) &&
c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u')
count++;
}
[Link]("Consonants: " + count);
}
}
Q99: Trim Whitespace
public class TrimString {
public static void main(String[] args) {
String str = " Hello World ";
[Link]("Trimmed: '" + [Link]() + "'");
}
}
Q100: Check if String is Empty
public class CheckEmpty {
26
public static void main(String[] args) {
String str = "";
[Link]("Empty: " + [Link]());
}
}
27
}
Q104: Read Multiple Inputs
import [Link];
28
Q108: Final Variable (Constant)
public class FinalVariable {
public static void main(String[] args) {
final int MAX = 100;
[Link]("Max: " + MAX);
}
}
Q109: Data Types
public class DataTypes {
public static void main(String[] args) {
byte b = 10;
short s = 20;
int i = 30;
long l = 40L;
float f = 50.5f;
double d = 60.5;
char c = 'A';
boolean bool = true;
[Link](b + ", " + s + ", " + i + ", " + l + ", " + f + ", " + d + ", " +
}
}
Q110: Type Casting
public class TypeCasting {
public static void main(String[] args) {
int i = 10;
double d = i;
[Link]("Implicit: " + d);
double d2 = 3.14;
int i2 = (int) d2;
[Link]("Explicit: " + i2);
}
}
Q111: Static Variable
public class StaticVariable {
static int count = 0;
void increment() {
count++;
}
29
StaticVariable obj1 = new StaticVariable();
StaticVariable obj2 = new StaticVariable();
[Link]();
[Link]();
[Link]("Count: " + count);
}
}
Q112: Local Variable
public class LocalVariable {
public static void main(String[] args) {
int a = 10;
{
int b = 20;
[Link](b);
}
// [Link](b); // Error: b is out of scope
}
}
Q113: Variable Naming
public class VariableNaming {
public static void main(String[] args) {
int myVar = 10;
String MY_CONSTANT = "Value";
double _value = 3.14;
int $money = 100;
[Link](myVar + ", " + MY_CONSTANT + ", " + _value + ", " + $money);
}
}
Q114: Print without Newline
public class PrintNoNewline {
public static void main(String[] args) {
[Link]("Hello ");
[Link]("World");
}
}
Q115: Escape Sequences
public class EscapeSequences {
public static void main(String[] args) {
[Link]("Hello\nWorld");
[Link]("Tab:\tSeparated");
[Link]("Backslash: \\");
[Link]("Quote: \"Hello\"");
30
}
}
Q116: Read Line Using Scanner
import [Link];
31
[Link]("Subtraction selected");
break;
case 3:
[Link]("Exit");
break;
}
[Link]();
}
}
Q119: Repeat User Input Until Condition Met
import [Link];
32
More Beginner Programs (121-200)
Q121: Print ASCII Table
public class ASCIITable {
public static void main(String[] args) {
[Link]("ASCII\tCharacter");
for (int i = 65; i <= 90; i++) {
[Link](i + "\t" + (char)i);
}
}
}
Q122: Number Guessing Game
import [Link];
33
}
}
Q124: Simple Calculator
import [Link];
switch (op) {
case '+': [Link]("Result: " + (a + b)); break;
case '-': [Link]("Result: " + (a - b)); break;
case '*': [Link]("Result: " + (a * b)); break;
case '/': [Link]("Result: " + (a / b)); break;
}
[Link]();
}
}
Q125: Check Triangle Validity
public class TriangleValidity {
public static void main(String[] args) {
int a = 3, b = 4, c = 5;
if (a + b > c && b + c > a && a + c > b)
[Link]("Valid Triangle");
else
[Link]("Invalid Triangle");
}
}
Q126: Calculate Triangle Area (Heron’s Formula)
public class TriangleArea {
public static void main(String[] args) {
double a = 3, b = 4, c = 5;
double s = (a + b + c) / 2;
double area = [Link](s * (s - a) * (s - b) * (s - c));
[Link]("Area: " + area);
}
}
34
Q127: Check Right Triangle
public class RightTriangle {
public static void main(String[] args) {
int a = 3, b = 4, c = 5;
if (a*a + b*b == c*c)
[Link]("Right Triangle");
else
[Link]("Not Right Triangle");
}
}
Q128: Grade Percentage Calculation
import [Link];
35
[Link]("Odd: " + odd + ", Even: " + even);
}
}
Q131: Find Second Largest
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 3};
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
for (int num : arr) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2)
max2 = num;
}
[Link]("Second Largest: " + max2);
}
}
Q132: Find Second Smallest
public class SecondSmallest {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9, 3};
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
for (int num : arr) {
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2)
min2 = num;
}
[Link]("Second Smallest: " + min2);
}
}
Q133: Count Positive and Negative
public class PositiveNegative {
public static void main(String[] args) {
int[] arr = {-1, 2, -3, 4, -5, 6};
int positive = 0, negative = 0;
for (int num : arr) {
if (num > 0)
positive++;
else if (num < 0)
negative++;
36
}
[Link]("Positive: " + positive + ", Negative: " + negative);
}
}
Q134: Sum of Even Numbers
public class SumEven {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
int sum = 0;
for (int num : arr) {
if (num % 2 == 0)
sum += num;
}
[Link]("Sum: " + sum);
}
}
Q135: Sum of Odd Numbers
public class SumOdd {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
int sum = 0;
for (int num : arr) {
if (num % 2 != 0)
sum += num;
}
[Link]("Sum: " + sum);
}
}
Q136: Print Even Numbers in Range
public class EvenInRange {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0)
[Link](i + " ");
}
}
}
Q137: Print Odd Numbers in Range
public class OddInRange {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0)
37
[Link](i + " ");
}
}
}
Q138: Print Prime Numbers in Range
public class PrimesInRange {
public static void main(String[] args) {
for (int i = 2; i <= 20; i++) {
boolean prime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime)
[Link](i + " ");
}
}
}
Q139: Sum of Perfect Squares
public class SumPerfectSquares {
public static void main(String[] args) {
int[] arr = {1, 4, 9, 16, 25};
int sum = 0;
for (int num : arr) {
int sqrt = (int) [Link](num);
if (sqrt * sqrt == num)
sum += num;
}
[Link]("Sum: " + sum);
}
}
Q140: Check Perfect Square
public class PerfectSquare {
public static void main(String[] args) {
int num = 16;
int sqrt = (int) [Link](num);
if (sqrt * sqrt == num)
[Link]("Perfect Square");
else
[Link]("Not Perfect Square");
38
}
}
Q141: Find Median
public class Median {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
[Link](arr);
double median = [Link] % 2 == 0 ?
(arr[[Link]/2 - 1] + arr[[Link]/2]) / 2.0 :
arr[[Link]/2];
[Link]("Median: " + median);
}
}
Q142: Find Mode (Most Frequent)
public class Mode {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 3, 3, 4};
int mode = arr[0], maxCount = 0;
for (int i = 0; i < [Link]; i++) {
int count = 0;
for (int j = 0; j < [Link]; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > maxCount) {
maxCount = count;
mode = arr[i];
}
}
[Link]("Mode: " + mode);
}
}
Q143: Standard Deviation
public class StandardDeviation {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
double mean = 0;
for (int num : arr)
mean += num;
mean /= [Link];
double variance = 0;
for (int num : arr)
39
variance += [Link](num - mean, 2);
variance /= [Link];
double sd = [Link](variance);
[Link]("Std Dev: " + sd);
}
}
Q144: Variance Calculation
public class Variance {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
double mean = 0;
for (int num : arr)
mean += num;
mean /= [Link];
double variance = 0;
for (int num : arr)
variance += [Link](num - mean, 2);
variance /= [Link];
40
[Link]("Q1");
else if (x < 0 && y > 0)
[Link]("Q2");
else if (x < 0 && y < 0)
[Link]("Q3");
else if (x > 0 && y < 0)
[Link]("Q4");
}
}
Q147: Distance Between Two Points
public class Distance {
public static void main(String[] args) {
double x1 = 0, y1 = 0, x2 = 3, y2 = 4;
double dist = [Link]([Link](x2 - x1, 2) + [Link](y2 - y1, 2));
[Link]("Distance: " + dist);
}
}
Q148: Slope of Line
public class Slope {
public static void main(String[] args) {
double x1 = 0, y1 = 0, x2 = 1, y2 = 2;
double slope = (y2 - y1) / (x2 - x1);
[Link]("Slope: " + slope);
}
}
Q149: Circumference of Circle
public class Circumference {
public static void main(String[] args) {
double radius = 5;
double circumference = 2 * [Link] * radius;
[Link]("Circumference: " + circumference);
}
}
Q150: Volume of Sphere
public class VolumeSphere {
public static void main(String[] args) {
double radius = 5;
double volume = (4/3.0) * [Link] * [Link](radius, 3);
[Link]("Volume: " + volume);
}
}
41
INTERMEDIATE LEVEL (201-400)
Object-Oriented Programming (201-250)
Q201: Simple Class and Object
class Student {
String name;
int roll;
double gpa;
void display() {
[Link]("Name: " + name + ", Roll: " + roll + ", GPA: " + gpa);
}
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
42
}
}
Q203: Default Constructor
class Car {
String model;
int year;
Car() {
model = "Unknown";
year = 0;
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}
Book() {
title = "Unknown";
author = "Unknown";
}
Book(String title) {
[Link] = title;
author = "Unknown";
}
void display() {
43
[Link]("Title: " + title + ", Author: " + author);
}
}
44
[Link] = salary;
}
45
[Link]("Bike moving on road");
}
}
void color() {
[Link]("Coloring shape");
}
}
46
public class Q210 {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
[Link]();
}
}
Q211: Interface
interface Animal {
void sound();
}
interface Swimmable {
void swim();
}
47
public class Q212 {
public static void main(String[] args) {
Duck d = new Duck();
[Link]();
[Link]();
}
}
Q213: This Keyword
class Rectangle {
int length;
int width;
void display() {
[Link]("Length: " + [Link] + ", Width: " + [Link]);
}
}
48
}
Q215: Polymorphism
class Animal {
void sound() {
[Link]("Generic sound");
}
}
49
[Link]();
Child c = (Child) p;
[Link]();
}
}
Q217: Instanceof Operator
class Animal {}
class Dog extends Animal {}
50
[Link]();
}
}
Q220: Protected Access Modifier
class Parent {
protected void display() {
[Link]("Protected method");
}
}
51
}
}
Q223: StringBuilder Methods
public class Q223 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](0, "!");
[Link](0, 1);
[Link]();
[Link]([Link]());
}
}
Q224: Wrapper Classes
public class Q224 {
public static void main(String[] args) {
Integer i = [Link](10);
Double d = [Link](3.14);
Boolean b = [Link](true);
52
Q227: Number to String Conversion
public class Q227 {
public static void main(String[] args) {
int i = 123;
String s = [Link](i);
String s2 = [Link](i);
[Link]("String: " + s + ", " + s2);
}
}
Q228: Math Class
public class Q228 {
public static void main(String[] args) {
[Link]("Max: " + [Link](5, 10));
[Link]("Min: " + [Link](5, 10));
[Link]("Abs: " + [Link](-5));
[Link]("Sqrt: " + [Link](25));
[Link]("Power: " + [Link](2, 3));
[Link]("Round: " + [Link](3.7));
}
}
Q229: Random Number Generation
import [Link];
53
Collections (231-280)
Q231: ArrayList Basics
import [Link];
54
for (String key : [Link]()) {
[Link](key + " = " + [Link](key));
}
}
}
Q234: HashMap Operations
import [Link];
55
[Link](10);
[Link](20);
[Link](40);
[Link]("Start");
[Link]("End");
56
import [Link];
[Link](list);
[Link]("Sorted: " + list);
[Link](list);
[Link]("Reversed: " + list);
}
}
Q241: Find in List
import [Link];
import [Link];
57
[Link]("Index of 20: " + [Link](20));
[Link]("Last index of 20: " + [Link](20));
}
}
Q242: Iterate HashMap
import [Link];
import [Link];
58
public static void main(String[] args) {
Set<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple");
59
public class Q247 {
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);
60
Q250: Frequency Count
import [Link];
61
Q253: Finally Block
public class Q253 {
public static void main(String[] args) {
try {
[Link]("Try block");
} catch (Exception e) {
[Link]("Catch block");
} finally {
[Link]("Finally block always executes");
}
}
}
Q254: Throw Exception
public class Q254 {
static void checkAge(int age) {
if (age < 18)
throw new ArithmeticException("Age must be >= 18");
else
[Link]("Valid age");
}
62
}
}
Q256: Try-With-Resources
import [Link];
63
[Link]("Class cast error");
}
}
}
Q260: Throws Keyword
public class Q260 {
static void riskyMethod() throws Exception {
throw new Exception("Something went wrong");
}
64
[Link]("Hello World\n");
[Link]("Java File I/O");
[Link]("File written successfully");
} catch (Exception e) {
[Link]([Link]());
}
}
}
Q263: Check File Exists
import [Link];
65
}
}
Q266: Append to File
import [Link];
66
}
}
Q269: Serialize Object
import [Link].*;
67
} catch (Exception e) {
[Link]([Link]());
}
}
}
68
[Link](squared);
}
}
Q284: Stream Reduce
import [Link];
import [Link];
69
public static void main(String[] args) {
Add a = (x, y) -> x + y;
[Link]("Sum: " + [Link](5, 3));
}
}
Q288: Method Reference
import [Link];
import [Link];
70
ADVANCED LEVEL (401-600)
Multithreading (401-450)
Q401: Creating Thread with Thread Class
class PrintThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Thread: " + i);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
71
public class Q403 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
}
}
Q404: Thread Synchronization
class Counter {
private int count = 0;
int getCount() {
return count;
}
}
72
synchronized void setValue(int v) throws InterruptedException {
value = v;
notifyAll();
}
73
Q407: Deadlock Example
class Account {
private int balance = 1000;
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Q408: Thread States
public class Q408 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
[Link]("Thread running");
try {
[Link](2000);
} catch (InterruptedException e) {}
});
74
[Link]();
[Link]("State after join: " + [Link]());
}
}
Q409: Volatile Keyword
class VolatileExample {
private volatile int flag = 0;
void setFlag() {
flag = 1;
}
int getFlag() {
return flag;
}
}
[Link]();
[Link]("All tasks completed");
}
}
75
Design Patterns (411-450)
Q411: Singleton Pattern
class Singleton {
private static Singleton instance;
private Singleton() {}
class AnimalFactory {
public static Animal createAnimal(String type) {
if ([Link]("Dog"))
return new Dog();
else if ([Link]("Cat"))
76
return new Cat();
return null;
}
}
class Subject {
[Link]<Observer> observers = new [Link]<>();
77
interface Component {
void operation();
}
Decorator(Component c) {
component = c;
}
78
class StrategyA implements Strategy {
public void execute() {
[Link]("Strategy A");
}
}
class Context {
Strategy strategy;
void setStrategy(Strategy s) {
strategy = s;
}
void executeStrategy() {
[Link]();
}
}
79
int roll;
double gpa;
class OldClass {
void oldMethod() {
[Link]("Old method");
}
}
80
public void newMethod() {
oldMethod();
}
}
class SubSystem2 {
void operation2() {
[Link]("Operation 2");
}
}
class Facade {
SubSystem1 s1 = new SubSystem1();
SubSystem2 s2 = new SubSystem2();
void complexOperation() {
s1.operation1();
s2.operation2();
}
}
81
class Real implements RealSubject {
public void request() {
[Link]("Real request");
}
}
void step2() {
[Link]("Step 2");
82
}
}
Node(int data) {
[Link] = data;
}
}
class BST {
Node root;
return root;
}
83
[Link]([Link] + " ");
inorder([Link]);
}
}
}
AVLNode(int data) {
[Link] = data;
height = 1;
}
}
class AVLTree {
AVLNode root;
AVLNode rotateRight(AVLNode y) {
AVLNode x = [Link];
AVLNode T2 = [Link];
[Link] = y;
[Link] = T2;
84
[Link] = [Link](getHeight([Link]), getHeight([Link])) + 1;
[Link] = [Link](getHeight([Link]), getHeight([Link])) + 1;
return x;
}
AVLNode rotateLeft(AVLNode x) {
AVLNode y = [Link];
AVLNode T2 = [Link];
[Link] = x;
[Link] = T2;
[Link] = [Link](getHeight([Link]), getHeight([Link])) + 1;
[Link] = [Link](getHeight([Link]), getHeight([Link])) + 1;
return y;
}
85
return rotateLeft(root);
}
return root;
}
}
class Graph {
Map<Integer, List<Integer>> graph = new HashMap<>();
void display() {
for (int vertex : [Link]()) {
[Link](vertex + " -> " + [Link](vertex));
}
}
}
86
Q424: BFS (Breadth-First Search)
import [Link].*;
class BFS {
void bfs(Map<Integer, List<Integer>> graph, int start) {
boolean[] visited = new boolean[[Link]()];
Queue<Integer> queue = new LinkedList<>();
[Link](start);
visited[start] = true;
while (![Link]()) {
int vertex = [Link]();
[Link](vertex + " ");
class DFS {
void dfs(Map<Integer, List<Integer>> graph, int vertex, boolean[] visited) {
visited[vertex] = true;
[Link](vertex + " ");
87
for (int neighbor : [Link](vertex, new ArrayList<>())) {
if (!visited[neighbor]) {
dfs(graph, neighbor, visited);
}
}
}
}
class Dijkstra {
void dijkstra(int[][] graph, int start) {
int n = [Link];
int[] dist = new int[n];
boolean[] visited = new boolean[n];
[Link](dist, Integer.MAX_VALUE);
dist[start] = 0;
visited[u] = true;
88
if (graph[u][v] != 0 && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
89
arr[left + x] = temp[x];
}
return i + 1;
}
90
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
}
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
91
arr[i] = temp;
heapify(arr, i, 0);
}
}
}
92
Q431-500: Continue with more advanced algorithms… (Remaining 69
questions covering Trie, Segment Tree, Fenwick Tree, Backtracking, Dynamic
Programming, etc.)
class Account {
String accountNumber;
String accountHolder;
double balance;
void displayBalance() {
[Link]("Balance: " + balance);
}
}
93
void createAccount() {
[Link]("Account Number: ");
String num = [Link]();
[Link]("Holder Name: ");
String name = [Link]();
[Link]("Initial Balance: ");
double balance = [Link]();
[Link]();
void displayMenu() {
[Link]("\n1. Create Account");
[Link]("2. Deposit");
[Link]("3. Withdraw");
[Link]("4. Check Balance");
[Link]("5. Exit");
[Link]("Choose: ");
}
while (true) {
[Link]();
int choice = [Link]();
[Link]();
switch (choice) {
case 1:
[Link]();
break;
case 2:
[Link]("Account Number: ");
String num = [Link]();
if ([Link](num)) {
[Link]("Amount: ");
double amt = [Link]();
[Link](num).deposit(amt);
[Link]("Deposited!");
}
break;
case 3:
[Link]("Account Number: ");
94
String num2 = [Link]();
if ([Link](num2)) {
[Link]("Amount: ");
double amt = [Link]();
if ([Link](num2).withdraw(amt))
[Link]("Withdrawn!");
else
[Link]("Insufficient balance!");
}
break;
case 4:
[Link]("Account Number: ");
String num3 = [Link]();
if ([Link](num3))
[Link](num3).displayBalance();
break;
case 5:
[Link]("Exit");
return;
}
}
}
}
STUDY TIPS
1. Start with Beginner Level: Master basics before moving to advanced
topics
2. Practice Daily: 10-15 questions per day
3. Write Code Manually: Don’t just read solutions
4. Test Edge Cases: Always test with boundary values
5. Optimize Solutions: Try to improve time/space complexity
6. Build Projects: Apply concepts to real-world projects
7. Review Regularly: Go back and review previous concepts
8. Time Yourself: Practice under timed conditions
9. Debug Errors: Learn from mistakes
10. Discuss Solutions: Talk through problems with others
REFERENCES
• Oracle Java Documentation: [Link]
• GeeksforGeeks Java: [Link]
• Java Code Geeks: [Link]
95
• W3Resource Java Exercises: [Link]
exercises/
• Java Interview Questions: Multiple sources
96