mcs-024-1.pdf - ignou rock

19
www.onlinecode.in 1 Page | 1 1. (a) What is Object Oriented Programming? Explain features of Object Oriented Programming. (5 Marks) Ans: Object oriented programming allows a decomposition of a problem into number entities called objects and then builds data and functions around these objects. The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects. Features of Object Oriented Programming Class and object A class is a blueprint that describes characteristics and functions of entity.. For example, the class Dog would consist of traits shared by all dogs. A class is collection of the properties and methods are called members. Object is an instance of class.

Upload: khangminh22

Post on 17-Feb-2023

1 views

Category:

Documents


0 download

TRANSCRIPT

www.onlinecode.in

1

Page

| 1

1. (a) What is Object Oriented Programming? Explain features of Object Oriented Programming.

(5 Marks)

Ans:

Object oriented programming allows a decomposition of a problem into number entities called objects and

then builds data and functions around these objects. The data of an object can be accessed only by the

functions associated with that object. However, functions of one object can access the functions of other

objects.

Features of Object Oriented Programming

Class and object

A class is a blueprint that describes characteristics and functions of entity.. For example, the class Dog

would consist of traits shared by all dogs. A class is collection of the properties and methods are called

members. Object is an instance of class.

www.onlinecode.in

2

Page

| 2

Data abstraction: - it is a process that provides only essential features by hiding its background details. A

data abstraction is a simple view of an object that includes required features and hides the unnecessary

details.

Data encapsulation:- it is a mechanism of bundling the data, and the functions that use them and data

abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the

user.

Inheritance: it is a process to create a new class from existing class or classes. Class ‘B’ is a sub class

that is derived from class ‘A’. Thus class ‘A’ is a parent class and class ‘B’ is a child class. It provides

reusability of code.

Polymorphism: - Generally, it is the ability to appear in different forms. In oops concept, it is the ability to

process objects differently depending on their data types. It’s the ability to redefine methods for derived

classes.

(b) What is platform independence? Explain why java is platform independent.

(2 Marks)

Ans:

The Java programs use compiler and interpreter. The programs written in Java are compiled by compiler

and converted into intermediate code known as Java byte code.

Java interpreter is a part of java runtime environment that reads byte code and convert it into

executable code on any operating system. It is known as JVM (Java Virtual Machine). The JVM makes

java portable so that java program can run on any platform. That’s why java is called Machine

independent and Architecture neutral.

(c) Write a program to explain how array of objects may be created in java.

(3 Marks)

Ans:

class myarray

{

void disp(int a)

{

System.out.println("\n my number="+a);

}

}

class callme

{

www.onlinecode.in

3

Page

| 3

public static void main(String arg[])

{

myarray ob[] =new myarray[5];

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

{

ob[i]=new myarray();

ob[i].disp(i);

}

}

}

2.

(a) Write a java program to demonstrate use of different data types available in java.

(4 Marks).

Ans:

public class data

{

public static void main(String arg[])

{

byte b =103;

short s =13;

int v = 123443;

int calc = -3872245;

long amount = 1234444441;

float Rate = 12.25f;

double sineVal = 12345.234d;

boolean flag = true;

boolean val = false;

char ch1 = 65; // code for X

char ch2 = 'Y';

System.out.println("byte Value = "+ b);

www.onlinecode.in

4

Page

| 4

System.out.println("short Value = "+ s);

System.out.println("int Value = "+ v);

System.out.println("int second Value = "+ calc);

System.out.println("long Value = "+ amount);

System.out.println("float Value = "+ Rate);

System.out.println("double Value = "+ sineVal);

System.out.println("boolean Value = "+ flag);

System.out.println("boolean Value = "+ val);

System.out.println("char Value = "+ ch1);

System.out.println("char Value = "+ ch2);

}

}

(b) Explain followings in context of java, with the help of examples.

(i) Class and objects

(ii) Abstraction and encapsulation

(iii) Application program and applet program

(6 Marks)

Ans:

(i) Class and object

A class is a blueprint that describes characteristics and functions of entity.. For example, the class Dog

would consist of traits shared by all dogs. A class is collection of the properties and methods are called

members. Object is an instance of class.

Data abstraction: - it is a process that provides only essential features by hiding its background details. A

data abstraction is a simple view of an object that includes required features and hides the unnecessary

details.

(ii) Data abstraction & Data encapsulation –

it is a process that provides only essential features by hiding its background details. A data abstraction is a

simple view of an object that includes required features and hides the unnecessary details. it is a

mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of

exposing only the interfaces and hiding the implementation details from the user.

(iii) Applet vs Application program

Java Application:

