Java Programming 2079
Java Programming 2079
// Validate input
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = 1; // Use long to handle larger factorials
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
scanner.close();
}
}
Sample Output:
Enter a non-negative integer to calculate its factorial: 5
Factorial of 5 is: 120
Alternative Using while Loop:
import java.util.Scanner;
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = 1;
int i = 1;
while (i <= number) {
factorial *= i;
i++;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
scanner.close();
}
}
OR: Discuss the concept of static data members and static methods with example.
Static Data Members and Static Methods: The document does not explicitly cover static
members and methods in detail, but it mentions that static fields are not serialized because they
belong to the class, not an instance. Based on this and standard Java concepts, here is a
comprehensive explanation:
Static Data Members:
o Declared with the static keyword, these belong to the class rather than any
specific object.
o Shared across all instances of the class, meaning all objects access the same copy
of the static variable.
o Commonly used for constants or shared resources, such as counters or
configuration settings.
o Example: A static variable to track the number of objects created for a class.
Static Methods:
o Also declared with the static keyword, these belong to the class and can be called
without creating an instance.
o Cannot access non-static (instance) variables or methods directly, as they are not
tied to an object.
o Often used for utility functions or operations that don’t require object-specific
data.
o Example: The main method in Java is static, allowing it to be called without
instantiating the class.
Example Program:
public class Student {
// Static data member
static int studentCount = 0;
// Instance variables
int id;
String name;
// Constructor
public Student(int id, String name) {
this.id = id;
this.name = name;
studentCount++; // Increment static counter when a new student is created
}
// Static method
public static int getStudentCount() {
return studentCount;
}
// Instance method
public void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
// Interface 2
interface Displayable {
void display();
}
// Subclass
class Dog extends Animal {
public Dog(String name) {
super(name); // Call superclass constructor
}
// Overriding method
@Override
public void eat() {
System.out.println(name + " is eating bones.");
}
// Additional method
public void bark() {
System.out.println(name + " is barking.");
}
}
// Writing to a file
writer = new FileWriter("MyFile.txt", true); // Append mode
writer.write("Hello World\n");
writer.write("Good Bye!\n");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
System.out.println("Error closing resources: " + e.getMessage());
}
}
}
}
Reading file contents:
[Existing content of MyFile.txt]
After execution, the file will append:
Hello World
Good Bye!
If an error occurs (e.g., file not found), the output might be:
An error occurred: MyFile.txt (No such file or directory)
[Stack trace]
5. What are byte stream classes? Explain the classes with example.
Byte Stream Classes in Java: Byte stream classes in Java handle input and output of data in the
form of bytes (8-bit units), suitable for processing raw data like binary files, images, or non-text
data. Byte streams as part of the java.io package, emphasizing their role in reading from and
writing to sources like files. Key byte stream classes include:
FileInputStream: Reads bytes from a file.
FileOutputStream: Writes bytes to a file.
BufferedInputStream: Buffers input to reduce direct access to the underlying source,
improving performance.
BufferedOutputStream: Buffers output to reduce direct writes, enhancing efficiency.
When to Use Byte Streams: Byte streams are ideal for handling raw data, such as binary files
(e.g., images, audio, or executables), where character encoding is not required. The document
contrasts byte streams with character streams, noting that byte streams process data byte by byte,
while character streams handle Unicode characters.
Example:
java.io.*;
Result: 50