Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Kunal Java Unit-3

Uploaded by

manglamdubey2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Kunal Java Unit-3

Uploaded by

manglamdubey2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

INDEX:

1. What are different string methods?

2. What is string buffer? Explain some methods of it.

3. What are wrapper classes in Java? Why we need them?

4. WAP in Java using Reader and Writer classes for

reading from and writing data into disk files.

5. What are thread class and thread class methods in java.

6. Explain thread lifecycle.


1. What are different string methods?
ANS- Java's String class provides a wide variety of methods for string manipulation:
Length: Returns the length of the string.
int length = str.length();

CharAt: Returns the character at the specified index.


char ch = str.charAt(0);

Substring: Returns a new string that is a substring of the original string.


String substr = str.substring(2); // from index 2 to end
String substr2 = str.substring(2, 5); // from index 2 to 4

IndexOf: Returns the index of the first occurrence of the specified character or
substring.
int indexOfChar = str.indexOf('e');
int indexOfSubstring = str.indexOf("lo");

ToLowerCase: Converts all the characters in the string to lowercase.


String lowerCaseStr = str.toLowerCase();

ToUpperCase: Converts all the characters in the string to uppercase.


String upperCaseStr = str.toUpperCase();
2. What is string buffer? Explain some methods of it.
ANS- StringBuffer in Java is a mutable sequence of characters, meaning it can be
modified after it is created.
It allows modifications like append, insert, and delete, making it ideal for string
manipulation tasks.
Example demonstrating the usage of some StringBuffer methods:
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

// Append
sb.append(" World");
System.out.println(sb); // Hello World

// Insert
sb.insert(5, " Java");
System.out.println(sb); // Hello Java World

// Replace
sb.replace(5, 10, "Awesome");
System.out.println(sb); // HelloAwesome World

// Delete
sb.delete(5, 12);
System.out.println(sb); // Hello World

// Reverse
sb.reverse();
System.out.println(sb); // dlroW olleH

// Capacity
System.out.println("Capacity: " + sb.capacity()); // Capacity: 21

// Ensure capacity
sb.ensureCapacity(50);
System.out.println("New Capacity: " + sb.capacity()); // New Capacity: 50
}
}
3. What are wrapper classes in Java? Why we need them?
ANS- Wrapper classes in Java are used to convert primitive data types into objects.
They are part of the java.lang package and provide a way to use primitive data types
(like int, char, boolean, etc.) as objects. Each primitive data type has a corresponding
wrapper class:
1. Integer: Wraps the primitive type int.
2. Boolean: Wraps the primitive type boolean.
3. Character: Wraps the primitive type char.
4. Byte: Wraps the primitive type byte.
5. Short: Wraps the primitive type short.
6. Long: Wraps the primitive type long.
7. Float: Wraps the primitive type float.
8. Double: Wraps the primitive type double.
Example Usages
1. Integer
int primitiveInt = 5;
Integer integerObj = Integer.valueOf(primitiveInt); // Boxing
int unboxedInt = integerObj.intValue(); // Unboxing
2. Boolean
boolean primitiveBoolean = true;
Boolean booleanObj = Boolean.valueOf(primitiveBoolean); // Boxing
boolean unboxedBoolean = booleanObj.booleanValue(); // Unboxing
3. Character
char primitiveChar = 'a';
Character characterObj = Character.valueOf(primitiveChar); // Boxing
char unboxedChar = characterObj.charValue(); // Unboxing

Importance of Wrapper Classes


1. Collections: Collections like ArrayList, HashMap, etc., cannot store primitive
types directly, but they can store objects of wrapper classes.
2. Null Values: Wrapper classes can represent null, while primitive types cannot,
making them useful for handling nullability in certain scenarios.
4. WAP in Java using Reader and Writer classes for reading from and writing
data into disk files.
ANS-
import java.io.*;
public class IOStreamExample {
public static void main(String[] args) {
try {
// Writing to a file using FileOutputStream OR writer classes
FileOutputStream outputStream = new FileOutputStream("output.txt");
String text = "Hello, IO Streams!";
byte[] bytes = text.getBytes();
outputStream.write(bytes);
outputStream.close();

// Reading from a file using FileInputStream OR reader classes


FileInputStream inputStream = new FileInputStream("output.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); }}}
5. What are thread class and thread class methods in java.
ANS- In Java, the Thread class is a fundamental class that allows you to create and
manage threads. It provides various methods to control and work with threads.
Thread Class Methods:
1. start(): Starts the execution of the thread by calling its run() method.
2. run(): Contains the code that will be executed by the thread.
3. sleep(long millis): Makes the thread sleep for a specified number of
milliseconds.
4. join(): Waits for the thread to die (terminate) before continuing.
5. isAlive(): Checks if the thread is still alive (running or ready to run).

public class ThreadSleepExample {


public static void main(String[] args) {
System.out.println("Thread execution started...");
try {
// Making the main thread sleep for 3 seconds
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread execution completed after sleeping for 3
seconds.");
}
}
6. Explain thread lifecycle.
ANS- Threads in Java are the smallest unit of execution within a program. They
represent individual paths of execution, allowing a program to perform multiple
tasks concurrently.
Threads have a life cycle that represents their various states from creation to
termination. The thread life cycle consists of several states that a thread goes
through during its execution:
Thread States:
1. New: The thread is in this state when it's created but has not yet started. It's
just a newly born thread waiting to be executed.
2. Runnable: Once the thread's start() method is called, it moves to the
runnable state. In this state, the thread is ready to run, but it may not be
currently running due to the thread scheduler.
3. Running: When the thread scheduler selects the thread for execution, it
moves to the running state. Here, the thread is actively executing its task.
4. Blocked/Waiting: A thread can move to a blocked or waiting state due to
several reasons, like waiting for I/O, synchronization locks, or sleep() method
calls. It's temporarily inactive.
5. Timed Waiting: Similar to blocked/waiting, but for a specified period.
Threads enter this state when they call methods like Thread.sleep(),
Object.wait(timeout), or I/O operations with a timeout.
6. Terminated/Dead: The thread completes its execution and reaches the
terminated state. Once a thread is terminated, it cannot be started again.

You might also like