A java application is a stand-alone program. This means it can be run by itself.

It cannot access from web browser.

It is run by JVM.

www.onlinecode.in

5

Page

| 5

It can access on local machine on which program is reside.

Applet

Applet cannot run as independent program.

Applet program can run from within a web browser or similar java enabled application such as an

applet viewer

Java applets are included in HTML pages using <applet> tag.

Applet communicates with server only.

Applets are not allowed to read or write to files on the local system.

3.

(a) What is static variable and static method? Explain why main method in java is always static.

(2 Marks)

Ans:

Static It can be used with a variable, a method or block of code. A static methods or variable cannot

instance specific. There is no need to create an object of the class to access the static features of the

class.

Class suman

{

Static int i=10;

}

Class aman

{

public static void main (string args[])

{

System.out.println(‘my number is=”+suman.i)

}

}

(b) What is inheritance? Explain the advantage of inheritance with an example program. What are

different types of inheritance supported by java?

(5 Marks)

Ans:

Inheritance: it is a process to create a new class from existing class or classes. Class ‘B’ is a sub class

that is derived from class ‘A’. Thus class ‘A’ is a parent class and class ‘B’ is a child class. It provides

reusability of code.

Advantage:

Code reusability

Function overriding

Save compilation and programmer time

www.onlinecode.in

6

Page

| 6

Increase modularity

Example:-

class suman

{

int c;

public void sum (int a, int b)

{

c=a+b;

system.out.println(c);

}

class pix extends suman

{

public static void main()

{

suman s=new suman();

s.sum(4,5);

}

}

(c) Explain the steps involved in creating a distributed application using Remote Method

Invocation (RMI). (3 Marks)

Ans:-

Steps to write the RMI program.

Create the remote interface

Provide the implementation of the remote interface

Compile the implementation class and create the stub and skeleton objects using the rmic tool

Start the registry service by rmiregistry tool

Create and start the remote application

Create and start the client application

www.onlinecode.in

7

Page

| 7

4.

(a) What is polymorphism? Is Interfaces in Java, a kind of polymorphism? Justify your answer

with the help of an example.

(2 Marks)

Ans:

Polymorphism : - Polymorphism is the way of providing the different functionality by

the functions having the same name based on the signatures of the methods. Interface is not a

polymorphism because interface provides a pattern of methods.

class student

{

int a,b;

void sum(int x,int y)

{

a=x;

b=y;

int c;

c=a+b;

System.out.println("sum with Arguments="+c);

}

void sum()

{

a=10;

b=20;

int c;

c=a+b;

System.out.println("sum without Arguments="+c);

}

}

6

(b) Explain the need of package in Java. Write a java program to show how package is created.

(3 Marks)

Ans:

A Java package is a set of classes which are grouped together. This grouping helps to organize Java

classes and interfaces classes with the same name.

A package provides a unique namespace for the types it contains.

www.onlinecode.in

8

Page

| 8

Classes in the same package can access each other's package-access members.

Creating package

package world;

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello World");

}

}

Calling package

import world.*;

import world.moon;

PATH: maintains a list of directories. The OS searches the PATH entries for executable programs, such

as Java Compiler (javac) and Java Runtime (java).

CLASSPATH: maintain a list of directories (containing many Java class files) and JAR files (a single-file

archive of Java classes). The Java Compiler and Java Runtime searches the CLASSPATH entries for

Java classes referenced in your program.

(c) What is rule of accessibility? Explain different level of accessibility in java.

(5 Marks)

Ans:

Rules are:

Access Modifiers Same Class Same Package Subclass Other packages

public Y Y Y Y

protected Y Y Y N

no access modifier Y Y N N

private Y N N N

(i)Class level access modifiers

Only two access modifiers is allowed, public and no modifier

If a class is ‘public’, then it CAN be accessed from ANYWHERE.

If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

(II) Member level access modifiers

All the four public, private, protected and no modifer is allowed.

public and no modifier – the same way as used in class level.

www.onlinecode.in

9

Page

| 9

private – members CAN ONLY access.

protected – CAN be accessed from ‘same package’ and a subclass existing in any package can

access.

5.

(a) What is abstract class? Explain need of abstract class with the help of an example.

(2 Marks)

Ans:

abstract class pixeles

{

int b=200;

abstract void salary();

}

class manager extends pixeles

{

void salary()

{

system.out.println(“salary=’+b*2);

}

}

class aman

{

public static void main(string args[])

{

manager m=new manager();

m.salary();

}

}

(b) What is an exception? Explain haw an exception is handled in Java. Explain hierarchy of different exception classes in java. Also explain why is it not necessary to handle runtime exception? (6 Marks) Ans: An exception is an event, which occurs during the execution of a program that disrupts the normal flow of

