Java Mid-1 Imp Queans

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

IMPORTANT Q&A FROM UNITS-1,2,3

UNIT-1
1. Explain why Java Language is known as platform independent.
Ans) To explain why Java is platform independent, We should discuss the working
of the Java programming language, that can be summed up in three steps.
Let’s go through the steps given below:

1. Here for the first step, we need to have a java source code otherwise we won't
be able to run the program. you need to save it with the program.java extension.
2. Secondly, we need to use a compiler so that it compiles the source code which
in turn gives out the java bytecode and that needs to have a program.class
extension. The Java bytecode is a redesigned version of the java source codes,
and this bytecode can be run anywhere irrespective of the machine on which it
has been built.
3. Later on, we put the java bytecode through the Java Virtual Machine which is an
interpreter that reads all the statements thoroughly step by step from the java
bytecode which will further convert it to the machine-level language so that the
machine can execute the code. We get the output only after the conversion is
through.
Execution Process of Java Program:

1. Creation of a Java Program-


Start by writing your Java code using a text editor or an integrated
development environment (IDE). Java code is usually saved with a ‘.java’
extension.

2. Compilation: Once you have written your Java code, the next step is to
compile it. Compilation is the process of converting human-readable Java
code into bytecode, which is a low-level representation of the code that can
be executed only by the Java Virtual Machine (JVM).

The next step is to open a command prompt or terminal and go to the


directory where your Java code is located. Use the ‘javac’ command to
compile the Java source file.
javac HelloWorld.java

If there are no errors in the code, this will generate a bytecode with a ‘.class’
extension (e.g., HelloWorld.class).
3. Execution:
Java Virtual Machine (JVM): The computer’s hardware does not execute the
generated bytecode directly. Instead, it runs on the Java Virtual Machine
(JVM). Java is platform-independent, allowing Java programs to run on any
machine with a compatible JVM.
2. List and Explain Java Buzzwords in detail.
Ans) Java Features (Java Buzzwords):

1. Simple: Java is designed to be easy to understand and use. Its syntax is clean
and straightforward, and it removes complex features like pointers (found in
other languages like C/C++), making it beginner-friendly.
2. Object-Oriented: Java follows the Object-Oriented Programming (OOP)
paradigm. It organizes code into classes and objects, which makes programs
easier to manage and scale. Everything in Java revolves around objects and
their interactions.
3. Portable: Java code can run on any machine, as long as it has the Java Virtual
Machine (JVM) installed. You can write Java programs on one system and run
them on another without needing to modify the code.
4. Platform Independent: Java programs are compiled into bytecode (not
machine-specific code). This bytecode can be executed on any platform that
has a JVM, making Java truly "write once, run anywhere."
5. Secured: Java provides a secure environment by limiting access to certain
resources and preventing common security issues (like memory corruption
through pointers). It has built-in security features like cryptography and
security policies.
6. Robust: Java is designed to be reliable and avoid common programming
errors. Features like automatic memory management (garbage collection),
exception handling, and strong type-checking make Java robust, meaning
programs are less likely to crash.
7. Architecture Neutral: Java bytecode is designed to be compatible with
different computer architectures. This means you don’t have to worry about
the underlying hardware when you write Java code.
8. Interpreted: Java programs are first compiled into bytecode, which is then
interpreted by the JVM. This makes it easier to execute the program on
different systems, as the JVM takes care of converting the bytecode into
machine-specific instructions.
9. High Performance: Although interpreted, Java achieves good performance
through the Just-In-Time (JIT) compiler, which converts bytecode into native
machine code during runtime, speeding up execution.
10.Multithreaded: Java supports multithreading, meaning it can execute
multiple tasks at the same time (in parallel). This is useful for tasks like
playing music while downloading a file.
11.Distributed: Java supports distributed computing, allowing programs to run
across multiple computers (nodes) on a network. Java has libraries like RMI
(Remote Method Invocation) and networking capabilities to make this
easier.
12.Dynamic: Java is dynamic because it can load classes at runtime. This allows
the code to adapt to evolving environments or handle new data types as
needed, making it flexible for developers.

3. Explain various data types in Java along with their size and
range.
Ans) Data Types
• A data type is a classification of data which tells the complier how the
programmer wants to use the data.
• Data types specify the different sizes and values that can be stored in the
variable.

Two kinds of Data Types in Java:


• Primitive
• Non-Primitive
Primitive Data Types:

1. byte: 8-bit signed integer


