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

JAVA ST-2 Solutions

The document discusses various features and concepts of Java, particularly focusing on Java 8's lambda expressions, functional interfaces, and the advantages of the Stream API. It also covers Java's module system, sealed classes, and provides examples of file handling, multithreading, and Base64 encoding/decoding. Additionally, it differentiates between ByteStream and CharacterStream, and explains the life cycle of a thread in Java.

Uploaded by

amitabh29chaubey
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)
2 views6 pages

JAVA ST-2 Solutions

The document discusses various features and concepts of Java, particularly focusing on Java 8's lambda expressions, functional interfaces, and the advantages of the Stream API. It also covers Java's module system, sealed classes, and provides examples of file handling, multithreading, and Base64 encoding/decoding. Additionally, it differentiates between ByteStream and CharacterStream, and explains the life cycle of a thread in Java.

Uploaded by

amitabh29chaubey
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

ST- 2 JAVA Solution

Q1: Importance of Lambda expression in JAVA 8.


Ans:
1. Concise Code: Reduces boilerplate, especially for anonymous classes.
() -> System.out.println(“Hello”);

2. Functional Programming: Enables passing behavior as a parameter.


3. Stream API: Simpli es operations like lter, map, reduce on collections.
list.stream(). lter(x -> x > 10).forEach(System.out::println);

4. Supports Functional Interfaces: Works with Runnable, Comparator, Predicate, etc.


5. Improves Readability & Parallelism: Clean, declarative code with optional parallel
execution.
Or
Q1:Elaborate functional interface using example code.
Ans: A functional interface is an interface that contains only one abstract method. These are ideal
for use with lambda expressions.
Key Points:
• De ned using @FunctionalInterface (optional but recommended)
• Can have default or static methods, but only one abstract method
• Used heavily in Java 8’s functional programming (e.g., Runnable, Comparator, Function,
etc.)
@FunctionalInterface
interface MyPrinter {
void print(String msg);
}

public class Main {


public static void main(String[] args) {
MyPrinter printer = msg -> System.out.println("Message: " + msg);
printer.print("Hello, Lambda!");
}
}

Q2:What are the advantages of stream in java, programming? Di erentiate terminal and
intermediate stream methods
Ans: Advantages of Streams in Java
1. Clean & Concise Code: Reduces boilerplate, makes code more readable.
2. Functional Style: Supports operations like map, lter, reduce.
3. E cient Processing: Can be lazy and optimized.
4. Easy Parallelism: Use .parallelStream() for multi-core processing.
5. Chained Operations: Allows powerful data transformation pipelines.
fi
ffi
fi
fi
fi
fi
ff
Example:
List<String> names = Arrays.asList("Alice", "Bob", "Anna");

long count = names.stream() // Stream source


. lter(n -> n.startsWith("A")) // Intermediate
.count(); // Terminal

System.out.println(count); //

Output: 2

Or
Q2: Write short Note on:
a. Sealed Classes b. Java Module System

Ans: a) Sealed Class


De nition:
Sealed classes restrict which other classes can extend or implement them.
Purpose:
• Provide controlled inheritance
• Improve security and maintainability

Example:
public sealed class Shape permits Circle, Square {}

nal class Circle extends Shape {}


nal class Square extends Shape {}

Bene ts:
• Limits subclassing
• Makes code more predictable and safe

B) Java Module System


De nition:
The Java Module System allows developers to divide programs into modules, improving scalability and
maintainability.

Purpose:
• Better encapsulation
• Avoid classpath issues
• Support for large applications

Syntax Example (module-info.java):


module my.app {
requires java.sql;
exports com.myapp.utils;
}

Bene ts:
• Explicit dependencies
• Faster startup and performance
• Better code organization

Q3: Write a java code to encode and decode using Base64.


Ans: Java Code: Base64 Encoding & Decoding
import java.util.Base64;
fi
fi
fi
fi
fi
fi
fi
public class Base64Example {
public static void main(String[] args) {
String originalText = "Hello, World!";

// Encode
String encodedText = Base64.getEncoder().encodeToString(originalText.getBytes());
System.out.println("Encoded: " + encodedText);

// Decode
byte[] decodedBytes = Base64.getDecoder().decode(encodedText);
String decodedText = new String(decodedBytes);
System.out.println("Decoded: " + decodedText);
}
}

Output:
Encoded: SGVsbG8sIFdvcmxkIQ==
Decoded: Hello, World!