the program's instructions. When an error occurs within a method, the method creates an object and

hands it off to the runtime system. The object, called an exception object, contains information about the

error, including its type and the state of the program when the error occurred. Creating an exception object

and handing it to the runtime system is called throwing an exception.

class Number { private int num; public void accept(int n) throws Exception { if( n == 0 ){

www.onlinecode.in

10

Page

| 10

throw new Exception(“can’t assign zero…”); } else if(n < 0) { throw new Exception(“can’t assign -ve value…”); } Else { System.out.println(“\n\n\tValid value.”); num = n; } } } public class ThrowsDemo { public static void main(String args[]) { Number ob = new Number(); Try { ob.accept(-8); //ob.accept(10); } catch(Exception e) { System.out.println(“\n Error: ” + e); } System.out.println(“\n\n”); } }

www.onlinecode.in

11

Page

| 11

In Java exceptions under Error and RuntimeException classes are unchecked exceptions. It can be

ignored. Checked and unchecked exceptions are functionally equivalent. There is nothing you can do with

checked exceptions that cannot also be done with unchecked exceptions, and vice versa.

(c) Write a java program to create two threads with different priority. (2 Marks)

Ans:

class pixeles extends Thread

{

static String msg[]={"PIXELES", "Classes", "for", "BCA", "MCA"};

public synchronized void display(String th1)

{

try

www.onlinecode.in

12

Page

| 12

{

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

System.out.println(th1+msg[i]);

}catch(Exception e)

{

System.out.println("Exception handled");

}

}

public void run()

{

try

{

display(getName());

this.sleep(1000);

}

catch(Exception ex)

{

}

}

}

public class synthread2

{

public static void main(String[] args)

{

pixeles t1=new pixeles("Thread One: ");

t1.start();

pixeles t2=new pixeles("Thread Two: ");

t2.start();

}

}

6.

(a) What is I/O stream in java? Write a program in java to create a file and copy the content of an

already existing file into it.

(4 Marks)

Ans:

import java.io.*;

class myfile

{

public static void main(String arg[]) throws IOException

www.onlinecode.in

13

Page

| 13

{

FileInputStream in=new FileInputStream(arg[0]);

System.out.print(byte ibuf[]=new byte[x];

int r=in.read(ibuf,0,x);

if(r!=1)

System.out.print(“File is empty”);

else

System.out.print(new String(ibuf));

System.out.print(“Size of File is=”+x);

String s= new String(ibuf);

FileOutputStream ot=new FileOutputStream(arg[1]);

for(int i=0;i<s.length();i++)

ot.write(s.charAt(i));

System.out.print(“File is Copied”);

ot.close();

in.close();

}}

(b) Create an Applet program to display your brief profile with your photograph. Make necessary

assumptions and use appropriate layout in your program.

(4 Marks)

ANs:

import java.applet.*;

import java.awt.*;

public class pix extends Applet{

Image img;

MediaTracker tr;

public void paint(Graphics g) {

tr = new MediaTracker(this);

img = getImage(getCodeBase(), "demoimg.gif");

tr.addImage(img,0);

g.drawImage(img, 0, 0, this);

g.drawString("Name:Ashok Kumar",100,200);

g.drawString("DOB:12/jun/1985",120,200);

g.drawString("Address: Delhi",130,200);

www.onlinecode.in

14

Page

| 14

g.drawString("Qly: BCA 4th Sem",140,200);

}

}

(c) Differentiate between String and StringBuffer classes. Also write a program to find the length

of a given string. (2 Marks)

Ans:

String is immutable:

String str = "Hello World";

StringBuffer is mutable:

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");

String buffers are safe for use by multiple threads. A StringBuffer class implements a mutable sequence of

characters. A StringBuffer class is like a String, but can be modified. At any point in time it contains some

particular sequence of characters, but the length and content of the sequence can be changed through

certain method calls.

7.

(a) What is need of layout manager? Explain different layouts available in java for GUI

programming. (4 Marks)

Ans:

Several AWT and Swing classes provide layout managers for general use:

FlowLayout

A FlowLayout arranges widgets from left to right until there's no more space left. Then it begins a row

lower, and moves from left to right again. Each component in a FlowLayout gets as much space as it

needs, and no more.

This is the default LayoutManager for applets and panels.

FlowLayout fl = new FlowLayout();

BorderLayout

A BorderLayout organizes an applet into North, South, East, West, and Center sections. North, South,

East, and West are the rectangular edges of the applet. They' are continually resized to fit the sizes of the

www.onlinecode.in

15

Page

| 15

widgets included in them. A BorderLayout places objects in the North, South, East, West, and Center of

an applet

this.setLayout(new BorderLayout())

Grid Layout

A GridLayout divides an applet into a specified number of rows and columns, which form a grid of cells,

each equally sized and spaced. It is important to note that each is equally sized and spaced as there is

similarly named Layout known as GridBagLayout. As Components are added to the layout, they are

placed in the cells,

CardLayout

A CardLayout object is a layout manager for a container. It treats each component in the container as a

card. Only one card is visible at a time, and the container acts as a stack of cards. The first component

added to a CardLayout object is the visible component when the container is first displayed.

Grid bag layout:- it is similar to grid layout in which elements are arragned in row and colums but it allows

to insert a component in span of two cells.

(b) What is a TCP/IP socket? Write a java program to create socket. (3 Marks)

Ans:

TCPServer

import java.io.*;

import java.net.*;

class TCPServer

www.onlinecode.in

16

Page

| 16

{

public static void main(String argv[]) throws Exception

{

String clientSentence;

String capitalizedSentence;

ServerSocket welcomeSocket = new ServerSocket(6789);

while(true)

{

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient =

new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

System.out.println("Received: " + clientSentence);

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);

}

}

}

(c) Explain the need of JDBC? Explain steps involved in connecting a databases using JDBC.

(3 Marks)

Ans:

Steps:

Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to

dynamically load the driver class.

Class.forName("oracle.jdbc.driver.OracleDriver");

Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","passwor

d");

Create the Statement object

www.onlinecode.in

17

Page

| 17

The createStatement() method of Connection interface is used to create statement. The object of

statement is responsible to execute queries with the database.

Statement stmt=con.createStatement();

Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This

method returns the object of ResultSet that can be used to get all the records of a table.

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())

{

System.out.println(rs.getInt(1)+" "+rs.getString(2));

}

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method

of Connection interface is used to close the connection.

con.close();

8.

(a) Explain basic networking features of java. (2 Marks)

Ans:

Distributed

We can create distributed applications in java. RMI and EJB are used for creating distributed applications.

We may access files by calling the methods from any machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with

many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares

the same memory. Threads are important for multi-media, Web applications etc.

(b) What are principles of event delegation model? Explain different sources of events and event

listener. (3 Marks).

Ans:

It is important to consider how users interact with the user interface when designing a graphical

user interface (GUI). The GUI may require users to click, resize, or drag and drop components of

the interface, and input data using the keyboard. These actions will result to an event and you

need to write a code to handle them. Event handling code deals with events generated by GUI user

www.onlinecode.in

18

Page

| 18

interaction. The best practices for coding event handlers are outlined in the event delegation

model.

The event model is based on the Event Source and Event Listeners. Event Listener is an object that

receives the messages / events. The Event Source is any object which creates the message / event. The

Event Delegation model is based on – The Event Classes, The Event Listeners, Event Objects.

There are three participants in event delegation model in Java;

- Event Source – the class which broadcasts the events

- Event Listeners – the classes which receive notifications of events

- Event Object – the class object which describes the event.

(c) What is servlet? Explain various ways of session management in servlet programming.

Ans:

A servlet is a Java programming language class used to extend the capabilities of a server. Although

servlets can respond to any types of requests, they are commonly used to extend the applications hosted

by web servers.

There are several ways through which we can provide unique identifier in request and response.

A. User Authentication – This is the very common way where we user can provide authentication

credentials from the login page and then we can pass the authentication information between

server and client to maintain the session. This is not very effective method because it won’t work

if the same user is logged in from different browsers.

B. HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts

navigating, we can set its value unique to the user and keep track of the session. This method

can’t be used with links because it needs the form to be submitted every time request is made

from client to server with the hidden field. Also it’s not secure because we can get the hidden

field value from the HTML source and use it to hack the session.

C. URL Rewriting – We can append a session identifier parameter with every request and

response to keep track of the session. This is very tedious because we need to keep track of this

parameter in every response and make sure it’s not clashing with other parameters.

D. Cookies – Cookies are small piece of information that is sent by web server in response header

and gets stored in the browser cookies. When client make further request, it adds the cookie to

the request header and we can utilize it to keep track of the session. We can maintain a session

with cookies but if the client disables the cookies, then it won’t work.

www.onlinecode.in

19

Page

| 19

Author:- UJJWAL KUMAR THAKUR

Supports:- St. Xavier Team & my friends

Reference:- PIXELES CLASSES

Mob:

9852781385

[email protected], web: www.onlinecode.in

www.ignourock.webs.com