2. short: 16-bit signed integer
3. int: 32-bit signed integer
4. long: 64-bit signed integer
5. float: 32-bit floating-point number
6. double: 64-bit floating-point number
7. boolean: Represents two values: true or false
8. char: 16-bit Unicode character

Example:
public class PrimitiveDataTypesDemo {

public static void main(String[] args) {


// byte (8-bit integer, range: -128 to 127)
byte byteValue = 100;

// short (16-bit integer, range: -32,768 to 32,767)


short shortValue = 30000;
// int (32-bit integer, range: -2^31 to 2^31-1)
int intValue = 100000;

// long (64-bit integer, range: -2^63 to 2^63-1)


long longValue = 10000000000L; // Note the 'L' suffix for
long literals

// float (32-bit floating point, use 'f' suffix)


float floatValue = 20.5f; // Note the 'f' suffix for float
literals

// double (64-bit floating point, default type for decimals)


double doubleValue = 12345.6789;

// boolean (true or false)


boolean booleanValue = true;

// char (16-bit Unicode character, uses single quotes)


char charValue = 'A';

// Print all the values


System.out.println("byteValue: " + byteValue);
System.out.println("shortValue: " + shortValue);
System.out.println("intValue: " + intValue);
System.out.println("longValue: " + longValue);
System.out.println("floatValue: " + floatValue);
System.out.println("doubleValue: " + doubleValue);
System.out.println("booleanValue: " + booleanValue);
System.out.println("charValue: " + charValue);
}
}

Output:

Non-Primitive Data Types:


1. Array
2. Class
3. Interfaces
4. String
5. Enum
Array:
• An array holds elements of the same type.
• The array name (used for declaration) is a reference value that carries the
base address of the continuous location of elements.
Array Declaration:
// both are valid declarations
int a [];
int[] a;
// allocating memory to array
a = new int[5];
// combining both statements in one
int a []= new int[5];

Storing values into array:


For array with initialization:
Example: a[0]=3;
a[1]=5;
Initialization along with value allocation:
Int a[]= {1,2,3,4,5};

Accessing elements of array:


//length is the property of array
//Using For loop
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
//Using for-each loop
for (int i : a)
System.out.println(i);
Class:
• A class is a user-defined data type from which objects are created.
• It describes the set of properties that are common to all objects of the same
type.
• A class gets invoked by the creation of the respective object.

Example:
public class Rectangle {

double length;
double breadth;
void calculateArea() {
double area = length * breadth;
System.out.println("area of the rectangle =" + area);
}

}
public class ClassDemo {

public static void main(String[] args) {

Rectangle rec = new Rectangle();


rec.length = 10;
rec.breadth = 20;
rec.calculateArea();

}
}

Output:
area of the rectangle =200.0

Interface:
• An interface is declared like a class (similar to class).
• The key difference is that the interface contains abstract methods by default.
They have no body.

Example:
interface printable {
void printMsg();
}

public class InterfaceDemo implements printable {


public void printMsg() {
System.out.println("HELLO");
}
public static void main(String[] args) {
// Calling interface method through class object
InterfaceDemo obj = new InterfaceDemo();
obj.printMsg();
}
}

Output:
HELLO
String:
• String data type stores a sequence or array of characters.
• String value is enclosed in double quotes.

Example:
public class StringDemo {
public static void main(String[] args) {
String s = "Java Programming";
System.out.println(s);
}
}

Output:
Java Programming

Enum:
• Enum is similar to class.
• Unlike class, enum constants are public, static and final (unchangeable-
cannot be overridden).
• Enum cannot extend other classes. But enum can implement interfaces.
• According to the Java naming conventions, we should have all constants in
capital letters. So, we have enum constants in capital letters.

Example:
class EnumExample {
//defining the enum inside the class
public enum Season {
WINTER, SPRING, SUMMER, FALL
}
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}
}
Output:
WINTER
SPRING
SUMMER
FALL

4. Demonstrate different control structures with syntax and


example.
Ans) Control Statements:
• Control statements decide the flow (order or sequence of execution of
statements) of a Java program.
• In Java, statements are parsed from top to bottom. Therefore, using the
control flow statements can interrupt a particular section of a program based
on a certain condition.
1. if Statement:
The if statement executes a block of code only if the specified condition is true.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example:
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5.");
}

2. if-else Statement:
The if-else statement allows you to execute one block of code if the condition is
true, and another block if the condition is false.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example for if-else:
int number = 3;
if (number > 5) {
System.out.println("Number is greater than 5.");
} else {
System.out.println("Number is less than or equal to 5.");
}

