IA2 Java
IA2 Java
1 Explain the changing the case of characters within a string with example
The method toLowerCase( ) converts all the characters in a string from uppercase to lower
case.
The toUpperCase( ) method converts all the characters in a string from lowercase to
uppercase.
String toLowerCase( )
String toUpperCase( )
Both methods return a String object that contains the uppercase or lowercase equivalent of
the invoking String.
public class CO {
The javax.servlet package is a fundamental part of Java EE (Enterprise Edition) used for
web development. Here are three key points about it:
• User Request
o A user enters a URL in their web browser.
o The browser creates an HTTP request for this URL.
o This request is sent to the appropriate web server.
• Server Receives Request
o The web server receives the HTTP request.
o The server maps the request to a specific servlet.
o The servlet is dynamically loaded into the server's memory.
• Initialization (init() method)
o The server calls the init() method of the servlet.
o This method is called only once, the first time the servlet is loaded.
o Initialization parameters can be passed to the servlet for configuration.
• Processing Requests (service() method)
o The server calls the service() method of the servlet.
o This method handles the HTTP request.
o The servlet can read data from the request and create a response for the client.
o The servlet stays in memory and can handle more requests.
o The service() method is called for each new HTTP request.
• Shutdown (destroy() method)
o The server may decide to unload the servlet from memory.
o The specific time and conditions for unloading depend on the server.
o The server calls the destroy() method of the servlet.
o This method releases any resources (like file handles) used by the servlet.
o Important data can be saved to a persistent store.
o The servlet's memory is then available for garbage collection.
The length() method returns the current length of the StringBuffer, while capacity()
returns the total allocated capacity.
// Output:
// buffer = Hello
// length = 5
// capacity = 21
ensureCapacity()
class EnsureCapacityDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Initial capacity = " + sb.capacity());
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity(50) = " +
sb.capacity());
}}
// Output:
// Initial capacity = 21
// Capacity after ensureCapacity(50) = 50
setLength()
The setLength() method sets the length of the StringBuffer. If the new length is greater,
null characters are added. If it is less, characters beyond the new length are lost.
class SetLengthDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
sb.setLength(2);
System.out.println("buffer after = " + sb);
}
}
// Output:
// buffer before = Hello
// buffer after = He
The charAt() method retrieves the character at a specified index, while setCharAt() sets
the character at a specified index.
// Output:
// buffer before = Hello
// charAt(1) before = e
// buffer after = Hi
// charAt(1) after = i
getChars()
The getChars() method copies a substring of the StringBuffer into a character array.
class GetCharsDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello World");
char[] target = new char[5];
sb.getChars(0, 5, target, 0);
System.out.print("Copied characters: ");
for(char c : target) {
System.out.print(c);
}
}
}
// Output:
// Copied characters: Hello
Because String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or StringBuilder, or use one of the following String
methods, which will construct a new copy of the string with your modifications complete.
substring()
The substring() method can be used to extract a part of a string. It has two forms:
concat()
The concat() method concatenates two strings, creating a new string that contains the
invoking string with the contents of the specified string appended to the end.
public class CO {
public static void main(String[] args) {
String s1 = "wel come to";
String s2 = " cec";
System.out.println("Concatenation = " + s1.concat(s2));
}
}
// Output:
// Concatenation = wel come to cec
`CharSequence` in Java is like a blueprint for anything that can hold a series of characters
you can read. It's more flexible than `String` because it includes `String`, `StringBuilder`, and
`StringBuffer` as types of sequences you can work with. While `String` is fixed to one type of
sequence, `CharSequence` lets you handle different kinds of character sequences in a similar
way.
The trim() method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed.
public class CO {
public static void main(String[] args) {
String s1 = " wel come to cec ";
System.out.println("trim() = " + s1.trim());
}
}
// Output:
// trim() = wel come to cec
public class CO {
public static void main(String[] args) {
// Initialize variables
int a = 10;
float b = 10;
double c = 10.0;
char d = 'a';
char e[] = {'a', 'b', 'c'};
reverse( ) :
We can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
public class CO {
public static void main(String[] args) {
// Create a StringBuffer object initialized with "Hello"
StringBuffer b = new StringBuffer("Hello");
equals()
• Usage: Compares two strings for equality based on character sequence and case
sensitivity.
• General Form: boolean equals(Object str)
• Description: Returns true if the invoking string object and the specified string str
have the exact same characters in the same order; otherwise, returns false.
equalsIgnoreCase()
• Usage: Compares two strings for equality while ignoring differences in case
sensitivity.
• General Form: boolean equalsIgnoreCase(String str)
• Description: Returns true if the invoking string object and the specified string str
have the same characters in the same order, treating uppercase letters (A-Z) as
equivalent to their corresponding lowercase letters (a-z); otherwise, returns false.
public class CO {
public static void main(String[] args) {
String a = "hello";
String b = "Hello";
startsWith()
endsWith()
A string literal in Java is just a piece of text enclosed within double quotes, like "hello" or
"123". When you write a string literal in your Java code, it's automatically treated as a String
object. This means you can use it like any other object in Java, with methods and operations
that are available for strings.
For example, "hello".length() will give you the length of the string "hello".
Additionally, if you have an array of characters (like char[] chars = {'a', 'b',
'c'}), you can create a String object from this array using the new keyword:
Here, str will be a String object containing the characters 'a', 'b', and 'c'.
Java automatically constructs a String object. Thus, you can use a string literal to initialize a
String object.
String b=”hello”;
System.out.println(“Length of string=”+“hello”.length());
9 Demonstrate getchar ( ) method with suitable programming example. Ans- 4th in pdf
10 Any 2 string classes with examples
Empty String:
String with one argument as Char: abcd
String with Three argument as Char: bcd
String with String object: abcd
byte to String: ABCDE
byte to string for subbyte: BC
StringBuffer to String: hello
StringBuilder to String: welcome
codepoint to String: CDE
11 Character Extraction
5.1 charAt()
To extract a single character from a String, you can use the charAt() method. It has this
general form:
Here, where is the index of the character that you want to obtain. The value of where must be
nonnegative and within the bounds of the string. charAt() returns the character at the
specified location. For example:
char ch;
ch = "abc".charAt(1); // assigns the value 'b' to ch
5.2 getChars()
If you need to extract more than one character at a time, you can use the getChars() method.
It has this general form:
// Using charAt()
char c = a.charAt(1);
System.out.println("charAt=" + c); // Output: charAt=e
// Using getChars()
char ch[] = new char[2];
a.getChars(1, 3, ch, 0);
System.out.println(ch); // Output: el
// Using getBytes()
byte b[] = a.getBytes();
System.out.println(b); // Output: [B@19821f (byte array
representation)
// Using toCharArray()
char ch1[] = a.toCharArray();
System.out.println(ch1); // Output: hello
}
}
12 Demonstrate Lambda Expressions Exceptions and Variable Capture.
• Access to Enclosing Scope: Lambda expressions in Java can access instance variables and
static variables defined in their enclosing class. They can also use this, which refers to the
instance of the enclosing class where the lambda is defined. This allows lambda expressions
to read and modify instance variables or call methods of the enclosing class.
• Local Variable Capture: When a lambda expression uses a local variable from its
enclosing scope, it must adhere to the rule of effectively final variables. An effectively final
variable is one that is assigned a value only once and that value does not change afterward. It
doesn't need to be explicitly declared as final, but if it were, it would still be valid.
• Effectively Final Variables: Lambda expressions cannot modify local variables from their
enclosing scope. Modifying such a variable would remove its effectively final status and
make it illegal for the lambda expression to capture it. This rule ensures that the lambda
expression does not cause unintended side effects or conflicts with other parts of the program.
• Instance Variables: Unlike local variables, lambda expressions can freely access and
modify instance variables of their enclosing class without restrictions.
13 Demonstrate difference between string buffer and string builder with suitable
example.
StringBuffer
sb.append(" ");
sb.append("World");
StringBuilder
sb.append(" ");
sb.append("World");
String Builder
public class StrCon {
public static void main(String[] args) {
// Creating an empty String
String a = new String();
System.out.println("Empty String: " + a);
In Java generics, bounded types refer to restrictions that can be placed on the types that can
be used as type arguments when instantiating a generic class or invoking a generic method.
These restrictions enforce specific relationships or capabilities that the type parameter must
have.
• Problem Statement: You want to create a generic class Stats that computes the average
of an array of numbers of any type (Integer, Float, Double, etc.).
• Initial Attempt: You define the class Stats<T> where T is a generic type parameter. The
class has an array nums of type T to hold numbers passed to it.
• Issue: In the average() method of Stats, you try to compute the average by summing up
the values in nums array. To do this, you attempt to call doubleValue() on each element of
nums to convert it to double. However, the compiler doesn't know that T will always be a
numeric type that supports doubleValue().
• Compiler Error: Since T could be any type (not necessarily numeric), the compiler
reports an error because it can't verify that doubleValue() exists for all possible types T.
• Solution - Bounded Type Parameter: To solve this, you can use a bounded type
parameter that restricts T to be only numeric types (subclasses of Number). This ensures:
• Revised Approach: Modify Stats class to use a bounded type parameter T extends
Number. This tells the compiler that T can only be a subclass of Number, ensuring
doubleValue() is available for all instances of T.
• Java provides bounded types to constrain the types that can be used as type arguments
in generic classes or methods.
• An upper bound is specified using the extends keyword followed by a superclass or
interface.
• This ensures that the type parameter (T) can only be replaced by types that are either
the specified superclass or subclasses thereof.
• To ensure that a generic class handles specific types only (e.g., numeric types), you
can use an upper bound.
• In the example, the Stats<T extends Number> specifies that T can only be Number
or its subclasses.
// Demonstrate Stats.
class BoundsDemo {
public static void main(String args[]) {
// Integer array
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
// Double array
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
• By bounding type T with Number, Java ensures that all objects of type T can call
doubleValue() because it's a method declared by Number.
• This restriction prevents the creation of non-numeric Stats objects. For instance,
trying to instantiate Stats<String> will result in compile-time errors because
String is not a subclass of Number.