0% found this document useful (0 votes)
13 views6 pages

Java Sol 1,4

Uploaded by

neha praveen
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)
13 views6 pages

Java Sol 1,4

Uploaded by

neha praveen
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/ 6

1a) Explain the concepts of raw types in java? Why are they consider unsafe?

Write a
program that demonstrate the use of raw types and explain the compiler warning
generated

Concepts of Raw Types:

In Java, raw types refer to using a generic class or interface without specifying a type
parameter. For example, using List instead of List<String>. Raw types were primarily used
in Java before generics were introduced (Java 5) to provide backward compatibility.

Why are Raw Types Considered Unsafe? Raw types are considered unsafe because
they bypass the type checking provided by generics. This can lead to ClassCastException at
runtime, which would otherwise be caught at compile time if generics were used
properly.

Example Program:

java
Copy code
import java.util.ArrayList;
import java.util.List;

public class RawTypeExample {


public static void main(String[] args) {
// Using raw type
List rawList = new ArrayList();
rawList.add("String1");
rawList.add(123); // Adding an integer

// This line will compile but cause ClassCastException at runtime


for (Object obj : rawList) {
String str = (String) obj; // Potential ClassCastException
System.out.println(str);
}
}
}

Compiler Warning:

When compiling the above code, you might see a warning similar to:

RawTypeExample.java uses unchecked or unsafe operations.


Recompile with -Xlint:unchecked for details.

This warning indicates that you're using raw types and the compiler can't ensure type safety,
potentially leading to runtime exceptions.
1 b) Differentiate between string and stringBuffer. explain reverse() method
of stringBuffer with an example.

• String:

• Immutable: Once a String object is created, it cannot be changed.


• Performance: Slower for concatenation operations as it creates new objects for each
concatenation.
• Example:

String str = "Hello";


str = str + " World"; // Creates a new String object

• StringBuffer:

• Mutable: Can be changed after creation.


• Performance: Faster for concatenation and modifications as it uses a mutable array of
characters.
• Thread-Safe: Methods are synchronized, making it safe for use in a multi-threaded
environment.
• Example:

StringBuffer sb = new StringBuffer("Hello");


sb.append(" World"); // Modifies the existing StringBuffer object

reverse() Method of StringBuffer: The reverse() method reverses the characters in the
StringBuffer object.

Example:

java
Copy code
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
sb.reverse();
System.out.println(sb); // Output: dlroW olleH
}
}

In this example, the reverse() method changes the order of characters in the StringBuffer
object from "Hello World" to "dlroW olleH".
4 a) Develop a java program to count the occurance of characters in the given
string. Explain IndexOf and LastIndexOf()method of string class with example.

java
Copy code
import java.util.HashMap;
import java.util.Map;

public class CharacterCount {


public static void main(String[] args) {
String input = "example string";
Map<Character, Integer> charCountMap = new HashMap<>();

for (char c : input.toCharArray()) {


charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}

for (Map.Entry<Character, Integer> entry : charCountMap.entrySet())


{
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Explanation:
• HashMap: Used to store characters as keys and their occurrences as values.
• toCharArray() method: Converts the string into a character array for easy iteration.

• getOrDefault(c, 0) + 1: If the character is not already in the map, it returns 0;


otherwise, it returns the current count and increments it by 1.

indexOf and lastIndexOf Methods in the String Class

• indexOf Method:
o Returns the index within the string of the first occurrence of the specified
character or substring. If the character or substring is not found, it returns -1.
o Example:

public class IndexOfExample {


public static void main(String[] args) {
String str = "example string";
int index1 = str.indexOf('e'); // Returns 0
int index2 = str.indexOf("string"); // Returns 8
int index3 = str.indexOf('x', 2); // Returns 1
(starting search from index 2)

System.out.println(index1); // Output: 0
System.out.println(index2); // Output: 8
System.out.println(index3); // Output: 1
}
}
• lastIndexOf Method:
o Returns the index within the string of the last occurrence of the specified
character or substring. If the character or substring is not found, it returns -1.
o Example:

public class LastIndexOfExample {


public static void main(String[] args) {
String str = "example string";
int lastIndex1 = str.lastIndexOf('e'); // Returns 7
int lastIndex2 = str.lastIndexOf("string"); // Returns
8
int lastIndex3 = str.lastIndexOf('e', 6); // Returns 0
(searches backward from index 6)

System.out.println(lastIndex1); // Output: 7
System.out.println(lastIndex2); // Output: 8
System.out.println(lastIndex3); // Output: 0
}
}
4b) What are the legacy classes and interfaces in java? Provide examples
write a program that uses a legacy collection class and then refactor it to use
the generic collection.

Legacy Classes and Interfaces: In Java, legacy classes and interfaces refer to
those that existed before Java 2 (Java 1.2), when the Collections Framework
was introduced. These include classes and interfaces in the java.util
package, such as:

• Vector
• Hashtable
• Stack
• Enumeration

These classes were later adapted to work with the Collections Framework and
generics, but they are considered legacy because they were designed before the
collections framework was introduced.

Example Program Using a Legacy Collection Class

Using Vector (Legacy Collection Class)


java
Copy code
import java.util.Vector;

public class LegacyCollectionExample {


public static void main(String[] args) {
Vector items = new Vector();
items.add("Apple");
items.add("Banana");
items.add("Cherry");

// Iterate using Enumeration (legacy interface)


java.util.Enumeration enumeration = items.elements();
while (enumeration.hasMoreElements()) {
String item = (String) enumeration.nextElement();
System.out.println(item);
}
}
}

Refactored Program Using Generic Collection

Using ArrayList (Generic Collection Class)


import java.util.ArrayList;
import java.util.List;

public class GenericCollectionExample {


public static void main(String[] args) {
List<String> items = new ArrayList<>();
items.add("Apple");
items.add("Banana");
items.add("Cherry");

// Iterate using for-each loop


for (String item : items) {
System.out.println(item);
}
}
}

Explanation

• Vector (Legacy Collection):


o Vector is a legacy class that is synchronized (thread-safe), but it lacks the modern
features of the Collections Framework.
o The example uses Vector without generics, so it requires explicit type casting when
retrieving elements.
o Iteration is done using Enumeration, which is also a legacy interface.
• ArrayList (Generic Collection):
o ArrayList is part of the modern Collections Framework and supports generics,
providing type safety at compile time.
o The example uses ArrayList<String> to ensure that only String objects are
stored.
o Iteration is done using the enhanced for-loop (for-each), which is more concise and
readable.

You might also like