3. if-else-if Ladder (if-else ladder):


The if-else-if ladder is used when you want to test multiple conditions. Once a
condition is true, the corresponding block of code is executed, and the rest of the
ladder is skipped.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all conditions are false
}

Example:
int number = 15;
if (number < 0) {
System.out.println("Number is negative.");
} else if (number == 0) {
System.out.println("Number is zero.");
} else if (number > 0 && number <= 10) {
System.out.println("Number is between 1 and 10.");
} else {
System.out.println("Number is greater than 10.");
}
Switch:
• switch statement is used to execute one block of code out of many based on
the value of an expression.
• It is more readable and efficient than an if-else-if ladder when working with
multiple possible conditions of a single variable.

Syntax:
switch (expression) {
case value1:
// code block for value1
break; // optional
case value2:
// code block for value2
break; // optional
// you can have as many cases as needed
default:
// code block if none of the cases match
}
Example:
public class SwitchDemo {
public static void main(String args[]) {
int day = 3;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid day");
}
}
}

Output:
Tuesday
Loop or Iterative Statements:
• For
• For-each
• While
• Do-while

1. for Loop:
The for loop is used when you know in advance how many times you want to
execute a statement or block of statements.
It consists of three parts: initialization, condition, and increment/decrement.

Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
2. for-each Loop (Enhanced for Loop):
• The for-each loop is used to iterate over arrays or collections such as
ArrayList.
• It is simpler and more readable when you don't need to work with the
index of elements.

Syntax:
for (dataType variable : array/collection) {
// code to be executed
}
Example:
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println("Number: " + num);
}

3. while Loop:
The while loop is used when you want to execute a block of code repeatedly as
long as a given condition is true. The condition is checked before the loop's body
is executed.
Syntax:
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
4. do-while Loop:
The do-while loop is similar to the while loop, but it guarantees that the loop's body
is executed at least once because the condition is checked after the loop's body.

Syntax:
do {
// code to be executed
} while (condition);

Example:
int i = 0;
do {
System.out.println("i = " + i);
i++;
} while (i < 5);

5. List and explain various forms of Inheritance.


Ans) Inheritance in Java
Inheritance is one of the fundamental concepts of Object-Oriented Programming
(OOP) that allows a class (child or subclass) to inherit fields and methods from
another class (parent or superclass). It enables code reusability, method overriding,
and polymorphism.
Key Points:
The subclass inherits all non-private members (fields and methods) of the
superclass.
Subclasses can add new fields and methods, or override methods of the superclass.
Java uses the `extends` keyword to establish an inheritance relationship.

Types of Inheritance in Java:


Output:
This animal eats food
The dog barks

2. Multilevel Inheritance: A class inherits from a subclass, creating a chain.


Output:
This animal eats food.
Mammals walk on land.
The dog barks.

3. Hierarchical Inheritance: Multiple classes inherit from the same superclass


4. Hybrid Inheritance: This is a mix of multiple and other types of inheritance,
but Java does not support multiple inheritance directly (where one class has more
than one parent class) to avoid ambiguity. However, multiple inheritance can be
achieved using interfaces.

6. Explain Polymorphism and its types.


Polymorphism in Java
Polymorphism in Java is the ability of an object to take on many forms. It allows a
single action to behave differently based on the object that it is acting upon.
There are two types of polymorphism in Java:
1. Compile-time polymorphism (Method Overloading): This occurs when multiple
methods in the same class share the same name but differ in parameters (number,
type, or order of parameters).
2. Run-time polymorphism (Method Overriding): This happens when a method in
a subclass has the same signature as a method in its superclass, allowing the
subclass to provide its specific implementation.
Compile-time Polymorphism (Method Overloading)
In method overloading, the same method name is used for different parameter
types or numbers of parameters.

Example

Output:
5
9
6.0
Run-time Polymorphism (Method Overriding)
Method overriding allows a subclass to provide a specific implementation of a
method that is already defined in its superclass. It occurs when a subclass has a
method with the same signature as a method in the superclass.
Example:

Output:
This is a generic animal sound.
The dog barks.
The cat meows.
7. Explain type casting with examples.

Ans) Typecasting in Java is the process of converting a variable from one data type
to another. There are two types of typecasting:

1. Implicit Typecasting (Widening Conversion): This occurs when a smaller


