MCS-024(MS Word Format) Available.

advertisement
PIXELES CLASSES
BCA & MCA (IGNOU)
Course Code
Course Title
: MCS-024
: Object Oriented Technologies and Java
Assignment Number
: BCA(IV)/024/Assignment/ 2015
October, 2015 (For July 2015 Session) April, 2016 (For January 2016 Session)
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.
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.
www.pixelesindia.com
Page | 1
PIXELES CLASSES
BCA & MCA (IGNOU)
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)
Page | 2
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.
We are teaching IGNOU’s BCA & MCA Students
(3 Marks)
Ans:
class myarray
Why join us?
{
 Regular Classes
void disp(int a)
 BCA & MCA IGNOU Special Institute
{
 Free Trial Classes
System.out.println("\n my number="+a);
}
 Subjective Knowledge
}
 Free PIXELES Guide Books (Prepared by our
class callme
teachers)
{
 Free Solved Assignments
public static void main(String arg[])
{
 Experienced Faculties
myarray ob[] =new myarray[5];
 100% Results
for(int i=0;i<=4;i++)
 Home Test Series
{
 Class Test Series
ob[i]=new myarray();
ob[i].disp(i);
}
 We teach you until you pass
 Final Year Synopsis & Project
 Proper Guidance
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
}
}
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);
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);
www.pixelesindia.com
Page | 3
PIXELES CLASSES
BCA & MCA (IGNOU)
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.
 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.
www.pixelesindia.com
Page | 4
PIXELES CLASSES
BCA & MCA (IGNOU)
(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
 Increase modularity
Example:-
www.pixelesindia.com
Page | 5
PIXELES CLASSES
BCA & MCA (IGNOU)
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);
}
}
Page | 6
(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
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.
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
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.
 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;
www.pixelesindia.com
Page | 7
PIXELES CLASSES
BCA & MCA (IGNOU)
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.
Page | 8
(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.
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;
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
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 ){
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[])
www.pixelesindia.com
Page | 9
PIXELES CLASSES
BCA & MCA (IGNOU)
{
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”);
}
}
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.
www.pixelesindia.com
Page | 10
PIXELES CLASSES
BCA & MCA (IGNOU)
(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
{
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();
}
}
www.pixelesindia.com
Page | 11
PIXELES CLASSES
BCA & MCA (IGNOU)
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)
Page | 12
Ans:
import java.io.*;
class myfile
{
public static void main(String arg[]) throws IOException
{
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) {
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
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);
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();
www.pixelesindia.com
Page | 13
PIXELES CLASSES
BCA & MCA (IGNOU)
Page | 14
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 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.
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
Page | 15
(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
{
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:
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
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","syste
m","password");

Create the Statement object
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
www.pixelesindia.com
Page | 16
PIXELES CLASSES
BCA & MCA (IGNOU)
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- Page | 17
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 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
www.pixelesindia.com
PIXELES CLASSES
BCA & MCA (IGNOU)
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 Page | 18
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.
PIXELES CLASSES
Branches & Contacts Details
Uttam Nagar:-WZ-B7, Old Pankha
Road (Opp. Primary School), Near
East Metro Station, Uttam Nagar,
New Delhi-59
Nangloi:-Plot. No-19, Ext- 2A,
oppBanke-Bihari, Talabwali Road,
Nangloi, Delhi-41
Ph: 9213327975, 9716339580
8750321695
pixeles@rediffmail.com, web: www.pixelesindia.com
www.pixelesindia.com
Download