ROLL NUMBER 2xxxxxxxxx
MASTER OF COMPUTER APPLICATION
PROGRAM
(MCA)
SEMESTER 2
FULL NAME NXXXXX X
COURSE CODE DCA6207
ASSIGNMENT SET – I
Answer 01:
Java is a powerful and flexible programming language that is widely used across various
platforms and industries. It follows the object-oriented programming model and provides a
wide range of features that make it suitable for developing everything from simple desktop
programs to large-scale enterprise applications.
One of the most useful features of Java is its simplicity. Its syntax is similar to C++, so anyone
with prior programming knowledge can pick it up easily. However, Java removes complex
features like pointers, operator overloading, and manual memory management, which are
present in languages like C/C++. This makes Java code easier to write, read, and debug.
Java is fully object-oriented, which means everything in Java is treated as an object. This
includes important concepts like encapsulation, inheritance, abstraction, and polymorphism.
For example, encapsulation hides the internal details of objects and only exposes necessary
parts to the user, making the code more secure and manageable. Inheritance allows new classes
to reuse code from existing ones, and polymorphism gives flexibility by allowing the same
function to behave differently based on the object calling it.
A very popular feature of Java is its platform independence. Java code is compiled into
bytecode, which can run on any system where the Java Virtual Machine (JVM) is installed.
This approach is known as “write once, run anywhere,” meaning you don’t need to rewrite
code for different operating systems.
Java is also multithreaded, which means multiple tasks can run at the same time within a
single program. This is useful for applications such as games, servers, and multimedia tools
where tasks like sound, animation, or file loading can happen together without waiting.
Java handles memory management automatically using its built-in garbage collector. This
means it cleans up unused objects from memory without the programmer needing to do
anything manually. This reduces the chances of memory leaks and improves performance.
In terms of security, Java is well equipped. It has features like the bytecode verifier and security
manager, which ensure that untrusted code does not harm the system. It also supports
encryption and authentication through its security APIs.
Java also comes with a rich standard library called the Java Development Kit (JDK), which
includes ready-made classes and methods for tasks like networking, file handling, GUI
development, database access, and much more.
In conclusion, Java’s simplicity, reliability, cross-platform capabilities, and strong security
make it a highly preferred language in the software industry, especially in fields like Android
development, web services, and enterprise systems.
Answer 02:
In Java programming, a constructor is a special method that is automatically called when an
object is created. It has the same name as the class and does not have a return type. Constructors
are mainly used to initialize objects with default or user-defined values. Java supports multiple
types of constructors, and each serves a different purpose in object creation.
1. Default Constructor
A default constructor is one that does not take any parameters. If the programmer does not
write any constructor in a class, the Java compiler automatically adds a default constructor. It
is mainly used when you want to create an object with default values.
Example:
class Car
{
Car()
{
[Link]("Default constructor called");
}
}
When we create an object like new Car();, the above constructor will run and show the
message.
2. Parameterized Constructor
A parameterized constructor is used when you want to initialize the object with specific values
during its creation. This constructor takes one or more arguments.
Example:
class Car
{
String model;
int year;
Car(String m, int y)
{
model = m;
year = y;
}
}
This constructor allows us to set the model and year when we create the object like new
Car("Toyota", 2023);.
3. Copy Constructor
Though Java does not have a built-in copy constructor like C++, we can create our own version
manually. A copy constructor is used to create a new object with the same values as an existing
object.
Example:
class Car
{
String model;
int year;
Car(Car obj)
{
model = [Link];
year = [Link];
}
}
This helps when we want to duplicate an object safely.
4. Constructor Overloading
In Java, we can define more than one constructor in the same class, each with a different
number or type of parameters. This concept is called constructor overloading. It provides
flexibility to create objects in different ways.
Example:
class Car
{
String model;
int year;
Car()
{
model = "Unknown";
year = 0;
}
Car(String m, int y)
{
model = m;
year = y;
}
}
Depending on whether you give arguments or not, the appropriate constructor will be called.
Answer 03-a:
In Java, control statements are used to manage the flow of execution in a program. They help
the programmer decide what code should run under specific conditions or how many times a
block of code should be repeated. These statements make the program logical, efficient, and
interactive.
Java control statements are mainly divided into three categories:
1. Decision-Making Statements
These are used to make choices based on conditions.
if: Runs code only if a condition is true.
if-else: Chooses between two blocks depending on whether the condition is true or
false.
switch: Allows multi-way selection based on the value of a variable.
Example:
int number = 5;
if (number > 0)
{
[Link]("Positive number");
}
else
{
[Link]("Zero or Negative number");
}
2. Looping Statements
These are used to repeat a block of code multiple times.
for: Used when the number of repetitions is known.
while: Repeats as long as a condition is true.
do-while: Runs at least once, then repeats if the condition remains true.
Example:
for (int i = 1; i <= 5; i++)
{
[Link]("Number: " + i);
}
3. Jumping Statements
Used to alter the normal sequence of execution.
break: Exits from a loop or switch block.
continue: Skips the current iteration and goes to the next.
return: Ends a method and optionally returns a value.
Answer 03-b:
In Java programming, understanding loops and basic arithmetic is very important. One
common task is to calculate the sum of a series, such as the sum of the first few odd numbers.
Odd numbers are numbers that are not divisible by 2, like 1, 3, 5, 7, and so on.
Let us now write a simple Java program to calculate the sum of the first 10 odd numbers. The
program also displays the entire series before showing the final sum.
Java Code Example:
public class OddSeriesSum
{
public static void main(String[] args)
{
int terms = 10;
int sum = 0;
int number = 1;
[Link]("Series: ");
for (int i = 1; i <= terms; i++)
{
[Link](number);
if (i != terms) [Link](" + ");
sum += number;
number += 2; // Move to next odd number
}
[Link]("\nSum of first " + terms + " odd numbers: " + sum);
}
}
Output:
Series: 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19
Sum of first 10 odd numbers: 100
Explanation:
The variable number starts at 1 (first odd number).
Each time, we add number to sum and increase number by 2 to get the next odd
number.
This continues for 10 times using a for loop.
Finally, we print the result.
Answer 04-a:
Inheritance is one of the most important features of object-oriented programming (OOP). In
Java, inheritance allows a class to acquire properties (fields) and behaviours (methods) from
another class. The class that gives the properties is called the parent (or superclass), and the
class that receives them is called the child (or subclass).
Types of Inheritance in Java:
1. Single Inheritance – One child class inherits from one parent class.
2. Multilevel Inheritance – A class inherits from another class which itself inherits from
another class.
3. Hierarchical Inheritance – Multiple classes inherit from the same superclass.
Java does not support multiple inheritance with classes to avoid confusion (ambiguity).
However, it can be achieved using interfaces.
Example:
class Animal
{
void eat()
{
[Link]("This animal eats food.");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("The dog barks.");
}
}
In the above code, Dog inherits the eat() method from Animal.
Use of super Keyword:
Used to call the parent class constructor or methods from the child class.
class Dog extends Animal
{
Dog()
{
super(); // Calls Animal constructor
[Link]("Dog constructor called");
}
}
Answer 04-b:
Method overriding is an important concept in Java’s object-oriented programming. It happens
when a child class provides its own version of a method that is already defined in the parent
class. This feature allows Java to support runtime polymorphism, where the method that runs
depends on the type of object created, not the reference type.
Rules for Method Overriding:
1. Same Method Signature:
The name, return type, and parameters must match exactly with the method in the
parent class.
2. Access Modifier:
The overriding method cannot have a more restrictive access modifier. For example,
if the parent method is public, the child method must also be public.
3. Return Type:
The return type should either be the same or a subtype (covariant return) of the parent
method.
4. Cannot Override final, static, or private Methods:
These methods are not inherited in a way that allows overriding.
5. @Override Annotation (Recommended):
This is used before the method to ensure it is actually overriding a method from the
parent class.
Example:
class Animal
{
void sound()
{
[Link]("Animal makes a sound");
}
}
class Dog extends Animal
{
@Override
void sound()
{
[Link]("Dog barks");
}
}
Answer 05-a:
In Java, both interfaces and abstract classes are used to achieve abstraction, which means
hiding the implementation details and showing only the important features to the user.
However, both are used in different situations and follow different rules.
Key Differences:
Feature Interface Abstract Class
Defines a contract (what should be Provides a base with some common
Purpose
done) code
Only abstract, default, and static Can have both abstract and non-abstract
Methods
methods methods
Variables Only public, static, final (constants) Can have instance variables of any type
Constructors Not allowed Allowed
A class can implement multiple A class can extend only one abstract
Inheritance
interfaces class
For common behaviour among related
Use Case For capabilities (e.g., Runnable)
classes
Examples:
Interface Example:
interface Animal
{
void sound();
}
class Dog implements Animal
{
public void sound()
{
[Link]("Dog barks");
}
}
Abstract Class Example:
abstract class Animal
{
abstract void sound();
void sleep()
{
[Link]("Sleeping...");
}
}
When to Use:
Use interface when you want to define behaviour without implementation.
Use abstract class when you have shared logic and want to provide a base for related
classes.
Answer 05-b:
In Java, both errors and exceptions are types of problems that can occur during the execution
of a program. They both come from the Throwable class, but they are used in different
situations and handled differently.
Definition and Purpose:
Error: Represents serious problems that are mostly out of the programmer’s control,
like memory issues or system failure. Errors are usually not handled in the code.
Exception: Represents issues that occur due to wrong logic, bad input, or failed
operations. Exceptions can be handled using try-catch blocks.
Hierarchy:
Throwable
│
├── Error
└── Exception
├── Checked Exception
└── Unchecked Exception (Runtime)
Examples:
Error: OutOfMemoryError, StackOverflowError
Checked Exception: IOException, SQLException (must be handled)
Unchecked Exception: NullPointerException, ArithmeticException (runtime errors)
Example Codes:
Handled Exception Example:
try
{
int result = 10 / 0;
}
catch (ArithmeticException e)
{
[Link]("Cannot divide by zero.");
}
Error Example (not handled):
public class Example
{
public static void main(String[] args)
{
main(args); // causes StackOverflowError
}
}
Answer 06:
In Java, data is read from and written to different sources like files, memory, or network using
the Input/Output (I/O) stream system. Among these, DataInputStream and
DataOutputStream are two important classes used to handle binary data, especially when
dealing with primitive data types like int, float, char, etc. They allow reading and writing of
these data types in a machine-independent format.
DataInputStream ([Link]):
This class is used to read primitive data from an input stream. It works commonly with
FileInputStream, which reads data from files.
Common Methods:
readInt() – Reads an integer (4 bytes).
readDouble() – Reads a double value (8 bytes).
readUTF() – Reads a string in UTF-8 format.
readBoolean() – Reads one byte and returns true if non-zero.
readFully(byte[] b) – Reads all bytes into a byte array.
DataOutputStream ([Link]):
This class is used to write primitive data types to an output stream in a portable way. It is
usually used along with FileOutputStream.
Common Methods:
writeInt(int v) – Writes an integer value.
writeDouble(double v) – Writes a double value.
writeUTF(String s) – Writes a string in UTF-8 format.
writeBoolean(boolean v) – Writes a boolean value.
flush() – Forces any buffered output bytes to be written out.
Example Program:
Let us write a small Java program that writes data using DataOutputStream and then reads
it using DataInputStream.
import [Link].*;
public class DataStreamExample
{
public static void main(String[] args) throws IOException
{
// Writing data to file
DataOutputStream dos = new DataOutputStream(new FileOutputStream("[Link]"));
[Link](42);
[Link](3.14);
[Link]("Hello Java");
[Link]();
// Reading data from file
DataInputStream dis = new DataInputStream(new FileInputStream("[Link]"));
int number = [Link]();
double value = [Link]();
String text = [Link]();
[Link]();
[Link]("Read from file: " + number + ", " + value + ", " + text);
}
}
Output:
Read from file: 42, 3.14, Hello Java