12 classic String-based Java interview questions with simple explanations and code.

 

1️⃣ Check if a String is a Palindrome

Problem
Given a string, check if it reads the same forward and backward. Example: "madam" → palindrome, "hello" → not palindrome.

Idea
Use two pointers: one at the beginning, one at the end, and compare characters.

public class PalindromeString { public static void main(String[] args) { String str = "Madam"; if (isPalindrome(str)) { System.out.println(str + " is a palindrome"); } else { System.out.println(str + " is not a palindrome"); } } public static boolean isPalindrome(String s) { if (s == null) return false; s = s.toLowerCase(); int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; } }

2️⃣ Reverse a String (Without Using Library Reverse)

Problem
Reverse a given string: input "hello" → output "olleh".

Idea
Convert to char array and swap from both ends.

public class ReverseString { public static void main(String[] args) { String str = "hello"; System.out.println("Original: " + str); System.out.println("Reversed: " + reverse(str)); } public static String reverse(String s) { if (s == null) return null; char[] chars = s.toCharArray(); int left = 0, right = chars.length - 1; while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } return new String(chars); } }

3️⃣ Reverse Words in a Sentence

Problem
Given "Java is awesome", output "awesome is Java" (reverse word order, not characters inside each word).

Idea
Split on spaces, reverse the array of words, then join back.

public class ReverseWordsInSentence { public static void main(String[] args) { String sentence = "Java is awesome"; System.out.println(reverseWords(sentence)); } public static String reverseWords(String s) { if (s == null || s.trim().isEmpty()) return s; String[] words = s.trim().split("\\s+"); int left = 0, right = words.length - 1; while (left < right) { String tmp = words[left]; words[left] = words[right]; words[right] = tmp; left++; right--; } return String.join(" ", words); } }

4️⃣ Check if Two Strings are Anagrams

Problem
Two strings are anagrams if they contain the same characters with the same frequency (order doesn’t matter).
Example: "listen" and "silent" → anagrams.

Idea
Either sort both strings and compare, or count character frequencies. Here we sort.

import java.util.Arrays; public class AnagramCheck { public static void main(String[] args) { String s1 = "listen"; String s2 = "silent"; if (areAnagrams(s1, s2)) { System.out.println(s1 + " and " + s2 + " are anagrams"); } else { System.out.println(s1 + " and " + s2 + " are not anagrams"); } } public static boolean areAnagrams(String a, String b) { if (a == null || b == null) return false; a = a.replaceAll("\\s+", "").toLowerCase(); b = b.replaceAll("\\s+", "").toLowerCase(); if (a.length() != b.length()) return false; char[] ca = a.toCharArray(); char[] cb = b.toCharArray(); Arrays.sort(ca); Arrays.sort(cb); return Arrays.equals(ca, cb); } }

5️⃣ Find the First Non-Repeating Character

Problem
Given a string, find the first character that does not repeat. Example: "swiss" → first non-repeating is 'w'.

Idea
First pass: count frequencies. Second pass: return first char with count 1.

