0% found this document useful (0 votes)
2 views

MCS 024 JAVA

The document discusses various concepts of Java programming, including the comparison between Object Oriented and Procedure Oriented programming, dynamic binding, function overloading, the significance of the static main method, interfaces, object serialization, and the differences between String and StringBuffer. It also covers the life cycle of applets, stream sockets, JDBC drivers, and the differences between servlets and applets along with the servlet life cycle. Additionally, it provides code examples to illustrate these concepts.

Uploaded by

thakurshah1216
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

MCS 024 JAVA

The document discusses various concepts of Java programming, including the comparison between Object Oriented and Procedure Oriented programming, dynamic binding, function overloading, the significance of the static main method, interfaces, object serialization, and the differences between String and StringBuffer. It also covers the life cycle of applets, stream sockets, JDBC drivers, and the differences between servlets and applets along with the servlet life cycle. Additionally, it provides code examples to illustrate these concepts.

Uploaded by

thakurshah1216
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

JAVA PROGRQAMMING ( MCS 024 ) Page |1

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.

(b) What is Dynamic Binding ? Explain the advantage of dynamic binding.


Ans.
In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a
perfect example of dynamic binding. In overriding both parent and child classes have
the same method.
Static Binding Dynamic Binding
It takes place at compile time for which It takes place at runtime so do it is
is referred to as early binding referred to as late binding.
It uses overloading more precisely It uses overriding methods.
operator overloading method
It takes place using normal functions It takes place using virtual functions
Real objects never use static binding Real objects use dynamic binding.

(c) Explain Function Overloading with the help of suitable example.


JAVA PROGRQAMMING ( MCS 024 ) Page |2

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));
}}

(d) Explain why the main method in Java is always static.


Ans.
Java main() method is always static, so that compiler can call it without the creation
of an object or before the creation of an object of the class.
In any Java program, the main() method is the starting point from where compiler
starts program execution. So, the compiler needs to call the main() method.
If the main() is allowed to be non-static, then while calling the main() method JVM
has to instantiate its class.
While instantiating it has to call the constructor of that class, There will be ambiguity
if the constructor of that class takes an argument.
Static method of a class can be called by using the class name only without creating
an object of a class.
The main() method in Java must be declared public, static and void. If any of these
are missing, the Java program will compile but a runtime error will be thrown.

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.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends). On
implementation of an interface, you must override all of its methods.

interface FirstInterface {

public void myMethod(); // interface method


}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

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

For serializing the object, we call the writeObject() method of ObjectOutputStream


class, and for deserialization we call the readObject() method of ObjectInputStream
class.

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.

// Java code for serialization and deserialization


// of a Java object
import java.io.*;

class Demo implements java.io.Serializable


{
public int a;
public String b;

// 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);

// Method for serialization of object


out.writeObject(object);

out.close();
file.close();

System.out.println("Object has been serialized");

catch(IOException ex)
{
System.out.println("IOException is caught");
}

Demo object1 = null;

// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object


object1 = (Demo)in.readObject();

in.close();
file.close();

System.out.println("Object has been deserialized ");


System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}

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

Criteria to choose between String and StringBuffer:


• If the Object value is not going to change use String Class because a String
object is immutable.
• In case the Object value can change, and will be modified by multiple threads,
use a StringBuffer because StringBuffer is synchronized and mutable.

(h) What is Stream Tokenizer ? Discuss with suitable example.


Ans.
The StreamTokenizer class takes an input stream and parses it into "tokens", allowing
the tokens to be read one at a time. The parsing process is controlled by a table and
a number of flags that can be set to various states. The stream tokenizer can
recognize identifiers, numbers, quoted strings, and various comment styles.
Each byte read from the input stream is regarded as a character in the range '\u0000'
through '\u00FF'. The character value is used to look up five possible attributes of
the character: white space, alphabetic, numeric, string quote, and comment
character. Each character can have zero or more of these attributes.

• nval : if current token is number, nval gives that number.


• sval : If current token is word, it gives the character of that word.
• TT_EOF : This is the point that represents that end of file has been read.
• TT_EOL : This represents that end of line has been read.
• TT_NUMBER : This represents that a number has been read.
• TT_WORD : This represents that word token has been read.
• ttype : This contains the type of the token which has been read.

Example:
JAVA PROGRQAMMING ( MCS 024 ) Page |7

file: D:/cp/file.txt

"Hey, 10 is my lucky number.

I divide 100 by my lucky number

and again I get 10."

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.

❖ Basic Applet Life Cycle:

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.

(b) What is a Stream Socket ? How is it different from Datagram Socket ?