data type is converted to a larger data type. It happens automatically without
explicit instruction from the programmer.
2. Explicit Typecasting (Narrowing Conversion): This occurs when a larger
data type is converted to a smaller data type. This requires explicit casting
because it may lead to data loss.

Example:

public class TypeCastingExample {


public static void main(String[] args) {
// Implicit Typecasting
int num = 10;
double d = num; // int to double
System.out.println("Implicit Typecasting: " + d); // Outputs: 10.0

// Explicit Typecasting
double pi = 3.14;
int intPi = (int) pi; // double to int
System.out.println("Explicit Typecasting: " + intPi); // Outputs: 3
}
}
• In the above implicit typecasting, an int is automatically converted to a double,
which is safe because a double can hold larger values.
• In the above explicit typecasting, a double is explicitly cast to an int, which
might lead to data loss (the decimal part is discarded).
8.Explain the use of setter and getter method.

Ans) In Java, setter and getter methods are used to control access to the private
fields of a class. These methods allow you to access and modify private variables
in a controlled manner, adhering to the principles of encapsulation.

• Getter Methods: These methods are used to retrieve or access the value of a
private field.
• Setter Methods: These methods are used to modify or update the value of a
private field.

By using these methods, you can:

1. Control the values assigned to fields (e.g., by adding validation in the setter).
2. Hide the internal representation of the class's data.

Example:

public class Person {


// Private field
private String name;
private int age;

// Getter for name


public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}

// Setter for age with validation


public void setAge(int age) {
if (age > 0) { // Adding validation
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
}

public class Main {


public static void main(String[] args) {
// Create an object of Person
Person person = new Person();

// Set values using setter methods


person.setName("John");
person.setAge(25);
// Get values using getter methods
System.out.println("Name: " + person.getName()); // Outputs: John
System.out.println("Age: " + person.getAge()); // Outputs: 25

// Attempt to set invalid age


person.setAge(-5); // Outputs: Age must be positive.
}
}

9. Differentiate this and this ().

Ans) In Java, this and this() serve different purposes, and they are used in distinct
contexts:

1. this keyword

• Purpose: Refers to the current object instance of a class.


• Use Case: It is used to differentiate between instance variables and method
parameters or to refer to the current object inside a method or constructor.

Example:
public class Person {
private String name;

// Constructor with a parameter


public Person(String name) {
this.name = name; // 'this' refers to the instance variable 'name'
}
public void display() {
System.out.println("Name: " + this.name); // 'this' refers to the current
object's name
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person("John");
person.display(); // Outputs: Name: John
}
}
2. this() Constructor Call

• Purpose: Calls another constructor of the same class.


• Use Case: It is used to call one constructor from another, helping to avoid
duplication of code.

Example:
public class Person {
private String name;
private int age;

// Constructor with no parameters


public Person() {
this("Unknown", 0); // Calls the constructor with two parameters
}
// Constructor with two parameters
public Person(String name, int age) {
this.name = name;
this.age = age;
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Person person1 = new Person(); // Calls the no-arg constructor
Person person2 = new Person("Alice", 30); // Calls the constructor with
parameters

person1.display(); // Outputs: Name: Unknown, Age: 0


person2.display(); // Outputs: Name: Alice, Age: 30
}
}
10. Define Abstraction and Encapsulation.

Ans) Definition: Abstraction is the concept of hiding the implementation details


and showing only the essential features of an object. In Java, abstraction is
achieved through abstract classes and interfaces.

• Key Purpose: Focus on "what" an object does rather than "how" it does it.
• Achieved By:
o Abstract Classes: Classes that cannot be instantiated and may have
abstract methods (methods without implementation).
o Interfaces: Define methods that must be implemented by any class
that implements the interface.

Example:
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
public abstract void sound();

// Concrete method (implementation provided)


public void sleep() {
System.out.println("Animal is sleeping");
}
}

// Subclass provides implementation of abstract method


class Dog extends Animal {
public void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal dog = new Dog(); // Can't instantiate Animal directly
dog.sound(); // Outputs: Dog barks
dog.sleep(); // Outputs: Animal is sleeping
}
}
2. Encapsulation

Definition: Encapsulation is the practice of wrapping data (variables) and code


(methods) together into a single unit (class), and restricting access to some of the
object's components by using access modifiers (like private, public, protected).

• Key Purpose: Control access to the internal state of the object to protect its
integrity and hide its implementation details from the outside world.
• Achieved By:
o Declaring fields as private and providing public getter and setter
methods to access or modify the fields.