import java.util.LinkedHashMap; import java.util.Map; public class FirstNonRepeatingChar { public static void main(String[] args) { String str = "swiss"; Character result = firstNonRepeating(str); System.out.println("First non-repeating character: " + result); } public static Character firstNonRepeating(String s) { if (s == null) return null; Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } for (Map.Entry<Character, Integer> e : freq.entrySet()) { if (e.getValue() == 1) { return e.getKey(); } } return null; // no unique char } }

6️⃣ Count Vowels and Consonants

Problem
Given a string, count how many vowels and consonants are present (alphabet letters only).

Idea
Loop through characters, check if alphabet, then check if it’s in 'aeiou'.

public class VowelConsonantCount { public static void main(String[] args) { String str = "Hello Java 123"; int vowels = 0; int consonants = 0; String lower = str.toLowerCase(); for (int i = 0; i < lower.length(); i++) { char ch = lower.charAt(i); if (ch >= 'a' && ch <= 'z') { if ("aeiou".indexOf(ch) != -1) { vowels++; } else { consonants++; } } } System.out.println("Vowels: " + vowels); System.out.println("Consonants: " + consonants); } }

7️⃣ Remove All Duplicates Characters (Keep First Occurrence)

Problem
Input: "programming" → Output: "progamin" (remove repeated chars, keep the first time they appear).

Idea
Use a boolean array or Set to track already seen characters.

import java.util.HashSet; import java.util.Set; public class RemoveDuplicateChars { public static void main(String[] args) { String str = "programming"; System.out.println(removeDuplicates(str)); } public static String removeDuplicates(String s) { if (s == null) return null; Set<Character> seen = new HashSet<>(); StringBuilder result = new StringBuilder(); for (char c : s.toCharArray()) { if (!seen.contains(c)) { seen.add(c); result.append(c); } } return result.toString(); } }

8️⃣ Check if One String is a Rotation of Another

Problem
Check if s2 is a rotation of s1.
Example: s1 = "waterbottle", s2 = "erbottlewat" → rotation.

Idea
If lengths are same, check if s2 is a substring of s1 + s1.

public class StringRotationCheck { public static void main(String[] args) { String s1 = "waterbottle"; String s2 = "erbottlewat"; if (isRotation(s1, s2)) { System.out.println(s2 + " is a rotation of " + s1); } else { System.out.println(s2 + " is NOT a rotation of " + s1); } } public static boolean isRotation(String s1, String s2) { if (s1 == null || s2 == null) return false; if (s1.length() != s2.length()) return false; if (s1.isEmpty()) return true; // both empty String doubled = s1 + s1; return doubled.contains(s2); } }

9️⃣ Longest Substring Without Repeating Characters

Problem
Given a string, find the length of the longest substring without repeating characters.
Example: "abcabcbb" → longest is "abc" → length 3.

Idea
Use sliding window with a map that stores last index of each character.

import java.util.HashMap; import java.util.Map; public class LongestUniqueSubstring { public static void main(String[] args) { String s = "abcabcbb"; System.out.println("Length: " + lengthOfLongestSubstring(s)); } public static int lengthOfLongestSubstring(String s) { if (s == null) return 0; Map<Character, Integer> lastIndex = new HashMap<>(); int start = 0; int maxLen = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (lastIndex.containsKey(c) && lastIndex.get(c) >= start) { // move start to one position after the last occurrence start = lastIndex.get(c) + 1; } lastIndex.put(c, i); maxLen = Math.max(maxLen, i - start + 1); } return maxLen; } }

πŸ”Ÿ Character Frequency Count

Problem
Print how many times each character appears in a string.
Example: "banana"b:1, a:3, n:2.

Idea
Use a Map<Character, Integer> and count all characters.

import java.util.LinkedHashMap; import java.util.Map; public class CharacterFrequency { public static void main(String[] args) { String str = "banana"; printCharFrequency(str); } public static void printCharFrequency(String s) { if (s == null) return; Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } for (Map.Entry<Character, Integer> e : freq.entrySet()) { System.out.println(e.getKey() + " -> " + e.getValue()); } } }

1️⃣1️⃣ Count Occurrences of a Substring

Problem
Given a string text and a string pattern, count how many times pattern appears in text (non-overlapping).

Example: text = "aaaa", pattern = "aa" → result = 2.

Idea
Scan using indexOf in a loop and move index by pattern length.

public class SubstringOccurrences { public static void main(String[] args) { String text = "aaaa"; String pattern = "aa"; System.out.println("Count: " + countOccurrences(text, pattern)); } public static int countOccurrences(String text, String pattern) { if (text == null || pattern == null || pattern.isEmpty()) return 0; int count = 0; int index = 0; while ((index = text.indexOf(pattern, index)) != -1) { count++; index += pattern.length(); // move past this occurrence } return count; } }

1️⃣2️⃣ Simple String Compression (Run-Length Encoding Style)

Problem
Compress a string by replacing consecutive repeating characters with the character followed by the count.
Example: "aaabbc""a3b2c1".
If compressed string is not smaller, return original.

Idea
Loop through string and count runs.

public class StringCompression { public static void main(String[] args) { String s = "aaabbc"; System.out.println("Original: " + s); System.out.println("Compressed: " + compress(s)); } public static String compress(String s) { if (s == null || s.isEmpty()) return s; StringBuilder sb = new StringBuilder(); int count = 1; for (int i = 1; i <= s.length(); i++) { if (i < s.length() && s.charAt(i) == s.charAt(i - 1)) { count++; } else { sb.append(s.charAt(i - 1)).append(count); count = 1; } } String compressed = sb.toString(); return compressed.length() < s.length() ? compressed : s; } }


Java Collections – Top 50 Interview Questions & Answers

 

Java Collections – Top 50 Interview Questions & Answers


1️⃣ What is the Java Collection Framework?

A unified architecture to store, retrieve, and manipulate groups of objects using interfaces like List, Set, and Map.


2️⃣ Why do we need collections?

To handle dynamic data, reduce coding effort, improve performance, and provide reusable data structures.


3️⃣ What are the main interfaces in the Collection Framework?

  • List

  • Set

  • Queue

  • Deque

  • Map (part of framework but not a child of Collection)


4️⃣ Difference between Collection and Collections?

CollectionCollections
InterfaceUtility class
Represents dataHelper methods

5️⃣ Difference between List, Set, and Map?

TypeνŠΉμ§•
ListAllows duplicates, ordered
SetNo duplicates
MapKey–value pairs

6️⃣ What is an ArrayList?

A resizable array implementation of List.


7️⃣ Difference between ArrayList and LinkedList?

ArrayListLinkedList
Fast readFast insert/delete
Uses arrayUses doubly linked list

8️⃣ What is Vector?

A legacy synchronized list (rarely used now).


9️⃣ Difference between ArrayList and Vector?

ArrayListVector
Not synchronizedSynchronized
FasterSlower

πŸ”Ÿ What is a Set?

A collection that does not allow duplicates.


1️⃣1️⃣ Difference between HashSet and TreeSet?

HashSetTreeSet
UnorderedSorted
FasterSlower

1️⃣2️⃣ What is LinkedHashSet?

Maintains insertion order while preventing duplicates.


1️⃣3️⃣ How does HashSet work internally?

Uses a HashMap internally to store elements as keys.


1️⃣4️⃣ What is a Map?

Stores data in key–value pairs.


1️⃣5️⃣ Difference between HashMap and Hashtable?

HashMapHashtable
Not synchronizedSynchronized
Allows nullNo null

1️⃣6️⃣ Difference between HashMap and LinkedHashMap?

HashMapLinkedHashMap
No orderMaintains insertion order

1️⃣7️⃣ Difference between HashMap and TreeMap?

HashMapTreeMap
UnorderedSorted
FasterSlower

1️⃣8️⃣ How does HashMap work internally?

Uses hashing, buckets, and linked lists / red-black trees (Java 8+).


1️⃣9️⃣ What is load factor?

Determines when a HashMap resizes (default = 0.75).


2️⃣0️⃣ What happens when HashMap is full?

It resizes and rehashes entries.


2️⃣1️⃣ What is collision in HashMap?

When multiple keys produce the same hash index.


2️⃣2️⃣ How are collisions handled?

Using:

  • Linked list (Java 7)

  • Linked list → Red-Black Tree (Java 8+)


2️⃣3️⃣ What is ConcurrentHashMap?

A thread-safe, high-performance Map.


2️⃣4️⃣ Difference between HashMap and ConcurrentHashMap?

HashMapConcurrentHashMap
Not thread-safeThread-safe
Allows nullNo null

2️⃣5️⃣ Why ConcurrentHashMap is faster than Hashtable?

Uses bucket-level locking instead of full synchronization.


2️⃣6️⃣ What is Queue?

A collection for holding elements before processing (FIFO).


2️⃣7️⃣ What is PriorityQueue?

Queue where elements are ordered by priority.


2️⃣8️⃣ Difference between Queue and Deque?

QueueDeque
One-end operationsBoth ends

2️⃣9️⃣ What is ArrayDeque?

A resizable array implementation of Deque.


3️⃣0️⃣ What is an Iterator?

Used to traverse a collection safely.


3️⃣1️⃣ Difference between Iterator and ListIterator?

IteratorListIterator
Forward onlyBidirectional
All collectionsList only

3️⃣2️⃣ What is fail-fast iterator?

Throws ConcurrentModificationException if collection is modified.


3️⃣3️⃣ What is fail-safe iterator?

Works on a copy of the collection (no exception).


3️⃣4️⃣ Example of fail-safe collection?

CopyOnWriteArrayList


3️⃣5️⃣ What is Collections.sort()?

Utility method to sort a list.


3️⃣6️⃣ Difference between Comparable and Comparator?

ComparableComparator
Natural orderCustom order
compareTo()compare()

3️⃣7️⃣ Can we sort a Map?

Directly ❌
Convert to:

  • List<Map.Entry>

  • or use TreeMap


3️⃣8️⃣ What is immutability in collections?

Unmodifiable collections cannot be changed.


3️⃣9️⃣ How to create immutable collections?

List.of("A", "B");

4️⃣0️⃣ What is EnumMap?

A Map optimized for enum keys.


4️⃣1️⃣ What is WeakHashMap?

Keys are weakly referenced → garbage collected when unused.


4️⃣2️⃣ What is IdentityHashMap?

Uses == instead of equals() for key comparison.


4️⃣3️⃣ What is SynchronizedMap?

Thread-safe wrapper using Collections.synchronizedMap().


4️⃣4️⃣ Difference between synchronizedMap and ConcurrentHashMap?

synchronizedMapConcurrentHashMap
Single lockSegment/bucket locking
SlowerFaster

4️⃣5️⃣ What is CopyOnWriteArrayList?

Thread-safe list optimized for read-heavy scenarios.


4️⃣6️⃣ What is NavigableMap?

Provides navigation methods like lowerKey(), higherKey().


4️⃣7️⃣ What is Spliterator?

Supports parallel traversal of collections.


4️⃣8️⃣ What is Stream API’s relation to collections?

Streams process collections in a functional style.


4️⃣9️⃣ Why Map is not part of Collection interface?

Because Map works with key–value pairs, not single elements.


5️⃣0️⃣ When to use which collection?

ScenarioUse
Fast lookupHashMap
Ordered dataLinkedHashMap
Sorted dataTreeMap
Thread safetyConcurrentHashMap

🎯 Interview Final Tip

Most collection questions test internal working and trade-offs, not just definitions.

What is AWS Terraform?

 

What is AWS Terraform?

✅ Terraform in simple words

Terraform is an Infrastructure as Code (IaC) tool by HashiCorp.
You write infrastructure in declarative config files (HCL), and Terraform creates/updates/destroys resources safely. HashiCorp Developer+1

Think of it like:

“Git for infrastructure” — your AWS setup becomes version-controlled code.


Why Terraform is needed (Real-world reasons)

1) Repeatable environments

Create identical dev / stage / prod using the same code.

2) Change control + audit

Infra changes are reviewed in PRs and tracked in Git.

3) Safer deployments (plan → apply)

Terraform shows what will change before it changes it.

4) Avoid manual console mistakes

No “clicked wrong region / deleted wrong bucket” surprises.


Basic Example: Create S3 Bucket + Allow One Role Access

✅ What we will build

  • Create an S3 bucket

  • Block public access

  • Add a bucket policy that allows one IAM role to:

    • List the bucket

    • Read/Write objects

AWS bucket policies are a standard way to grant access to buckets. AWS Documentation+1


πŸ“ Folder Structure

s3-terraform-demo/ main.tf variables.tf outputs.tf

1️⃣ main.tf

terraform { required_version = ">= 1.5.0" required_providers { aws = { source = "hashicorp/aws" version = ">= 5.0" } } } provider "aws" { region = var.aws_region } # ----------------------------- # S3 Bucket # ----------------------------- resource "aws_s3_bucket" "app_bucket" { bucket = var.bucket_name tags = { Name = var.bucket_name Environment = var.environment } } # Optional but recommended: block all public access resource "aws_s3_bucket_public_access_block" "app_bucket_block_public" { bucket = aws_s3_bucket.app_bucket.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true } # ----------------------------- # Bucket policy: allow ONE IAM role access # ----------------------------- data "aws_iam_policy_document" "allow_role_access" { statement { sid = "AllowRoleListBucket" effect = "Allow" principals { type = "AWS" identifiers = [var.allowed_role_arn] } actions = [ "s3:ListBucket" ] resources = [ aws_s3_bucket.app_bucket.arn ] } statement { sid = "AllowRoleReadWriteObjects" effect = "Allow" principals { type = "AWS" identifiers = [var.allowed_role_arn] } actions = [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ] resources = [ "${aws_s3_bucket.app_bucket.arn}/*" ] } } resource "aws_s3_bucket_policy" "app_bucket_policy" { bucket = aws_s3_bucket.app_bucket.id policy = data.aws_iam_policy_document.allow_role_access.json }

Notes:


2️⃣ variables.tf

variable "aws_region" { type = string description = "AWS region to deploy into" default = "us-west-2" } variable "environment" { type = string description = "Environment name (dev/stage/prod)" default = "dev" } variable "bucket_name" { type = string description = "Globally unique S3 bucket name" } variable "allowed_role_arn" { type = string description = "IAM Role ARN that should get access to the bucket" }

3️⃣ outputs.tf

output "bucket_name" { value = aws_s3_bucket.app_bucket.bucket } output "bucket_arn" { value = aws_s3_bucket.app_bucket.arn }

▶️ How to Run

1) Set variables (example)

export TF_VAR_bucket_name="vinod-demo-bucket-123456789" export TF_VAR_allowed_role_arn="arn:aws:iam::123456789012:role/MyAppRole"

2) Initialize / Plan / Apply

terraform init terraform plan terraform apply

✅ Summary (Interview-ready)

  • Terraform is IaC that manages infra lifecycle using declarative code. HashiCorp Developer+1

  • You define AWS resources like aws_s3_bucket and attach policies using aws_s3_bucket_policy. Terraform Registry+1

  • To give a role access to a bucket, you use an S3 bucket policy (resource-based policy) listing the role as a principal. AWS Documentation+1

AWS Lambda – Simple Explanation with Example

 

AWS Lambda – Simple Explanation with Example 

What is AWS Lambda?

AWS Lambda is a serverless compute service that lets you run code without managing servers.
You upload your code, and AWS automatically:

  • Runs it

  • Scales it

  • Manages infrastructure

  • Charges only for execution time


Simple Meaning

You write only the code. AWS handles servers, scaling, and availability.


πŸ—️ Traditional Server vs AWS Lambda

❌ Traditional Server

  • Provision EC2

  • Manage OS

  • Handle scaling

  • Pay even when idle

✅ AWS Lambda

  • No servers to manage

  • Auto-scaling

  • Pay per request

  • Event-driven


⚙️ How AWS Lambda Works

Event (HTTP / S3 / SQS / Cron) ↓ AWS Lambda ↓ Executes Code ↓ Returns Result

πŸ”” What Can Trigger a Lambda?

TriggerUse Case
API GatewayREST APIs
S3File upload processing
SQSMessage processing
SNSNotifications
EventBridgeScheduled jobs
DynamoDBStream processing

🧩 Supported Languages

  • Python

  • Java

  • Node.js

  • Go

  • C#

  • Ruby


πŸ§ͺ Simple AWS Lambda Example (Python)

🎯 Use Case

Create a Lambda that returns “Hello from Lambda”


1️⃣ Lambda Function Code (Python)

def lambda_handler(event, context): return { "statusCode": 200, "body": "Hello from AWS Lambda!" }

2️⃣ Explanation

  • event → input data (HTTP request, S3 event, etc.)

  • context → runtime metadata

  • Function returns response to the caller


3️⃣ Sample Input (API Gateway)

{ "name": "Vinod" }

4️⃣ Sample Output

{ "statusCode": 200, "body": "Hello from AWS Lambda!" }

Java Lambda Example (Very Simple)

public class HelloLambda { public String handleRequest() { return "Hello from Java Lambda"; } }

✔️ AWS invokes handleRequest()
✔️ No main method needed


AWS Lambda Pricing (High Level)

  • Charged by:

    • Number of requests

    • Execution time (milliseconds)

  • No cost when idle

πŸ“Œ Free tier available (1M requests/month)


Key Benefits of AWS Lambda

  • πŸš€ Auto scaling

  • πŸ’Έ Cost efficient

  • πŸ› ️ No server management

  • πŸ”„ Event-driven

  • 🌍 High availability


Limitations (Interview Important)

LimitationDetails
Cold startInitial startup delay
Execution timeMax 15 minutes
StatelessNo local persistence
Memory limitsUp to 10 GB

🌍 Real-World Use Cases

  • REST APIs

  • Image resizing

  • File validation

  • Background jobs

  • Data transformation

  • Event processing


AWS Lambda vs EC2 (Quick Compare)

FeatureLambdaEC2
Server management❌ No✅ Yes
ScalingAutomaticManual
PricingPay per executionPay per hour
Best forEvent-drivenLong-running apps

Interview One-Line Summary

AWS Lambda is a serverless compute service that runs code in response to events and automatically manages scaling and infrastructure.


Final Takeaways

  • Lambda is event-driven

  • Ideal for microservices

  • No infrastructure management

  • Best for short-lived tasks

  • Backbone of serverless architecture

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts