0% found this document useful (0 votes)
8 views19 pages

java_workbook_Vignesh

The document contains a series of programming puzzles and their solutions, focusing on string manipulation, sorting, and data structure usage in Java. Each puzzle presents a scenario requiring specific coding techniques, such as decrypting messages, swapping vowels, sorting words, and managing collections. Additionally, it includes short answers related to servlet programming and HTTP status codes.

Uploaded by

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

java_workbook_Vignesh

The document contains a series of programming puzzles and their solutions, focusing on string manipulation, sorting, and data structure usage in Java. Each puzzle presents a scenario requiring specific coding techniques, such as decrypting messages, swapping vowels, sorting words, and managing collections. Additionally, it includes short answers related to servlet programming and HTTP status codes.

Uploaded by

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

VIGNESH K S

1CR23MC118
ACROSS

3. Override
Clue: I am going to change your implementation

5. ParseInt
Clue: Converts string to int
7. Interface
Clue: Create an annotation

8. Autoboxing
Clue: Converts primitive type to wrapper

9. Target
Clue: I specify whom an annotation is meant for

10. Ordinal
Clue: A method gives positional value (used with enums)

DOWN

1. Values
Clue: Method that returns all enum constants

2. Retention
Clue: Specifies the scope of annotation

4. Deprecated
Clue: Oops I am no longer available
6. Marker
Clue: Annotation with no
elements

Puzzle 1: The Treasure Hunt Message

Story:

You are an adventurer looking for hidden treasure in a remote jungle.


You've found a mysterious ancient scroll that reads:

"Xfgntq wt tfqqmfy xj xjqqd!"

The message seems to be encrypted, but there’s a hint on the scroll: "Shift

the letters by 3 places backward and solve!"

Your task is to decrypt the message and find out where the treasure is
hidden.

Question:
Write a program using a String to decrypt the message and reveal the
location of the treasure. You need to shift each letter backward by 3 places
in the alphabet (e.g., 'D' becomes 'A').

Solution:

public class
TreasureHuntDecryptor { public
static void main(String[] args) {
String encryptedMessage = "Xfgntq wt tfqqmfy xj xjqqd!"; StringBuilder
decryptedMessage = new StringBuilder();

for (char c :
encryptedMessage.toCharArray()) { if
(Character.isLetter(c)) { char base =
Character.isUpperCase(c) ? 'A' : 'a';

char decryptedChar = (char) ((c - base - 3 + 26) % 26 + base);


decryptedMessage.append(decryptedChar);
} else {
decryptedMessage.append(c);
}
}
System.out.println("Decrypted Message: " + decryptedMessage);
}
}

Puzzle 2: The Mischievous Parrot

Story:

In a distant land, there is a parrot that repeats everything you say.


However, it does something strange: it swaps every vowel with the next
vowel in the sequence (a → e, e → i, i → o, o → u, u → a).

You say to the parrot: "Hello, how are you?"

The parrot responds by repeating what you said, but with all vowels
swapped.

Question:
Write a program using StringBuffer to swap the vowels in the given sentence
and output what the parrot says in response.

Solution:

public class MischievousParrot