Or

Q3: Write a java program demonstrate the use of try with resources with example code.
Ans: Java Program: Try-with-Resources Example
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesExample {


public static void main(String[] args) {
// Make sure a le named "example.txt" exists in the project directory
String lePath = "example.txt";

// Try-with-resources block
try (BufferedReader reader = new BufferedReader(new FileReader( lePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading le: " + e.getMessage());
}
}
}

Key Points:
• No need to explicitly close Bu eredReader — it’s done automatically.
• Any class that implements AutoCloseable or Closeable can be used.

Section B

Q4: Write a java program t o Read data from a text le like sample.txt which is available in d:/sample
code folder using FileReader. [TCS]
Ans: Java Program to Read File Using FileReader
import java.io.FileReader;
import java.io.IOException;
fi
fi
ff
fi
fi
fi
public class ReadFileExample {
public static void main(String[] args) {
String lePath = "D://samplecode//sample.txt";

try (FileReader fr = new FileReader( lePath)) {


int character;
while ((character = fr.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("Error reading le: " + e.getMessage());
}
}
}

Notes:
• Use double slashes (//) in le path or a single backslash with escaping (\\).
• The try-with-resources automatically closes the FileReader.
• This is suitable for TCS Java le handling questions.

Or
Q2: Write a java program t o create 4 threads using Runnable interface, set the names and run all the
threads. [Infosys]
Ans: Java Program: 4 Threads Using Runnable
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}

public class ThreadExample {


public static void main(String[] args) {
// Create Runnable instance
Runnable task = new MyTask();

// Create 4 threads
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
Thread t3 = new Thread(task, "Thread-3");
Thread t4 = new Thread(task, "Thread-4");

// Start all threads


t1.start();
t2.start();
t3.start();
t4.start();
}
}

Output (Sample):
Thread running: Thread-1
Thread running: Thread-3
Thread running: Thread-2
Thread running: Thread-4
(Note: Output order may vary as threads run concurrently.)
fi
fi
fi
fi
fi
Q5: Di erentiate between ByteStream and CharacterStream with suitable example.

Example: ByteStream (Reading Binary File)


import java.io.FileInputStream;
import java.io.IOException;

public class ByteStreamExample {


public static void main(String[] args) {
try (FileInputStream s = new FileInputStream("image.jpg")) {
int byteData;
while ((byteData = s.read()) != -1) {
System.out.print(byteData + " ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Example: CharacterStream (Reading Text File)


import java.io.FileReader;
import java.io.IOException;

public class CharacterStreamExample {


public static void main(String[] args) {
try (FileReader reader = new FileReader("text le.txt")) {
int charData;
while ((charData = reader.read()) != -1) {
System.out.print((char) charData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Summary:
• Use ByteStreams for binary data.
• Use CharacterStreams for text data.
ff
fi
fi
fi
Or

Q5:Discuss the role of multithreading programming in large scale application. Explain life cycle of a
thread.
Ans: Role of Multithreading in Large-Scale Applications

Multithreading allows multiple tasks to run concurrently in the same program. It’s critical for performance
and responsiveness in large-scale applications.

Key Roles:
1. Improved Performance: Tasks like I/O, processing, or computation can run in parallel.
2. Responsiveness: UI or web servers stay active while background tasks run.
3. Resource Sharing: Threads share memory space e ciently.
4. Scalability: Makes full use of multi-core CPUs.
5. Faster Execution: Reduces idle time and increases throughput.

Use Cases:
• Web servers handling multiple requests
• Game engines (UI + logic + physics running in parallel)
• Financial applications (real-time trading + logging + monitoring)

Life Cycle of a Thread in Java

Java threads go through 5 main states as per Thread.State:

1. New
• Thread is created using Thread t = new Thread();
• Not started yet

2. Runnable
• After calling start()
• Ready to run, but may wait for CPU

3. Running
• Actively executing the run() method

4. Blocked/Waiting/Sleeping
• Temporarily inactive
• Blocked: waiting for a resource
• Sleeping: using Thread.sleep(ms)
• Waiting: using wait() or join()

5. Terminated (Dead)
• Run method is completed or exception occurred

Thread Life Cycle Diagram:


NEW → start() → RUNNABLE → RUNNING → (WAITING/SLEEPING/BLOCKED) → RUNNING →
TERMINATED
ffi

You might also like