Example:
public class Person {
// Private fields
private String name;
private int age;

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for age


public int getAge() {
return age;
}
// Setter method for age with validation
public void setAge(int age) {
if (age > 0) {
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(30);

System.out.println("Name: " + person.getName()); // Outputs: John


System.out.println("Age: " + person.getAge()); // Outputs: 30
}
}
UNIT-2
11. Differentiate Error and Exception with examples.

Ans) 1. Error:
Definition:
Errors represent serious problems that are generally not meant to be caught or
handled by a program. These are problems that occur in the runtime environment
itself, and typically, the application cannot recover from them.

Examples of Errors:
`OutOfMemoryError`: Occurs when the JVM runs out of memory.
`StackOverflowError`: Happens when the stack for a thread overflows, typically
due to infinite recursion.
`VirtualMachineError`: Indicates that the Java Virtual Machine (JVM) has
encountered a problem.
Errors are usually not handled using `try-catch` blocks because they indicate
problems that are outside the control of the application (e.g., hardware or system-
level failures).
Example:
//Example of an Error (typically not handled)
public class ErrorDemo {
public static void main(String[] args) {
// This will eventually throw StackOverflowError due to
infinite recursion
main(args);
}
}
2. Exception:
Definition:
Exceptions are conditions that occur due to program errors or other unexpected
conditions that can be caught and handled within the program. Exceptions indicate
conditions that a program should be able to handle (for example, invalid input, file
not found, etc.).

Types of Exceptions:
1. Checked Exceptions (Compile time exceptions): These are exceptions that are
checked at compile-time. The programmer must handle them either by using a
`try-catch` block or by declaring them in the method signature using the
`throws` keyword.
Examples of Checked Exceptions:
`IOException`: Thrown when an input or output operation fails, such as when
trying to read from a file that doesn't exist.
`SQLException`: Thrown when a database access error occurs.
`FileNotFoundException`: Thrown when a file is not found.
`ClassNotFoundException`: Thrown when trying to load a class through
reflection, and the class cannot be located.
// Example of an Exception
public class UncheckedExceptionExample {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[10]);
// This will throw ArrayIndexOutOfBoundsException
}
}
Comparing Exception and Error:
Aspect Exception Error
Definition Represents the conditions a Represents serious system-
program should handle. level issues.
Recoverability Can often be caught and Typically, not recoverable
handled. by the program
Examples `IOException`, `OutOfMemoryError`,
`NullPointerException`, `StackOverflowError`
`ArithmeticException
Checked/Unchecked Includes both checked and Only unchecked (not meant
unchecked exceptions to be handled).

12. Explain the purpose of try-catch block with an example.


1. `try` Block:
The `try` block contains code that may throw an exception. If an exception occurs
in the `try` block, the exception is passed (thrown) to the `catch` block for handling.
Example:
package examples;
public class TryExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw
ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division
by zero is not allowed.");
}
}
}
Output:
Exception caught: Division by zero is not allowed.
2. `catch` Block:
The `catch` block catches and handles the exception thrown by the `try` block. You
can specify the type of exception to be caught. There can be multiple `catch` blocks
for different types of exceptions.
Example:
public class CatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[3];
System.out.println(arr[5]);
// This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of
bounds!");
}
}
}

Output:
Array index is out of bounds!

13. Differentiate throw & throws keywords with examples.


Ans) throw` Statement:
The `throw` statement is used to explicitly throw an exception. You can throw built-
in exceptions or custom exceptions. Once the exception is thrown, the normal flow
of execution stops, and the nearest `catch` block that matches the exception type
is executed.
Example:
public class ThrowExample {
public static void main(String[] args) {
validateAge(15);
// This will throw IllegalArgumentException
}

public static void validateAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must
be 18 or older.");
} else {
System.out.println("You are eligible to
vote.");
}
}
}

Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or
older.