Ans.
Socket is a data structure that maintains necessary information used for
communication between client & server. Therefore both end of communication has
its own sockets.
JAVA PROGRQAMMING ( MCS 024 ) Page |9

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.

(c) Briefly discuss the different kinds of drivers used in JDBC.


Ans.
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database.
There are four types of JDBC drivers:

• JDBC-ODBC Bridge Driver,


• Native Driver,
• Network Protocol Driver, and
• Thin Driver
1) JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls. This is now discouraged because of thin driver. The ODBC driver
needs to be installed on the client machine.

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.

3) Network Protocol driver:


The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol. It is fully written 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

Servlet Life Cycle:


• Loads the servlet class.
• Creates an instance of the servlet class.
• Initializes the servlet instance by calling the init() method.
• When servlet is executed it invokes the service method, passing a request and
response object.
• If the container needs to remove the servlet, it finalizes the servlet by calling
the servlet’s destroy() method.

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.

RMI Object Hierarchy:


JAVA PROGRQAMMING ( MCS 024 ) P a g e | 12

Creating Distributed Applications Using RMI


• Design and implement the components of your distributed application.
• Compile sources and generate stubs.
• Make classes network accessible.
• Start the application.

(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;
}

static float SUM(float a, float 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));
}
}

(c) Compare doGet() and doPost() method.


Ans.
Get method Post method
Get Request sends the request Post request send the request
parameter as query string appended at parameters as part of the http request
the end of the request. body.
Get method is visible to every one (It Post method variables are not displayed
will be displayed in the address bar of in the URL.
browser ).
Restriction on form data, only ASCII No Restriction on form data, Binary data
characters allowed. is also allowed.
Get methods have maximum size is Post methods have maximum size is 8
2000 character. mb.
Restriction on form length, So URL No restriction on form data.
length is restricted
Remain in browser history. Never remain the browser history.

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

Types of literals in Java:

Types of literal Example


Number Literals -45, 4L, 0777, 0XFF, 2.56F, 10e45, .36E-2
Boolean Literals TRUE, FALSE
Character Literals 'a', '#', '3', \n, \\, \"
String Literals "A string with a \t tab in it”
Double Literals 1.5, 45.6, 76.4E8
Long Literals 34L
Float Literals 45.6f, 76.4E8F, 1.5F

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

Disadvantages of Garbage Collection in Java


Garbage collectors bring some runtime overhead that is out of the programmer’s
control. This could lead to performance problems for large applications that scale
large numbers of threads or processors, or sockets that consume a large amount of
memory.

(c) What are uses of final keyword in Java ?


Ans.
The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:

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

Output:Compile Time Error

2. method:
If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error

3. class:
If you make any class as final, you cannot extend it.

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 15
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}

Output:Compile Time Error

(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.

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output: thread is running...

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

Q.5 Write short notes on the following :


(a) Transient and Volatile Modifiers
Ans.
Transient Volatile
The Transient marked variable prevents The Volatile marked variable follows
it from being serialized. happen-before relationship on visibility
in multithreaded java program which
reduces the risk of memory consistency
errors.
It gives control and flexibility over to It prevents JVM from doing re-ordering
exclude some object methods from which could compromise
serialization process. synchronization.
During deserialization they are They are not initialized with a default
initialized with a default value. value.
It cannot be used with the static It can be used with the static keyword.
keyword as static variable do not belong
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 16

to individual instance. During


serialization, only object’s current state
is concerned.
It cannot be used with the final It can be used with the final keyword.
keyword. Although JVM doesn’t
complain about it but during
deserialization one will face problem of
reinitializing a variable.

(b) Random Access File and its methods


Ans.
This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called file
pointer, by moving the cursor we do the read write operations. If end-of-file is
reached before the desired number of byte has been read than EOFException is
thrown.

Methods:
read(), close(), seek(), readInt(), length(), readUTF(), getChannel(), getFilePointer().

(c) TCP/IP Sockets


Ans.
A TCP/IP socket is used for communications between two computers. The socket
includes the Internet protocol (IP) address, as well as the host or port that the
computers are using to transmit the data. All applications that take part in the
transmission use the socket to send and receive information.

Java provides two classes for TCP/IP:


- Socket and serverSocket

(d) Multidimensional Array in JAVA


Ans.
Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order commonly).

Syntax: int [ ] [ ] TwoDarray = new int [10][15];


Int [ ] [ ] [ ] threeDarray = new int [5][6][4];

class GFG {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)


for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "
+ arr[i][j]);
}
JAVA PROGRQAMMING ( MCS 024 ) P a g e | 17
}

- Generally used for matrix problems


JAVA PROGRQAMMING ( MCS 024 ) P a g e | 18

You might also like