{ public static void main (String[]

args) {

String input = "Hello, how are you?";

StringBuffer result = new StringBuffer();

for (int i = 0; i < input.length(); i++)

{ char c = input.charAt(i);

result.append(swapVowel(c));

System.out.println("Parrot says: " + result.toString());

}
private static char swapVowel(char c) {

switch (c)

{ case 'a': return

'e';

case 'e': return 'i';

case 'i': return 'o';

case 'o': return 'u';

case 'u': return 'a';

// Handle uppercase

vowels case 'A': return

'E'; case 'E': return 'I';

case 'I': return 'O'; case

'O': return 'U'; case 'U':

return 'A';

default:

return c;

Puzzle 3: The Case of Mixed-Up Letters

Story:

You have a string containing a sentence, and it’s been scrambled in a


specific way. The sentence needs to be sorted by the alphabetical order of
the words.

The scrambled sentence is: "lived

lives wonderful we in world"


Question:
Using StringBuffer and String, sort the words alphabetically in the sentence
and output the correct order.

Solution:

import java.util.Arrays;

public class MixedUpLetters {

public static void main(String[]

args) {

String sentence = "lived lives wonderful we in world";

// Split sentence into words

String[] words = sentence.split(" ");

// Sort the words alphabetically

Arrays.sort(words);

// Use StringBuffer to construct the sorted

sentence StringBuffer sortedSentence = new

StringBuffer(); for (String word : words) {

sortedSentence.append(word).append(" ");

// Trim the trailing space and print result

System.out.println("Sorted Sentence: " +


sortedSentence.toString().trim());

}
Puzzle 4: The Lost Map Pieces

Story:

You’ve uncovered a series of old, torn pieces of a treasure map scattered


across the jungle. Each piece has a number on it, but they are not in order.
Your task is to reorganize the pieces in ascending order to piece together
the map.

You find the following list of pieces:

[5, 3, 8, 1, 7]

The treasure is hidden at the location indicated by the last piece, so you
need to sort the pieces correctly.

Question:
Write a program using a List<Integer> to sort the list of pieces in ascending
order. Output the sorted list to find out which piece marks the treasure
location.

Solution:

import java.util.*;

public class LostMapPieces {

public static void main(String[]

args) {

List<Integer> pieces = Arrays.asList(5, 3, 8, 1, 7);

Collections.sort(pieces);

System.out.println("Sorted Map Pieces: " + pieces);

int treasureLocation = pieces.get(pieces.size() - 1);

System.out.println("The treasure is at piece: " + treasureLocation);

}
Puzzle 5: The Wizard's Potion Ingredients

Story:

A wizard is brewing a potion and has a list of ingredients, but some


ingredients are duplicates. He wants to make sure there is only one of each
ingredient in the potion. You are given the following list of ingredients:

["Eye of Newt", "Toadstool", "Dragon Scale", "Eye of Newt", "Bat Wing"]

The wizard says, "I don’t need duplicates. Only unique ingredients will
work in the potion!"

Question:
Write a program using a Set<String> to remove duplicates from the list and
output the unique ingredients.

Solution:

import java.util.*;

public class WizardsPotion


{ public static void main(String[]
args) {
// List of ingredients with duplicates
List<String> ingredients = Arrays.asList(
"Eye of Newt",
"Toadstool",
"Dragon Scale",
"Eye of Newt",
"Bat Wing"
);

// Use a Set to remove duplicates


Set<String> uniqueIngredients = new LinkedHashSet<>(ingredients); //
preserves insertion order // Output the unique ingredients
System.out.println("Unique Ingredients for the
Potion:"); for (String ingredient :
uniqueIngredients) {

System.out.println("- " + ingredient);


}
Puzzle 6: The Pirate's Stash

Story:

You’ve discovered a pirate’s stash of treasure, but all the gold coins are
mixed up in different bags. You need to sort the coins by their value to
determine which bag contains the highest value. Each bag contains a list
of coins, represented by a List<Integer>.

The bags contain the following coins:

[100, 50, 200, 150] [300, 100, 50] [200, 500, 50]

Question:
Write a program using List<List<Integer>> to sort the coins in each bag in
ascending order and print out the sorted bags of coins.

Solution:

import java.util.*;

public class PiratesStash { public

static void main(String[] args) {

// List of bags, each with a list of coin values

List<List<Integer>> coinBags = new ArrayList<>();

// Adding bags coinBags.add(new

ArrayList<>(Arrays.asList(100, 50, 200, 150)));

coinBags.add(new ArrayList<>(Arrays.asList(300, 100, 50)));

coinBags.add(new ArrayList<>(Arrays.asList(200, 500, 50)));

// Sort coins in each bag for

(int i = 0; i < coinBags.size(); i++) {

Collections.sort(coinBags.get(i));
}

// Print sorted coin bags

System.out.println("Sorted Bags of Coins:");

for (int i = 0; i < coinBags.size(); i++) {

System.out.println("Bag " + (i + 1) + ": " + coinBags.get(i));

Puzzle 7: The Legendary Artifacts

Story:

You are an archaeologist who has found several artifacts from different
time periods. These artifacts are stored in a collection, but they need to be
classified into two categories: ancient and modern.

The artifacts are represented by the following list of objects:

["Ancient Vase", "Modern Sculpture", "Ancient Sword", "Modern Painting",


"Ancient Shield"]

The museum curator tells you: "Please separate the artifacts into two
lists—one for ancient artifacts and one for modern artifacts."

Question:
Write a program using two List<String> to classify the artifacts into ancient
and modern categories. Output the two separate lists.

Solution:

import java.util.*;

public class LegendaryArtifacts {

public static void main(String[] args) {

// List of all artifacts

List<String> artifacts = Arrays.asList(


"Ancient Vase",

"Modern Sculpture",

"Ancient Sword",

"Modern Painting",

"Ancient Shield"

);

// Separate lists for ancient and modern artifacts

List<String> ancientArtifacts = new ArrayList<>();

List<String> modernArtifacts = new ArrayList<>();

// Classify artifacts for (String

item : artifacts) { if

(item.startsWith("Ancient")) {

ancientArtifacts.add(item); } else if

(item.startsWith("Modern")) {

modernArtifacts.add(item);

// Output the categorized lists

System.out.println("Ancient Artifacts:");

for (String ancient : ancientArtifacts) {

System.out.println("- " + ancient);

}
System.out.println("\nModern Artifacts:");

for (String modern : modernArtifacts) {

System.out.println("- " + modern);

Puzzle 8: The Student's Grades

Story:

A teacher has a list of students and their grades, but he wants to find the
highest grade and determine which student received it. The grades are
stored in a Map<String, Integer> where the key is the student’s name, and
the value is their grade.

Here’s the list of students and their grades:

{"Alice": 85, "Bob": 92, "Charlie": 88, "David": 91}

The teacher says, "Find out who got the highest grade in the class!"

Question:
Write a program using a Map<String, Integer> to find the student with the
highest grade and output their name and grade.

import java.util.*;

public class StudentGrades {

public static void main(String[]

args) {

// Map of students and their grades

Map<String, Integer> grades = new

HashMap<>(); grades.put("Alice", 85);

grades.put("Bob", 92);

grades.put("Charlie", 88);

grades.put("David", 91);
// Variables to track highest

grade String topStudent = "";

int highestGrade =

Integer.MIN_VALUE;

// Find the highest grade for

(Map.Entry<String, Integer> entry :

grades.entrySet()) { if (entry.getValue() >

highestGrade) { highestGrade =

entry.getValue(); topStudent =

entry.getKey();

// Output the top student's name and grade

System.out.println("Top Student: " + topStudent);

System.out.println("Highest Grade: " + highestGrade);

Puzzle 9: The Magical Bag of Marbles

Story:

A magician has a bag of marbles in different colors. The magician is


preparing a trick and wants to find out how many marbles of each color
are in the bag. The bag contains the following colors of marbles:

["Red", "Blue", "Red", "Green", "Blue", "Red"]

The magician says, "I need to know how many of each color I have for my
trick!"

Question:
Write a program using a Map<String, Integer> to count the occurrences of
each marble color and output the counts.
import java.util.*;

public class MarbleCount {

public static void main(String[]

args) {

// List of marbles

List<String> marbles = Arrays.asList("Red", "Blue", "Red", "Green", "Blue",


"Red");

// Map to store the count of each marble color

Map<String, Integer> marbleCount = new HashMap<>();

// Loop through the list of marbles and count the

occurrences for (String marble : marbles) {

marbleCount.put(marble, marbleCount.getOrDefault(marble,

0) + 1);

// Output the counts of each marble color for

(Map.Entry<String, Integer> entry :

marbleCount.entrySet()) {

System.out.println(entry.getKey() + ": " + entry.getValue());

Puzzle 10: The Lost Keys

Story:

You’ve found a set of keys, each with a unique identifier. Unfortunately,


one of the keys is missing. The keys are in a Set<String>, but you need to
check which one is missing by comparing it to the expected set.

Here is the expected set of keys:

{"Key1", "Key2", "Key3", "Key4", "Key5"}


And here is the set you found:

{"Key1", "Key3", "Key5", "Key2"}

The key is missing. Your task is to figure out which one.

Question:
Write a program using Set<String> to find the missing key and output its
identifier.

import java.util.*;

public class MissingKey {

public static void main(String[]

args) {

// Expected set of keys

Set<String> expectedKeys = new HashSet<>(Arrays.asList("Key1", "Key2",


"Key3", "Key4", "Key5"));

// Set of keys found

Set<String> foundKeys = new HashSet<>(Arrays.asList("Key1", "Key3", "Key5",


"Key2"));

// Find the missing key by checking the difference between the sets

expectedKeys.removeAll(foundKeys);

// The remaining element in the expected set is the missing key

System.out.println("The missing key is: " + expectedKeys.iterator().next());

Short Answer - One line code


1. Give the code to retrieve the MIME type of the body of the request?

String mimeType = request.getContentType();

2. Give the code to get PrintWriter object in servlet

PrintWriter out = response.getWriter();

3. Give the code can be used to set the length of content of body of the
response?

response.setContentLength(length);

4. Give the code to create a cookie in servlet?

Cookie cookie = new Cookie("name", "value"); response.addCookie(cookie);

5. Write the statement to create a connection to the database?

Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",
"username", "password");

6. Give the code snippet to do batch updates.

connection.createStatement().addBatch("SQL_QUERY");
connection.createStatement().executeBatch();
7. List the methods of resultset. resultSet.getString(), resultSet.getInt(),
resultSet.getDate(), resultSet.next(), resultSet.previous(), etc.

Complete the table with the appropriate

Sl.# Header/Status code Description

Specifies the domain name of the server (used in


1. Host virtual hosting)

2. Connection Controls whether the network connection stays open


after the current transaction

Accept-Language
3. Specifies the Client proferred Languages

Adds a cookie to the response


4. response.addCookie(ck)

Moved Permanently (used for URL redirection)


5. Status code : 301

Forbidden (client does not have access rights)


6. Status code : 403

Service Unavailable (server is temporarily unavailable)


7. Status code : 503

ck.setMaxAge(0)
8. Set cookie age to as zero

9.
a) javax.servlet List 2 packages represent interfaces and
b) javax.servlet.http classes for servlet api
10. HttpSession Provides a way to identify a user across
more than one page request or visit to a
Web site and to store information about
that user
public String Returns a string containing servlet information
11. (description etc.)
getServletInfo()

12. List any 3 a. public void init(ServletConfig


methods of config)
GenericServlet class b. public abstract void
service(ServletRequest req,
ServletResponse res)
c. public void destroy()
THANK
YOU

You might also like