5. `throws` Keyword:
The `throws` keyword is used in a method signature to declare that a method can
throw one or more exceptions. It is used for checked exceptions that the method
may not handle itself but leaves to be handled by the calling code.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ThrowsExample {


public static void main(String[] args) {
try {
readFile();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}

// The method declares that it throws


FileNotFoundException
public static void readFile() throws FileNotFoundException {
File file = new File("nonexistent.txt");
Scanner scanner = new Scanner(file);
}
}
Output:
File not found.
14. Explain the File class. Demonstrate writing content to a file using a
program.
‘File’ Class
In Java, the `File` class from the `java.io` package is used to represent and interact
with file and directory pathnames in the file system. It provides methods to create,
delete, and inspect files and directories.
Program to Write Content to a File:

We can use the FileWriter or BufferedWriter class along with the File
class to write content to a file.

Here's an example of a program that writes some text to a file using the
FileWriter class:

Example:

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

public class WriteToFileExample {

public static void main(String[] args) {

// Specify the file path

File file = new File("example.txt");

try {

// Create FileWriter object to write to the file

FileWriter writer = new FileWriter(file);


// Write content to the file

writer.write("Hello, this is an example of writing to a file in Java.\n");

writer.write("This is the second line of text.\n");

// Close the writer to release resources

writer.close();

System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

15. Explain any three RandomAccessFile Class Methods.


Ans)
Example
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {


public static void main(String[] args) {
try {
// Create a RandomAccessFile in "rw" mode
(read and write)
RandomAccessFile file = new
RandomAccessFile("example.txt", "rw");
// Write some data to the file
file.writeUTF("Hello, RandomAccessFile!");
// Move the file pointer to the beginning
file.seek(0);
// Read the data from the file
String message = file.readUTF();
System.out.println("Read from file: " +
message);
// Move the file pointer to a specific
position
file.seek(6); // After "Hello, "
file.writeUTF("Java!");
// Move back to the beginning to read the
updated content
file.seek(0);
String updatedMessage = file.readUTF();
System.out.println("Updated message: " +
updatedMessage);
// Close the file
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

UNIT-3
16.Define a Package? What is its use in java?
Package
A package in Java is used to group related classes and interfaces, providing
modularity and reusability. Packages also help avoid name conflicts by categorizing
classes into namespaces.
Example:
//Define a package
package examples;

public class MyClass {


public void display() {
System.out.println("This is MyClass inside the
'mypackage' package.");
}
}
Output:
This is MyClass inside the 'mypackage' package.

17. Explain Formatter and Scanner classes in detail.


Formatter:
It is part of util package. it is used to format strings, numbers, others.
Example:
package mypackage;
import java.util.Formatter;

public class FormatterClassDemo {


public static void main(String[] args) {
Formatter formatObj = new Formatter();
String name = "David";
int age = 30;
float height = 5.4f;
System.out.println(formatObj.format("hey %s ! Your
height is %.1f and age is %d", name, height, age));
}
}

Output:
hey David ! Your height is 5.4 and age is 30
Scanner class:
Scanner allows you to take the input from the user when we run the java
program. Scanner allows us to handle different types of data as input in Java.
Example:
import java.util.Scanner;

public class ScannerClassDemo {


public static void main(String args[]) {
// Initializing Scanner class object
Scanner sc = new Scanner(System.in);

// Taking String as input


System.out.println("Enter your name: ");
String name = sc.nextLine();

// Taking character as input


System.out.println("Enter your surname initial: ");
char surNameInitial = sc.next().charAt(0);

// Taking integer as input


System.out.println("Enter your age: ");
int age = sc.nextInt();

// Taking float as input


System.out.println("Enter your height: ");
float height = sc.nextFloat();
System.out.println("Hello " + surNameInitial + "."
+ name);
System.out.println("Your age is " + age + " and
height is " + height);

}
}
18. Define CLASSPATH. What is its purpose?
CLASSPATH
CLASSPATH is an environment variable that tells the Java Virtual Machine (JVM)
where to look for user defined classes and packages. It's the path where Java
should search for compiled bytecode (i.e., .class files).
You can set it using: Command line:
`set CLASSPATH=path_to_directory`
Programmatically within Java:
System.out.println(System.getProperty("java.class.path"));

19. Explain StringTokenizer Class in detail.


StringTokenizer
`StringTokenizer` is used to break a string into tokens (parts). It's part of `java.util`
and is helpful when you need to split a string based on delimiters.
Example:
import java.util.StringTokenizer;

public class TokenizerExample {


public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Java is
fun", " ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:
Java
is
fun

20. Explain the use of Random Class with example.


Random:

In Java, the `Random` class is part of the `java.util` package and is used to generate
random numbers of different types (int, long, double, etc.). Here’s a breakdown of the
constructors and common methods you mentioned, along with simple examples.

Example
import java.util.Random;
public class RandomExample1 {
public static void main(String[] args) {
Random random = new Random(); // Uses current time as seed
int randomInt = random.nextInt();
System.out.println("Random integer: " + randomInt);
}
}
Output:

Random integer: 879985397

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy