BCA 3rd Semester Examination 2024
JAVA PROGRAMMING — Code: 303303
COMPLETE DETAILED SOLUTIONS — ALL QUESTIONS
Time: 3 Hours Full Marks: 60 Questions: 7 (Attempt 5)
Q1 (Compulsory): 6×2=12 Q2 (Compulsory): 3×4=12 Q3–Q7 (choose 3): 3×12=36
QUESTION 1 — Short Answers (Any 6) [2×6 = 12 Marks]
Q1(a) What is World Wide Web?
Answer:
The World Wide Web (WWW) is a global system of interlinked hypertext documents and multimedia content
accessed over the Internet using web browsers. It was invented by Tim Berners-Lee in 1989.
Key Points:
• Uses HTTP/HTTPS protocol for data transfer between web servers and browsers
• Web pages are written using HTML (HyperText Markup Language)
• Resources are identified by URLs (Uniform Resource Locators)
• The Web is a SERVICE that runs ON the Internet (not the same as Internet)
• Supports text, images, audio, video, and interactive applications
Key Difference: The Internet is the global network infrastructure. The WWW is one service that
runs over the Internet, along with email, FTP, etc.
Q1(b) Which keyword is used to define a class in Java?
Answer:
The keyword 'class' is used to define a class in Java.
Syntax and Example:
class ClassName {
// data members (variables)
dataType variableName;
// member methods
returnType methodName(parameters) { ... }
}
// Practical example:
class Student {
String name;
int rollNo;
void display() {
[Link]("Name: " + name + ", Roll: " + rollNo);
}
}
Related Class Keywords:
• 'extends' — for inheritance: class Dog extends Animal
• 'abstract' — for abstract class: abstract class Shape
• 'final' — prevents subclassing: final class String
• 'public' — access modifier with class
Q1(c) What is the data type for single character in Java?
Answer:
The data type for a single character in Java is 'char'.
Properties of char:
• Size: 2 bytes (16 bits) — unlike C/C++ which uses 1 byte
• Range: 0 to 65,535 (unsigned Unicode values)
• Java uses Unicode (UTF-16) — supports international characters
• Char literals are enclosed in single quotes: 'A', '9', '$'
char letter = 'A';
char digit = '9';
char symbol = '$';
char unicode = '\u0041'; // Unicode for 'A'
// Arithmetic on char:
char c = 'A';
[Link]((int) c); // 65 (Unicode/ASCII value)
[Link]((char)(c+1)); // B
Q1(d) Which operator is used for assignment in Java?
Answer:
The '=' (equals sign) is the basic assignment operator in Java. It assigns the value on the right side to the
variable on the left side.
Assignment Operators in Java:
Operator Example Equivalent To
= x=5 x=5
+= x += 3 x=x+3
-= x -= 2 x=x-2
*= x *= 4 x=x*4
/= x /= 2 x=x/2
%= x %= 3 x=x%3
Important: Do NOT confuse '=' (assignment) with '==' (equality comparison). x = 5 assigns; x == 5
checks equality.
Q1(e) What does JVM stand for?
Answer:
JVM stands for Java Virtual Machine.
What is JVM?
The Java Virtual Machine is an abstract computing engine that provides the runtime environment in which
Java bytecode (.class files) is executed. It sits between the compiled Java program and the hardware.
Key Functions of JVM:
• Class Loading: Loads .class files into memory
• Bytecode Verification: Checks for security violations
• Execution: Interprets bytecode or compiles it via JIT compiler
• Memory Management: Manages Heap, Stack; performs Garbage Collection
• Platform Independence: Same bytecode runs on Windows, Linux, Mac
Java Source (.java) →[javac]→ Bytecode (.class) →[JVM]→ Output
Q1(f) What is 'do' statement?
Answer:
The 'do' statement (do-while loop) is a control flow construct that executes a block of code at least ONCE,
then repeats while the condition is true. The condition is checked AFTER the body.
Syntax:
do {
// loop body — executes at least ONCE
} while (condition); // semicolon required
Example:
int i = 1;
do {
[Link]("Count: " + i);
i++;
} while (i <= 5);
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5
Key Property: Even if the condition is false from the start, the do-while body executes ONCE. This
distinguishes it from the while loop.
Q1(g) What is the process of combining data and methods into a single unit called?
Answer:
The process of combining data (variables/fields) and methods (functions) into a single unit is called
ENCAPSULATION.
Encapsulation in Detail:
Encapsulation is one of the four fundamental OOP pillars. In Java, a 'class' is the encapsulating unit.
Restricting direct access to data using access modifiers (private) is called Data Hiding.
public class BankAccount {
private double balance; // data HIDDEN from outside
private String owner;
public void deposit(double amt) { // method controls access
if (amt > 0) balance += amt;
}
public double getBalance() { // controlled read access
return balance;
}
}
Benefits:
• Data hiding and security
• Modularity and easy maintenance
• Flexibility — implementation can change without affecting outside code
Q1(h) Which is applet?
Answer:
An applet is a special Java program designed to run inside a web browser or applet viewer. It extends
[Link] class, has no main() method, and uses lifecycle methods controlled by the browser.
Key Characteristics:
• Extends [Link] (or [Link])
• Lifecycle methods: init(), start(), paint(), stop(), destroy()
• Runs inside browser — restricted access to local system (sandbox security)
• Requires HTML <applet> tag or appletviewer to run
import [Link].*;
import [Link].*;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello from Applet!", 50, 60);
}
}
// Run: appletviewer [Link]
Q1(i) What is the superclass of all classes in Java?
Answer:
The 'Object' class ([Link]) is the superclass (root class) of ALL classes in Java. Every class directly
or indirectly inherits from Object. If a class does not explicitly extend anything, it implicitly extends Object.
Important Methods of Object Class:
Method Purpose
toString() Returns string representation of object
equals(Object obj) Checks equality of two objects
hashCode() Returns hash code of the object
getClass() Returns runtime class of the object
clone() Creates a copy of the object
finalize() Called before garbage collection
wait() / notify() Thread synchronization
Q1(j) Illustrate the concept of 'nesting of method'.
Answer:
Nesting of methods means calling one method from within another method. This allows breaking complex
tasks into smaller helper methods, each calling others.
public class NestingDemo {
// Innermost: calculates square
int square(int n) {
return n * n;
}
// Middle: calls square() — nested call
int sumOfSquares(int a, int b) {
return square(a) + square(b); // calls square() twice
}
// Outer: calls sumOfSquares() — another nested call
void display(int x, int y) {
int result = sumOfSquares(x, y);
[Link]("Sum of squares = " + result);
}
public static void main(String[] args) {
NestingDemo obj = new NestingDemo();
[Link](3, 4); // 3^2 + 4^2 = 9 + 16 = 25
}
}
// Call chain: main() → display() → sumOfSquares() → square()
// Output: Sum of squares = 25
QUESTION 2 — Medium Answers (Any 3) [4×3 = 12
Marks]
Q2(a) Explain the difference between an abstract class and an interface in Java. [4
marks]
Abstract Class:
Declared with 'abstract' keyword. Can have abstract methods (no body) AND concrete methods (with body).
Cannot be instantiated directly.
abstract class Shape {
String color;
abstract double area(); // abstract — no body
void displayColor() { // concrete — has body
[Link]("Color: " + color);
}
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; color = "Red"; }
double area() { return 3.14 * r * r; } // must implement
}
Interface:
Declared with 'interface' keyword. All methods are public abstract by default. Variables are public static final. A
class 'implements' (not extends) an interface. Multiple interfaces can be implemented.
interface Drawable {
void draw(); // public abstract by default
int MAX = 100; // public static final by default
}
interface Resizable {
void resize();
}
class Square implements Drawable, Resizable { // multiple interfaces
public void draw() { [Link]("Drawing Square"); }
public void resize() { [Link]("Resizing Square"); }
}
Comparison Table:
Abstract Class Interface
Keyword: abstract Keyword: interface
Can have abstract + concrete methods All methods abstract (Java 7)
Variables can be any type Variables: public static final only
Subclass uses 'extends' Implementing class uses 'implements'
Single inheritance only Multiple interfaces allowed
Can have constructors Cannot have constructors
For shared behavior + state For defining capability/contract
Q2(b) What is method overloading in Java? Explain its benefits with a simple
example. [4 marks]
Definition:
Method overloading means defining multiple methods in the SAME class with the SAME name but
DIFFERENT parameter lists (different number, type, or order of parameters). The correct method is selected
by the compiler at compile time — Compile-time / Static Polymorphism.
Rules:
• Same method name required
• Parameters MUST differ (number, type, or order)
• Return type alone is NOT enough to overload
Example:
class Calculator {
// 1. Two integers
int add(int a, int b) {
[Link]("int+int: ");
return a + b;
}
// 2. Two doubles
double add(double a, double b) {
[Link]("double+double: ");
return a + b;
}
// 3. Three integers
int add(int a, int b, int c) {
[Link]("int+int+int: ");
return a + b + c;
}
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](5, 3)); // int+int: 8
[Link]([Link](2.5, 1.5)); // double+double: 4.0
[Link]([Link](1, 2, 3)); // int+int+int: 6
}
}
Benefits of Method Overloading:
• Readability: One meaningful name (add) instead of add_int, add_double
• Flexibility: Same operation for different data types
• Code cleanliness: Reduces method name clutter
• Supports polymorphism: One interface, multiple implementations
Q2(c) Describe the various looping statements of Java programming. [4 marks]
1. for Loop — When number of iterations is known
// Syntax:
for (initialization; condition; update) { body }
// Example: Print 1 to 5
for (int i = 1; i <= 5; i++) {
[Link](i + " ");
} // Output: 1 2 3 4 5
2. while Loop — Entry-controlled, condition checked BEFORE body
// Syntax:
while (condition) { body }
// Example: Sum until n > 0
int n = 5, sum = 0;
while (n > 0) {
sum += n;
n--;
}
[Link]("Sum = " + sum); // Sum = 15
3. do-while Loop — Exit-controlled, condition checked AFTER body, runs at LEAST once
// Syntax:
do { body } while (condition);
// Example: Menu loop
int choice;
do {
[Link]("[Link] [Link]");
choice = new [Link]([Link]).nextInt();
} while (choice != 2);
Quick Comparison:
Feature for while do-while
Condition checked Before body Before body After body
Min executions 0 0 1
Best for Known count Unknown count Must run once
Q2(d) What are the key principles of OOP? Briefly explain how Java supports at
least two. [4 marks]
The Four Key OOP Principles:
• Encapsulation — combining data and methods; data hiding
• Abstraction — hiding complexity, showing only essentials
• Inheritance — acquiring properties/methods of another class
• Polymorphism — one name, many behaviors
Java Support — Principle 1: Encapsulation
Java achieves encapsulation through classes and private access modifiers. Fields are kept private; getter and
setter methods provide controlled access.
class Person {
private String name; // private — hidden
private int age;
public String getName() { return name; } // getter
public void setName(String n) { name = n; }// setter
public void setAge(int a) {
if (a > 0) age = a; // validation in setter
}
}
Java Support — Principle 2: Inheritance
Java supports inheritance using the 'extends' keyword. A subclass inherits all non-private fields and methods
of its superclass, enabling code reuse.
class Vehicle {
int speed = 100;
void move() { [Link]("Moving at " + speed); }
}
class Car extends Vehicle { // inherits from Vehicle
void honk() { [Link]("Beep!"); }
}
Car c = new Car();
[Link](); // inherited → Moving at 100
[Link](); // own method → Beep!
Q2(e) Explain the concept of inheritance in Java. [4 marks]
Definition:
Inheritance is the OOP mechanism by which a child class (subclass) acquires the properties (fields) and
behaviors (methods) of a parent class (superclass). It promotes code reuse and establishes an IS-A
relationship.
Syntax: class ChildClass extends ParentClass { ... }
Types of Inheritance:
• Single: class Dog extends Animal (one parent, one child)
• Multilevel: Animal → Dog → Puppy (chain)
• Hierarchical: Animal → Dog, Animal → Cat (one parent, many children)
• Multiple: NOT directly supported in Java — use interfaces
Complete Single Inheritance Example:
class Animal {
String name;
void eat() { [Link](name + " is eating"); }
}
class Dog extends Animal { // Dog IS-A Animal
void bark() { [Link]("Woof!"); }
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link] = "Bruno";
[Link](); // inherited → Bruno is eating
[Link](); // own method → Woof!
}
}
Key Points:
• 'super' keyword accesses parent class: super() calls parent constructor
• All Java classes implicitly extend [Link]
• Java avoids multiple class inheritance to prevent diamond problem
QUESTION 3 — JVM & Simple Java Program [12 Marks]
Q3 Write a simple Java program. What is the purpose of a Java Virtual Machine
(JVM)?
Part A: Simple Java Programs
Program 1 — Hello World:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
[Link]("Welcome to Java Programming!");
}
}
// Compile: javac [Link]
// Run: java HelloWorld
// Output: Hello, World!
// Welcome to Java Programming!
Program 2 — Complete Demo (variables, loop, method):
public class JavaDemo {
static int add(int a, int b) { return a + b; }
public static void main(String[] args) {
String name = "Java";
int version = 17;
double pi = 3.14159;
boolean isPopular = true;
[Link]("Language : " + name);
[Link]("Version : " + version);
[Link]("Pi value : " + pi);
[Link]("Popular : " + isPopular);
[Link]("10 + 20 : " + add(10, 20));
[Link]("Numbers 1-5: ");
for (int i = 1; i <= 5; i++) [Link](i + " ");
}
}
// Output:
// Language : Java
// Version : 17
// Pi value : 3.14159
// Popular : true
// 10 + 20 : 30
// Numbers 1-5: 1 2 3 4 5
Part B: Purpose of Java Virtual Machine (JVM)
Definition:
The Java Virtual Machine (JVM) is an abstract computing engine that provides the runtime environment in
which Java bytecode is executed. It sits between the compiled Java program and the hardware/OS.
Core Purposes / Functions of JVM:
1. Platform Independence (Write Once, Run Anywhere)
Java source is compiled to platform-neutral bytecode (.class files). The JVM on each OS runs this same
bytecode. No recompilation needed for Windows, Linux, or Mac.
.java → [javac] → .class (bytecode) → [JVM on any OS] → Program Output
2. Bytecode Execution
• Interpreter: Reads and executes bytecode line by line
• JIT (Just-In-Time) Compiler: Converts frequently-used bytecode to native machine code for speed
3. Automatic Memory Management & Garbage Collection
JVM allocates memory for objects on the Heap and automatically frees memory for unreferenced objects
through Garbage Collection — no manual memory management needed.
4. Security — Bytecode Verification
Before executing, the Bytecode Verifier checks code for type mismatches, illegal memory access, and stack
overflows. Prevents malicious code from harming the system.
5. Class Loading
The Class Loader loads .class files into memory dynamically as needed. It handles Bootstrap, Extension, and
Application class loaders.
JVM Architecture:
┌──────────────────────────────────────────────┐
│ JVM │
│ ┌─────────────────────────────────────┐ │
│ │ Class Loader Subsystem │ │
│ │ (Load → Verify → Prepare → Init) │ │
│ └────────────────┬────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────┐ │
│ │ Runtime Data Areas │ │
│ │ Heap | Stack | Method Area | PC │ │
│ └────────────────┬────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────┐ │
│ │ Execution Engine │ │
│ │ Interpreter + JIT Compiler + GC │ │
│ └─────────────────────────────────────┘ │
└──────────────────────────────────────────────┘
Summary: JVM = Platform independence + Bytecode execution + Automatic memory management
+ Security. Without JVM, no Java program can run.
QUESTION 4 — Class and Object [12 Marks]
Q4 What are class and object in Java? How is class related to an object? How is an
object created from a class?
4.1 What is a Class?
A class is a user-defined blueprint or template that defines the structure (data/fields) and behavior (methods)
that all objects of that class will have. A class itself does not store data — it only defines what data and
operations its objects will have.
A Class Contains:
• Data Members (Fields): Variables holding the state (e.g., name, age)
• Member Methods: Define behaviors/operations (e.g., display(), calculate())
• Constructors: Special methods to initialize objects when created
• Access Modifiers: Control visibility (public, private, protected)
Class Syntax:
class ClassName {
// Data members
dataType fieldName;
// Constructor
ClassName(parameters) { /* initialization */ }
// Methods
returnType methodName(parameters) { /* body */ }
}
Comprehensive Class Example:
class Student {
// Data members
String name;
int rollNo;
double marks;
// Constructor
Student(String n, int r, double m) {
name = n; rollNo = r; marks = m;
}
// Methods
void display() {
[Link]("Name: " + name + " | Roll: " + rollNo
+ " | Marks: " + marks);
}
char getGrade() {
if (marks >= 90) return 'A';
else if (marks >= 75) return 'B';
else if (marks >= 60) return 'C';
else return 'D';
}
}
4.2 What is an Object?
An object is a specific real-world instance of a class — it occupies actual memory and contains real values for
the fields defined in the class.
An Object Has Three Properties:
• State: Current values in its fields (name="Ravi", rollNo=101, marks=85.5)
• Behavior: What it can do — the methods it can call (display(), getGrade())
• Identity: A unique reference/address in memory that distinguishes it from other objects
4.3 Relationship Between Class and Object
CLASS OBJECT
Blueprint / Template Real entity / Instance of class
Logical entity — no memory for data Physical entity — occupies Heap memory
Defined ONCE in code Multiple objects can be created
Like a cookie cutter Like the actual cookie
Example: class Student { ... } Example: Student s1 = new Student(...)
4.4 How is an Object Created from a Class?
Objects are created using the 'new' keyword. Creation involves 3 steps:
Step 1 — Declaration: Declare a reference variable of the class type.
Student s1; // s1 is a reference variable, currently null
Step 2 — Instantiation: 'new' allocates memory on the Heap for the object.
s1 = new Student("Ravi", 101, 85.5);
// 'new' allocates memory, calls constructor, returns reference address
Step 3 — Initialization: Constructor initializes the object's fields with given values.
Combined (most common — all 3 steps at once):
Student s1 = new Student("Ravi", 101, 85.5);
Complete Program — Multiple Objects from Same Class:
public class StudentTest {
public static void main(String[] args) {
// Three objects from the SAME Student class
Student s1 = new Student("Ravi", 101, 85.5);
Student s2 = new Student("Priya", 102, 92.0);
Student s3 = new Student("Amit", 103, 67.5);
[Link](); [Link]("Grade: " + [Link]());
[Link](); [Link]("Grade: " + [Link]());
[Link](); [Link]("Grade: " + [Link]());
}
}
// Output:
// Name: Ravi | Roll: 101 | Marks: 85.5 Grade: B
// Name: Priya | Roll: 102 | Marks: 92.0 Grade: A
// Name: Amit | Roll: 103 | Marks: 67.5 Grade: C
Memory Note: Each object (s1, s2, s3) has its OWN copy of name, rollNo, marks in Heap memory.
All three share the same method code stored once in the Method Area.
QUESTION 5 — Applet Life Cycle [12 Marks]
Q5 How do applets differ from applications? Describe applet life cycle.
5.1 Applet vs Java Application — Differences
Applet Java Application
Runs inside browser / applet viewer Runs as standalone program via JVM
No main() method Execution starts from main()
Uses 5 lifecycle methods No lifecycle — sequential top-bottom execution
Extends Applet / JApplet class No mandatory parent class
Needs HTML <applet> tag to run Run directly: java ClassName
Cannot access local file system Full access to local file system
Primarily GUI-based Can be console or GUI
Browser controls start/stop User/OS controls execution
Compiled: javac; Run: appletviewer Compiled: javac; Run: java
5.2 What is an Applet?
An applet is a Java program embedded in a web page that runs inside a browser or applet viewer. It extends
[Link] and does not have a main() method. Instead, the browser calls specific lifecycle methods
automatically.
5.3 The Five Applet Lifecycle Methods
(1) init() — Initialization (called ONCE)
Called the first and only time when the applet is loaded into memory. Used for one-time setup: initializing
variables, setting background, reading parameters, creating components. Equivalent to a constructor.
public void init() {
setBackground([Link]);
[Link]("1. init() called — applet loaded");
}
(2) start() — Start/Resume (called after init and each time visible)
Called after init() and every time the user returns to the page. Used to start/resume threads, animations, or
any ongoing processing.
public void start() {
[Link]("2. start() called — applet started/resumed");
}
(3) paint(Graphics g) — Rendering (called to draw the screen)
Called after start() and whenever the applet area needs redrawing (resize, minimize/restore, repaint() call).
The Graphics object provides drawing methods.
public void paint(Graphics g) {
[Link]([Link]);
[Link](new Font("Arial", [Link], 18));
[Link]("Hello Applet!", 50, 80);
[Link](10, 10, 280, 180);
[Link]([Link]);
[Link](90, 40, 100, 100);
}
(4) stop() — Pause (called when applet becomes invisible)
Called when the user navigates away from the page, minimizes the browser, or switches tabs. Used to pause
threads and resource-intensive work to save CPU.
public void stop() {
[Link]("4. stop() called — applet paused");
}
(5) destroy() — Cleanup (called ONCE, before removal from memory)
Called when the applet is permanently removed — browser is closed or page is unloaded. Used for final
cleanup: stopping threads, closing files, releasing resources.
public void destroy() {
[Link]("5. destroy() called — applet removed");
}
5.4 Applet Life Cycle Diagram
[Browser loads applet]
↓
init() ← called ONCE at start
↓
start() ←──────────────────────────┐
↓ │
paint(g) │
↓ │
[User navigates away from page] │
↓ │
stop() │
├── [User returns] ────────────┘
│
└── [Browser closed / page removed]
↓
destroy() ← called ONCE at end
5.5 Complete Applet Program
import [Link].*;
import [Link].*;
/*
* <applet code="[Link]" width=400 height=300>
* </applet>
*/
public class LifeCycleDemo extends Applet {
String message = "";
public void init() {
message = "Applet Initialized!";
setBackground([Link]);
[Link]("init() called");
}
public void start() {
message = "Applet is Running!";
repaint();
[Link]("start() called");
}
public void paint(Graphics g) {
[Link](new Font("Arial", [Link], 20));
[Link]([Link]);
[Link](message, 50, 100);
[Link]([Link]);
[Link]("BCA 3rd Semester Java", 50, 140);
[Link](10, 10, 375, 275);
}
public void stop() { [Link]("stop() called"); }
public void destroy() { [Link]("destroy() called"); }
}
// Compile: javac [Link]
// Run: appletviewer [Link]
QUESTION 6 — Byte Streams vs Character Streams [12
Marks]
Q6 Explain the fundamental difference between byte streams and character
streams. When to use which? Provide an example of each.
6.1 Introduction to Java I/O Streams
A stream is an ordered sequence of data flowing between a program and an I/O device (file, network,
keyboard). Java's [Link] package divides streams into two categories based on data type:
• Byte Streams — process raw binary data, 8 bits at a time
• Character Streams — process text data, 16-bit Unicode characters at a time
6.2 Stream Class Hierarchy
[Link] Package
├── BYTE STREAMS (8-bit binary)
│ ├── InputStream (abstract — for reading)
│ │ ├── FileInputStream reads raw bytes from a file
│ │ ├── BufferedInputStream wraps stream for buffered reading
│ │ ├── DataInputStream reads Java primitives (int, double...)
│ │ └── ObjectInputStream reads serialized objects
│ └── OutputStream (abstract — for writing)
│ ├── FileOutputStream writes raw bytes to a file
│ ├── BufferedOutputStream wraps stream for buffered writing
│ ├── DataOutputStream writes Java primitives
│ └── ObjectOutputStream writes serialized objects
│
└── CHARACTER STREAMS (16-bit Unicode text)
├── Reader (abstract — for reading)
│ ├── FileReader reads characters from file
│ ├── BufferedReader adds line-reading (readLine())
│ └── InputStreamReader bridges bytes → characters
└── Writer (abstract — for writing)
├── FileWriter writes characters to file
├── BufferedWriter adds buffered writing
└── OutputStreamWriter bridges characters → bytes
6.3 Byte Streams — Detailed Explanation
Byte streams are the lowest level of Java I/O. They handle data as raw bytes (8-bit unsigned integers). They
have no knowledge of character encoding and are therefore suitable for any type of file — binary or text.
Example — FileInputStream and FileOutputStream:
import [Link].*;
public class ByteStreamDemo {
public static void main(String[] args) {
String filename = "[Link]";
// WRITE using FileOutputStream
try {
FileOutputStream fos = new FileOutputStream(filename);
String data = "Hello, Byte Stream!";
byte[] bytes = [Link](); // convert String to byte array
[Link](bytes); // write bytes to file
[Link]();
[Link]("Bytes written: " + [Link]);
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
// READ using FileInputStream
try {
FileInputStream fis = new FileInputStream(filename);
int b;
[Link]("Data read: ");
while ((b = [Link]()) != -1) { // -1 = end of file
[Link]((char) b); // cast byte → char
}
[Link]();
[Link]();
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
// Output:
// Bytes written: 19
// Data read: Hello, Byte Stream!
6.4 Character Streams — Detailed Explanation
Character streams process data as 16-bit Unicode characters. They automatically handle character encoding
(UTF-8, UTF-16, ISO-8859-1), making them ideal for reading and writing text files that must be portable
across platforms.
Example — FileReader/FileWriter with BufferedReader:
import [Link].*;
public class CharStreamDemo {
public static void main(String[] args) {
String filename = "[Link]";
// WRITE using FileWriter
try {
FileWriter fw = new FileWriter(filename);
[Link]("Hello, Character Stream!\n");
[Link]("Line 2: Java I/O is powerful.\n");
[Link]("Unicode: \u0041 \u0042 \u0043"); // A B C
[Link]();
[Link]("File written successfully.");
} catch (IOException e) {
[Link]("Write error: " + [Link]());
}
// READ using BufferedReader (reads line by line)
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String line;
[Link]("File contents:");
while ((line = [Link]()) != null) { // null = EOF
[Link](line);
}
[Link]();
} catch (IOException e) {
[Link]("Read error: " + [Link]());
}
}
}
// Output:
// File written successfully.
// File contents:
// Hello, Character Stream!
// Line 2: Java I/O is powerful.
// Unicode: A B C
6.5 When to Use Which?
Use Byte Streams for... Use Character Streams for...
Binary files: images, audio, video, ZIP Text files: .txt, .csv, .html, .xml, .json
When exact byte-level preservation is needed When character encoding matters (UTF-8 etc.)
Object serialization (ObjectOutputStream) Reading/writing Java source or config files
Network communication at binary level When reading line by line (BufferedReader)
Unknown file format Internationalized/Unicode text handling
Copying any file bit-for-bit Log files, report generation, user input/output
6.6 Summary Comparison Table
Byte Streams Character Streams
Unit: 8-bit byte Unit: 16-bit Unicode character
Base: InputStream / OutputStream Base: Reader / Writer
No encoding — raw binary Automatic character encoding
Best for binary data Best for text data
read() returns 0–255 read() returns character value
FileInputStream, FileOutputStream FileReader, FileWriter, BufferedReader
More fundamental / lower level Built on top of byte streams
QUESTION 7 — Java Concepts [3×4 = 12 Marks]
Q7 Discuss: (a) Java Token (b) Java API Package (c) While Statement (d) Else-if
Ladder
Q7(a) Java Token [4 marks]
A token is the smallest meaningful unit in a Java program. When the compiler processes source code, it first
breaks it into tokens (lexical analysis). Java has 5 types of tokens:
1. Keywords (Reserved Words)
Words with predefined special meaning. Cannot be used as identifiers. Java has 53 keywords.
class, public, static, void, int, double, char, if, else, for, while,
do, new, return, import, extends, implements, try, catch, finally,
abstract, interface, final, this, super, true, false, null ...
2. Identifiers
Names given to variables, methods, classes, interfaces, packages by the programmer.
Rules: Start with letter / _ / $; no spaces; not a keyword; case-sensitive
Valid: myVar, _count, $price, StudentName, MAX_SIZE
Invalid: 2name (starts with digit), my-var (hyphen), class (keyword)
3. Literals
Fixed constant values directly in code.
int x = 42; // integer literal
double d = 3.14; // floating-point literal
char c = 'A'; // character literal
String s = "Hello"; // string literal
boolean b = true; // boolean literal
Object o = null; // null literal
4. Operators
Symbols performing operations on operands.
Arithmetic: + - * / %
Relational: == != > < >= <=
Logical: && || !
Assignment: = += -= *= /=
Unary: ++ -- (unary+) (unary-)
Bitwise: & | ^ ~ << >>
Ternary: ?:
5. Separators / Punctuators
Symbols that structure/separate code elements.
( ) — method calls, parameters, grouping expressions
{ } — class body, method body, block statements
[ ] — array declaration and element access
; — statement terminator
, — parameter/variable list separator
. — member access ([Link])
Example: In 'int sum = a + b;' the tokens are: 'int' (keyword), 'sum' (identifier), '=' (operator), 'a'
(identifier), '+' (operator), 'b' (identifier), ';' (separator)
Q7(b) Java API Package [4 marks]
The Java API (Application Programming Interface) is a large collection of pre-written, ready-to-use classes
and interfaces organized into packages. These come built-in with the Java Development Kit (JDK) and save
programmers from writing common functionality from scratch.
What is a Package?
A package is a named folder/namespace that groups related classes and interfaces. It avoids name conflicts
and provides access control. The 'import' keyword makes package classes available in your code.
import [Link]; // import specific class
import [Link].*; // import all classes from [Link]
Important Java API Packages:
Package Key Classes / Purpose
[Link] Auto-imported. String, Math, Object, System, Integer, Thread, Exception
[Link] Scanner, ArrayList, LinkedList, HashMap, Arrays, Date, Random, Stack
[Link] FileInputStream, FileReader, BufferedReader, FileWriter — File I/O
[Link] BigInteger, BigDecimal — arbitrary precision arithmetic
[Link] URL, Socket, InetAddress — networking classes
[Link] Button, Frame, Graphics, Color — Abstract Window Toolkit (GUI)
[Link] JFrame, JButton, JLabel, JTextField — modern Swing GUI
[Link] Applet class — creating web applets
Example — Using Multiple Packages:
import [Link];
import [Link];
public class PackageDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<String> langs = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]("Languages: " + langs);
// [Link] — available without import
[Link]("sqrt(144) = " + [Link](144)); // 12.0
[Link]("pow(2,10) = " + [Link](2,10)); // 1024.0
}
}
Creating a User-defined Package:
// File: mypack/[Link]
package mypack;
public class Hello {
public void greet() {
[Link]("Hello from mypack!");
}
}
// [Link]
import [Link];
public class Main {
public static void main(String[] args) {
Hello h = new Hello();
[Link](); // Hello from mypack!
}
}
Q7(c) While Statement [4 marks]
The while statement is an entry-controlled loop that executes a block of code repeatedly as long as the given
boolean condition is true. The condition is evaluated BEFORE each iteration — if the condition is false initially,
the body never executes.
Syntax:
while (condition) {
// loop body
// update statement (prevent infinite loop)
}
Working:
Step 1: Evaluate condition
Step 2: TRUE → execute body → go to Step 1
FALSE → exit loop → continue program
Example 1 — Print 1 to 10:
int i = 1;
while (i <= 10) {
[Link](i + " ");
i++;
}
// Output: 1 2 3 4 5 6 7 8 9 10
Example 2 — Sum of digits:
int num = 12345, sum = 0, temp = num;
while (temp != 0) {
sum += temp % 10; // add last digit
temp /= 10; // remove last digit
}
[Link]("Sum of digits of " + num + " = " + sum);
// Output: Sum of digits of 12345 = 15
Example 3 — Reverse a number:
int n = 4321, rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
[Link]("Reverse = " + rev); // Reverse = 1234
Important Notes:
• Always include update statement to avoid infinite loops
• while is also called 'entry-controlled' loop
• If condition is false initially, body executes 0 times
Q7(d) Else-if Ladder [4 marks]
The else-if ladder is a multi-branch decision-making construct that tests multiple conditions in sequence. Once
a true condition is found, its block executes and ALL remaining conditions are skipped. The final 'else' acts as
a default.
Syntax:
if (condition1) {
// executes when condition1 is TRUE
} else if (condition2) {
// executes when condition2 is TRUE (and condition1 is FALSE)
} else if (condition3) {
// executes when condition3 is TRUE (and 1,2 are FALSE)
}
// ... any number of else-if blocks ...
else {
// executes when ALL conditions above are FALSE (default)
}
Flow:
condition1 TRUE? → execute block1 → DONE
FALSE → condition2 TRUE? → execute block2 → DONE
FALSE → condition3 TRUE? → ...
all FALSE → execute else
Example 1 — Grade System:
public class GradeSystem {
public static void main(String[] args) {
int marks = 78;
if (marks >= 90) {
[Link]("Grade: A — Excellent");
} else if (marks >= 75) {
[Link]("Grade: B — Very Good");
} else if (marks >= 60) {
[Link]("Grade: C — Good");
} else if (marks >= 45) {
[Link]("Grade: D — Pass");
} else {
[Link]("Grade: F — Fail");
}
}
}
// Output: Grade: B — Very Good (78 >= 75 is first true condition)
Example 2 — Positive, Negative, or Zero:
int num = -5;
if (num > 0) {
[Link](num + " is Positive");
} else if (num < 0) {
[Link](num + " is Negative");
} else {
[Link]("Number is Zero");
}
// Output: -5 is Negative
Key Properties:
• Conditions tested TOP to BOTTOM — order matters!
• Only ONE block executes — the first condition that is true
• The else block at the end is optional but acts as the default case
• Can have unlimited else-if blocks
else-if vs switch: Use else-if for range conditions (marks >= 90) or non-integer comparisons. Use
switch for exact integer/char value matching — it is faster and cleaner.
All the Best for Your BCA Java Programming Exam 2024!
Complete solutions to ALL questions — Q1(a-j), Q2(a-e), Q3, Q4, Q5, Q6, Q7(a-d)