MCS 024 JAVA
MCS 024 JAVA
June, 2021
1. (a) Compare Object Oriented and Procedure Oriented approaches. Give salient
features of both.
Ans.
Procedural Oriented Object Oriented Programming
Programming
In procedural programming, program is In object oriented programming,
divided into small parts program is divided into small parts
called functions. called objects.
Procedural programming follows top Object oriented programming follows
down approach. bottom up approach.
There is no access specifier in Object oriented programming have
procedural programming. access specifiers like private, public,
protected etc.
Adding new data and function is not Adding new data and function is easy.
easy.
Procedural programming does not have Object oriented programming provides
any proper way for hiding data so it is data hiding so it is more secure.
less secure.
In procedural programming, overloading Overloading is possible in object
is not possible. oriented programming.
In procedural programming, function is In object oriented programming, data is
more important than data. more important than function.
Procedural programming is based on Object oriented programming is based
unreal world. on real world.
Examples: C, FORTRAN, Pascal, Basic Examples: C++, Java, Python, C# etc.
etc.
Ans.
Function overloading is a feature of object-oriented programming where two or
more functions can have the same name but different parameters.
When a function name is overloaded with different jobs it is called Function
Overloading.
Function overloading can be considered as an example of polymorphism feature.
Method overloading increases the readability of the program.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
class Book {
public static void getBookInfo() { //static method
System.out.println("Welcome to TutorialsPoint Library");
}
}
public class Test {
public static void main(String[] args) {
//Call static method of Book class using class name only
Book.getBookInfo();
}
}
JAVA PROGRQAMMING ( MCS 024 ) Page |3
(e) What is an Interface ? Write a program to show how a class implements two
interfaces.
Ans.
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
interface FirstInterface {
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
(f) What is Object Serialization ? Briefly discuss the working of Object Serialization.
Ans.
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the
actual Java object in memory. This mechanism is used to persist the object.
Most impressive is that the entire process is JVM independent, meaning an object
can be serialized on one platform and deserialized on an entirely different platform.
JAVA PROGRQAMMING ( MCS 024 ) Page |4
We must have to implement the Serializable interface for serializing the object.
Note − When serializing an object to a file, the standard convention in Java is to give
the file a “ .ser ” extension.
Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}
class Test
{
public static void main(String[] args)
{
Demo object = new Demo(1, "geeksforgeeks");
String filename = "file.ser";
JAVA PROGRQAMMING ( MCS 024 ) Page |5
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
in.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
JAVA PROGRQAMMING ( MCS 024 ) Page |6
(g) Compare StringBuffer Object with String Object. When should StringBuffer
Object be preferred over String Object ?
Ans.
String StringBuffer
The length of the String object is fixed. The length of the StringBuffer can be
increased.
The String object is immutable. The StringBuffer object is mutable.
String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too memory when we concatenate strings.
many strings because every time it
creates new instance.
String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you can equals() method of Object class.
compare the contents of two strings by
equals() method.
String class is slower while performing StringBuffer class is faster while
concatenation operation. performing concatenation operation.
String class uses String constant pool. StringBuffer uses Heap memory
Example:
JAVA PROGRQAMMING ( MCS 024 ) Page |7
file: D:/cp/file.txt
package com.cp.io;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
public class StreamTokenizerDemoOne {
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("D:/cp/file.txt");
StreamTokenizer st = new StreamTokenizer(fileReader);
while(st.nextToken() != StreamTokenizer.TT_EOF) {
if(st.ttype == StreamTokenizer.TT_NUMBER) {
System.out.println("Number: "+st.nval);
} else if(st.ttype == StreamTokenizer.TT_WORD) {
System.out.println("Word: "+st.sval);
}else if(st.ttype == StreamTokenizer.TT_EOL) {
System.out.println("--End of Line--");
}
}
}
}
JAVA PROGRQAMMING ( MCS 024 ) Page |8
2. (a) Discuss the life cycle of applet, with the help of a suitable block diagram.
Ans.
1. The browser reads the HTML page and finds any <APPLET> tags.
2. The browser parses the <APPLET> tag to find the CODE and possibly
CODEBASE attribute.
3. The browser downloads the. Class file for the Applet from the URL (Uniform
Resource Locator) found in the last step.
4. The browser converts the raw bytes downloaded into a Java class, that is a
Java.lang.Class object.
5. The browser instantiates the Applet class to form an Applet object. This
requires the Applet to have a no-args constructor.
6. The browser calls the Applet’s init () method.
7. The browser calls the Applet’s start () method.
8. While the Applet is running, the browser passes all the events intended for the
Applet, like mouse clicks, key presses, etc. to the Applet’s handle Event ()
method.
9. The default method paint() in Applets just draw messages or graphics (such as
lines, ovals etc.) on the screen. Update events are used to tell the Applet that it
needs to repaint itself.
10. The browser calls the Applet’s stop () method.
11. The browser calls the Applet’s destroy () method.
Stream Sockets
Stream Sockets are used to provide a connection-oriented service (i.e. TCP-
Transmission Control Protocol).
With stream sockets a process establishes a connection to another process. Once the
connection is in place, data flows between processes in continuous streams.
Datagram Sockets
This socket are used to provide a connection-less service, which does not guarantee
that packets reach the destination and they are in the order at the destination. In
this,
individual packets of information are transmitted. In fact it is observed that packets
can be lost, can be duplicated, and can even be out of sequence.
2) Native-API driver:
The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not
written entirely in java.
4) Thin driver:
The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java
language.
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 10
(d) How do Servlets differ from Applets ? Briefly discuss the Servlet Life Cycle.
Ans.
Applets Servlets
A Java applet is a small application A servlet is a Java programming
which is written in Java and delivered to language class used to extend the
users in the form of bytecode. capabilities of a server.
Applets are executed on client side. Servlets are executed on server side.
Applets are used to provide interactive Servlets are the Java counterpart to
features to web applications that cannot other dynamic Web content
be provided by HTML alone like capture technologies such as PHP and ASP.NET.
mouse input etc.
Life cycle of Applets init(), stop(), Lifecycle of servlets are:- init( ), service(
paint(), start(), destroy(). ), and destroy( ).
Packages available in Applets are :- Packages available in servlets are:-
import java.applet.*; and import import javax.servlet.*; and import
java.awt.*. java.servlet.http.*;
Applets use user interface classes like No User interface required.
AWT and Swing.
Applets are more prone to risk as it is on Servlets are under the server security.
the client machine.
Applets utilize more network bandwidth Servlets are executed on the servers and
as it executes on the client machine. hence require less bandwidth.
Requires java compatible browser for It accepts input from browser and
execution. generates response in the form of HTML
Page, Javascript Object, Applets etc.
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 11
3. (a) What is RMI ? Briefly discuss the RMI object hierarchy. Discuss how
distributed applications are created using RMI.
Ans.
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an
object running in another JVM.
The RMI provides remote communication between the applications using two
objects stub and skeleton.
(b) Write a JAVA program that overloads the function ‘SUM’ that computes the sum of
two integers and the sum of two float values.
Ans.
class Adder {
static int SUM(int a, int b) {
return a + b;
}
class TestOverloading2 {
public static void main(String[] args) {
System.out.println(Adder.SUM(11, 11));
System.out.println(Adder.SUM(12.3f, 12.6f));
}
}
4. (a) What is a Literal ? How many types of literals are there in Java ?
Ans.
Literal: Any constant value which can be assigned to the variable is called
literal/constant.
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 13
Integral literals
• Decimal literals (Base 10): In this form, the allowed digits are 0-9.
o int x = 101;
• Octal literals (Base 8): In this form, the allowed digits are 0-7.
o // The octal number should be prefix with 0.
o int x = 0146;
• Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9, and
characters are a-f.
o // The hexa-decimal number should be prefix
o // with 0X or 0x.
o int x = 0X123Face;
• Binary literals (Base 2): we can specify literal value even in binary form also,
allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
o int x = 0b1111;
Floating-Point literal:
Decimal literals (Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;
float f = 45.52f;
(b) Briefly discuss the term Garbage Collection. Give advantages and disadvantages
of Garbage Collection.
Ans.
Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are
created on the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.
Advantages of Garbage Collection in Java
It makes java memory-efficient because the garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector (a part of JVM), so we don’t need
extra effort.
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 14
1. variable:
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
2. method:
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
3. class:
If you make any class as final, you cannot extend it.
(d) Explain how threads are created by implementing Runnable Interface. What is
thread priority ?
Ans.
The Runnable interface consists of only one method run() that provides an entry
point into thread execution.
Java assigns each thread a priority. This priority is an integer that specifies the
relative priority of one thread to another. This priority ranges from minimum 1 to
max. 10.
Methods used:
getPriority(): to get the priority of the thread
setPriority(): to set the priority of the thread
Methods:
read(), close(), seek(), readInt(), length(), readUTF(), getChannel(), getFilePointer().
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };