Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
BCA 4TH SEMESTER
MCS-024 ASSIGNMENTSOLUTION (2020-21)
Q1. a) What is Object Oriented Programming (OOP)? Explain
its advantages. Also describe concept of data hidingin OOP.
Answer : - Object-OrientedProgramming is amethodology orparadigm to designa program usingclasses and
objects. It simplifies thesoftwaredevelopmentandmaintenance by providingsomeconcepts :
 Object -Any entity that has state and behavioris knownas an object. An Objectcan be definedas an
instanceof aclass.
 Class - Collectionof objects is calledclass. Itis alogical entity. Aclass canalso bedefinedas a
blueprint from whichyoucancreate an individual object. Class doesn'tconsumeany space.
 Inheritance -Whenoneobject acquires all the properties and behaviors of a parent object, it is
knownas inheritance.
 Polymorphism -If one task is performedby different ways, itis knownas polymorphism. InJava, we
usemethod overloadingand methodoverridingto achievepolymorphism.
 Abstraction -Hidinginternal details and showingfunctionality is knownas abstraction. InJava, we
useabstract class andinterface to achieveabstraction.
 Encapsulation -Binding(orwrapping) codeand data together into a singleunit are knownas
encapsulation. Ajava class is theexampleof encapsulation. Javabeanis the fully encapsulatedclass
becauseall the data members are private here.
Advantage ofObject Oriented ProgrammingSystem(OOPs) -
 OOPs makes development andmaintenanceeasier whereas ina procedure-oriented programming
language it is not easy to manage if codegrows as project sizeincreases.
 OOPs provides datahidingwhereas ina procedure-oriented programminglanguage a global data can
be accessedfrom anywhere.
 OOPs provides theability to simulatereal-worldeventmuchmoreeffectively. Wecanprovidethe
solutionof real word problem if we are usingthe Object-Oriented Programminglanguage.
Data Hiding - Data hidingis asoftware developmenttechniquespecifically usedinobject-oriented
programming(OOP) to hide internal object details (data members). Datahidingensures exclusivedataaccess
to class members andprotects object integrity by preventing unintended or intended changes.
Data hidingalso reduces system complexity forincreasedrobustness by limitinginterdependencies between
software components.
Q1. b) Explain different data types available in Java.
Answer : - In Javadata types are dividedinto two groups :
 Primitivedata types - includes byte, short, int, long, float, double, booleanandchar
 Non-primitivedatatypes - suchas String, Arrays and Classes
Primitive Data Types
Data
Type
Size Description and Example
byte 1
bytes
Stores whole numbersfrom -128 to 127
Example: byte a = 10, byte b = -20;
short 2
bytes
Stores whole numbersfrom -32,768 to 32,767
Example: short s = 10000, shortr = -5000;
int 4
bytes
Stores whole numbersfrom -2,147,483,648to
2,147,483,647
Example: int a = 100000, intb= -200000;
long 8
bytes
Stores whole numbersfrom -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
Note that you should end the valuewith an "L".
Example: long a = 100000L, longb= -200000L;
float 4
bytes
Stores fractional numbers. Sufficientfor storing6 to 7
decimal digits
Note that you should end the valuewith an "f":
Example: float x = 234.5f;
double 8
bytes
Stores fractional numbers. Sufficientfor storing15
decimal digits
Example: doubley = 12.3;
boolean 1 bit Stores true or false values
Example: char letter = 'A';
char 2
bytes
Stores a single character/letter or ASCII values
Example: Boolean b = false;
Non-Primitive Data Types
Non-primitivedatatypes are calledreference types becausethey refer to objects.
Themain differencebetween primitiveandnon-primitivedatatypes are :
 Primitivetypes are predefined (already defined) inJava. Non-primitivetypes arecreated by the
programmer and is not definedby Java (except for String).
 Non-primitivetypes canbeused to call methods to perform certain operations, whileprimitivetypes
cannot.
 A primitivetypehas always avalue, whilenon-primitivetypes canbenull.
String -The String data type is usedto store a sequenceof characters (text). String values must besurrounded
by doublequotes :
Example - String message= "Hello World";
Q1. c) Describe features of Java programming language.
Answer : - Theprimary objectiveof Java programminglanguage creationwas to make itportable, simpleand
secureprogramming language. Apart from this, there are also someexcellentfeatures whichplay animportant
rolein the popularity of this language.
A listof mostimportantfeatures of Javalanguage is givenbelow.
 Simple -Javais very easy to learn, and its syntax is simple, cleanandeasy to understand.
 Object-Oriented -Javais anobject-oriented programming language. Everything inJava is an object.
Object-oriented means we organize oursoftware as a combinationof different types of objects that
incorporates both data and behavior.
Basic concepts of OOPs are:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
 Platform Independent-Javacodeis compiledby thecompilerandconvertedinto bytecode. This
bytecodeis a platform-independent codebecauseit can be run onmultipleplatforms, i.e., WriteOnce
and Run Anywhere(WORA).
 Secured -Javais best knownforits security. WithJava, wecan developvirus-freesystems. Javais
securedbecause :
o No explicit pointer
o Java Programs run inside a virtual machinesandbox
o Classloader : ClassloaderinJavais a part of the JavaRuntimeEnvironment(JRE) whichis
usedto loadJava classes into theJavaVirtual Machinedynamically. Itadds security by
separating the package for the classes of thelocal filesystem from thosethatare imported
from network sources.
o Bytecode Verifier : It checks the codefragments forillegal codethat canviolateaccess right
to objects.
o Security Manager : Itdetermines what resources a class canaccess suchas readingand
writing to the local disk.
 Robust -Robustsimply means strong. Javais robustbecause:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collectioninjava whichruns onthe JavaVirtual Machineto get
rid of objects whichare not being usedby a Javaapplicationanymore.
o There are exception handlingand the typecheckingmechanism inJava. All thesepoints make
Javarobust.
 Architecture Neutral -Javais architectureneutral becausethere are no implementationdependent
features, forexample, the sizeof primitivetypes is fixed.
 Portable -Java is portablebecause itfacilitates youto carry the Javabytecodeto any platform. It
doesn't require any implementation.
 Distributed -Javais distributedbecauseitfacilitates users to create distributedapplications inJava.
RMIand EJB are used forcreating distributed applications. This featureof Javamakes us able to access
files by callingthemethods from any machineon the internet.
 Multithreaded-Athread is likea separate program, executing concurrently. Wecanwrite Java
programs that deal withmany tasks at onceby definingmultiplethreads. Themainadvantage of
multi-threading is that itdoesn't occupy memory foreachthread. It shares a commonmemory area.
 Dynamic -Java is adynamic language. It supports dynamic loadingof classes.Itmeans classes are
loadedon demand.
Q2. a) What is a class? Define a class in Java and with the help
of that class describe meaning of data members and member
functions. Also describe use of different types of access
spcifiers available in Java.
Answer : -
 A Class is auser defineddata-type whichhavedata members and member functions.
 Data members are the data variables andmember functions arethe functions usedto manipulate
these variables andtogether these data members and memberfunctions defines the properties and
behaviorof the objects ina Class.
 A class is likeablueprintforan object.
class Student
{
//Data Members
private int id;
private String name;
//Member Functions
public static void main(String
args[])
{
id=10;
name="Debabrata";
System.out.println(id + "t" +
name);
}
}
There are 4 types of access spcifiers inJava:
 private -The privateaccess modifieris accessibleonly withinclass.
 default -If youdon't useany modifier, itis treated as defaultbydefault. Thedefault modifieris
accessibleonly withinpackage.
 protected -Theprotected access modifieris accessiblewithinpackageandoutsidethe package but
through inheritance only.
 public -The public access modifieris accessibleeverywhere. Ithas the widestscopeamongall other
modifiers.
Q2. b) Describe advantages of abstract method. Write a java
program to create a Shape class with an abstract method
Find_Area( ). Inherit Circle and Rectangle classes from Shape
class. Implement Find_Area( ) method in derived classes.
Make necessary assumptions.
Answer : - Amethod whichis declaredas abstract and does nothave implementationis knownas an abstract
method.
Example : abstract voidprintStatus( ); // No MethodBody
If a class includes abstractmethods, thenthe class itself mustbedeclared abstract.
Abstractionis a process of hidingthe implementationdetails andshowingonly functionality to theuser.
Another way, it shows only essential things to theuser and hides the internal details, forexample, sendingSMS
where youtype the text and sendthe message. Youdon't knowthe internal processingaboutthe message
delivery.
public abstract class Shape
{
// Abstract Method
abstract void Find_Area();
}
import java.io.*;
public class Circle extends Shape
{
private double radius;
// Inputthe valueof Radiusfrom the User
void Input()throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value of Radius ...");
radius = Double.parseDouble(br.readLine());
}
// Calculate the area of a Circle based on given Input
void Find_Area()
{
double area = 3.14 * radius * radius;
System.out.println("Area of the Circle is = " +
area);
}
}
import java.io.*;
public class Rectangle extends Shape
{
private double length;
private double breadth;
// Inputthe valueof Length and Breadth from the User
void Input()throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value of Length ...");
length = Double.parseDouble(br.readLine());
System.out.println("Enter the value of Breadth
...");
breadth = Double.parseDouble(br.readLine());
}
// Calculate the area of a Rectangle based on given Input
void Find_Area()
{
double area = length * breadth;
System.out.println("Area of the Rectangle is = " +
area);
}
}
import java.io.*;
public class CallMethod
{
public static void main(String args[])throws
IOException
{
Circle ob1 = new Circle();
Rectangle ob2 = new Rectangle();
// Calculate the Area of a Circle
ob1.Input();
ob1.Find_Area();
// Calculate the Area of a Rectangle
ob2.Input();
ob2.Find_Area();
}
}
Output :
Enter the valueof Radius...
10.5
Area of the Circle is = 346.185
Enter the valueof Length ...
20
Enter the valueof Breadth ...
10
Area of the Rectangle is = 200.
Q3. a) Explain use(s) of following keywords of Java with the
help of program/example.
i. final
ii. finally
iii. super
Answer : -
final Keyword
 Final is a keywordornon-access modifierinjava.
 It can be apply withclass, variables, andmethods.
 If youmakeany class as final class thenyoucannotinherit(extends) this class. If youmakeany
variableas final variablethen youcannot change the valueof this variableafter initialization. If you
makeany methodas final methodthen youcannot overridethis method.
 If we declarefinal variablealongwith static keywordwill becomeaconstants.
Example :
class Speed
{
//final variable
final int speedlimit=90;
void run()
{
speedlimit=400;
}
public static void main(String
args[])
{
Speed obj=new Speed();
obj.run();
}
}
Output : CompileTimeError
finally Keyword -
 Thefinally keywordis usedto create a block of codethat follows atry block.
 Javafinally block of codeis usedto execute important codesuchas closingconnection, stream etc.
 Javafinally block is alwaysexecutedwhether exception is handledor not.
Example :
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int n=5/0;
System.out.println("Answer = " + n);
}
catch(Exception e) {
System.out.println(e); }
finally
{
System.out.println("finally block is
always executed");
}
System.out.println("rest of the code...");
}
}
Output :
java.lang.ArithmeticException: / by zero
finally block is alwaysexecuted
rest of the code...
super Keyword -We canuse superkeywordto access the data member and methods of parent class. Itis used
if parent class andchildclass havesamemethods orvariables.
Example :
//Parent Class
class Base
{
int fact;
void Factorial(int n)
{
fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
}
}
//Child Class
class Derived extends Base
{
void Factorial(int n)
{
//Call the OverridingMethod of ParentClass
super.Factorial(n);
System.out.println("Factorial =
"+super.fact);
}
}
Q3. b) What is interface? How interface is different from
abstract class? Write a program in Java to explain how
interfaces are implemented.
Answer : - Likea class, aninterfacecan havemethods and variables, butthe methods declared ininterface are
by default abstract (only methodsignature, no body). Interfaces specify whata class mustdo andnot how.
A class thatis declared withabstract keyword, is knownas abstract class injava. It canhave abstract and non-
abstract methods (methodwith body). Methodthat are declared withoutany body withinan abstract class are
calledabstract method. Themethod body will bedefinedby its subclass. Abstractmethodcannever be final
and static. Any class thatextends an abstract class mustimplementall theabstractmethods declared by the
super class.
Abstract Class Interface
Abstract class can have abstract and
non-abstract methods.
Interface can have only abstract
methods.
Abstract class doesn'tsupport
multipleinheritance.
Interface supportsmultiple
inheritance.
Abstract class can have final, non-
final, static and non-static variables.
Interface has only static and final
variables.
Abstract class can providethe
implementation of interface.
Interface can'tprovidethe
implementation of abstract class.
An abstract class can extend another
Javaclass and implementmultiple
Javainterfaces.
An interface can extend another Java
interface only.
A Javaabstract class can have class
memberslike private, protected, etc.
Membersof a Javainterface are
public by default.
Java Interface Example
interface Bank
{
double RateOfInterest();
double ATMcharges();
}
class SBI implements Bank
{
public double RateOfInterest() { return 6.2; }
public double ATMcharges() { return 100.0; }
}
class RBL implements Bank
{
public double RateOfInterest() { return 6.8; }
}
class InterestCheck
{
public static void main(String args[])
{
Bank ob1=new SBI();
System.out.println("SBI Interest Rate = " +
ob1.RateOfInterest());
System.out.println("SBI ATM Charges = " +
ob1.ATMcharges());
Bank ob2=new RBL();
System.out.println("RBL Interest Rate = " +
ob2.RateOfInterest());
}
}
Q4. a) What is polymorphism? Explain use of polymorphism
in java programming.
Answer : - PolymorphisminJavais aconceptby whichwe canperform a singleactionindifferent ways. There
are two types of polymorphisminJava:compile-timepolymorphismandruntimepolymorphism.
Run timePolymorphism alsoknownas methodoverriding. Methodoverridingmeans havingtwo or more
methods withthe samename, samesignature but with different implementation.
CompiletimePolymorphism also knownas methodoverloading. Methodoverloadingmeans havingtwo or
moremethods with the samename but withdifferent signatures.
Example ofPolymorphism
class Bank
{
double getRateOfInterest() { return 0.0; }
}
class SBI extends Bank
{
double getRateOfInterest() { return 6.2; }
}
class ICICI extends Bank
{
double getRateOfInterest() { return 6.8; }
}
class AXIS extends Bank
{
double getRateOfInterest() { return 6.5; }
}
class TestPolymorphism
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("SBI Interest Rate = " +
b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Interest Rate = " +
b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Interest Rate = " +
b.getRateOfInterest());
}
}
Q4. b) What is exception? What are different types of
exceptions? Explain need of exceptions handling with the
help of a program.
Answer : - Exceptions are events that occurduring the execution of programs that distrupthe normal flowof
instructions (example-divideby zero, array access outof bound, etc.).
In Java, an exception is anobject that wraps an error event that occurred withina methodand contains :
 Informationabout the error includingits type
 Thestate of the program when the error occurred
 Optionally, othercustom information
Different Types ofJava Exceptions
 ArithmeticException
If we divideany numberby zero, there occurs an ArithmeticException.
int a = 50/0; //ArithmeticException
 NullPointerException
If we havea null valueinany variable, performingany operation onthe variablethrows a
NullPointerException.
String s = null;
System.out.println(s.length()); //NullPointerException
 NumberFormatException
Thewrong formatting of any valuemay occurNumberFormatException. SupposeI havea string
variablethat has characters, convertingthis variableinto digitwill occurNumberFormatException.
String s = "abc";
int i=Integer.parseInt(s); //NumberFormatException
 ArrayIndexOutOfBoundsException
If youare insertingany valueinthe wrong index, itwouldresult inArrayIndexOutOfBoundsException
as shownbelow:
int a[ ] = new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
There are 5 keywords whichareused inhandling exceptions inJava.
Keyword Description
try
The "try" keyword isused to specify a block where we should
place exception code. The try block mustbe followed by either
catch or finally. It means, wecan't usetry block alone.
catch
The "catch" block is used to handlethe exception. It mustbe
preceded by try block which meanswe can'tuse catch block
alone. It can be followed by finally block later.
finally
The "finally"block is used to execute the importantcode of the
program. It is executed whether an exception is handled or not.
throw The "throw" keyword isused to throw an exception.
throws
The "throws" keyword isused to declareexceptions. It doesn't
throw an exception. It specifies that there may occur an
exception in the method. It is alwaysused with method
signature.
Java Exception Handling Example
public class
JavaExceptionExample
{
public static void main(String
args[])
{
try
{
// Codethat may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Rest of the
code...");
}
}
Output :
java.lang.ArithmeticException:/by zero
Rest of the code...
Q5. a) What is multithreading? Explain advantages of
multithreading. Describe use of setPriority and getPriority
methods for Java multithreading. Also describe how threads
are synchronized in Java with the help of a program.
Answer : - Multithreadinginjava is a process of executing multiplethreads simultaneously.Threadis basically
a lightweightsub-process, asmallestunitof processing. Multiprocessingandmultithreading, bothare usedto
achievemultitasking.
We usemultithreadingthan multiprocessingbecausethreads sharea commonmemory area. They do not
allocateseparate memory area so saves memory, andcontext-switchingbetween the threads takes less time
than process. JavaMultithreadingis mostly usedingames, animationetc.
Advantages ofJava Multithreading
 It does not block the userbecause threads are independent and youcanperform multipleoperations
at sametime.
 You canperform many operations together so it saves time.
 Threads are independent so it does not affect other threads if exception occurina singlethread.
setPriority()- The setPriority( ) methodof thread class is usedto change the thread's priority. Every thread
has a priority whichis represented by the integer number between 1to 10.
Syntax : public final voidsetPriority(inta)
getPriority()- ThegetPriority( ) methodof thread class is usedto check the priority of the thread. Whenwe
create a thread, ithas somepriority assignedto it. Priority of thread can either be assignedby the JVM or by the
programmer explicitly whilecreatingthethread.
Syntax : public final intgetPriority( )
Thread class provides 3constantproperties :
1. public static intMIN_PRIORITY
2. public static intNORM_PRIORITY
3. public static intMAX_PRIORITY
Defaultpriority of a thread is 5(NORM_PRIORITY). Thevalueof MIN_PRIORITYis 1andthe valueof
MAX_PRIORITYis 10.
Example ofpriority ofa Thread
class PriorityExample extends Thread
{
public void run()
{
System.out.println("running thread priority :
"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
PriorityExample p1=new PriorityExample();
p1.setPriority(Thread.MAX_PRIORITY);
p1.start();
}
}
Output :
running thread name : Thread-0
running thread priority : 10
Java - Thread Synchronization
When we start two or more threads withina program, there may be a situationwhen multiplethreads try to
access thesame resourceand finally they canproduce unforeseenresult due to concurrency issues. For
example, if multiplethreads try to write withina samefilethen they may corrupt the data because one of the
threads can overridedata orwhileone thread is openingthe samefileat the sametimeanother thread might
be closingthesamefile.
So there is a need to synchronizetheactionof multiplethreads and make surethat only onethread canaccess
the resource at a givenpoint intime. This is implementedusingaconceptcalledmonitors. Eachobjectin Javais
associatedwitha monitor, whichathread canlock orunlock. Only onethread at a timemay holda lock ona
monitor.
Javaprogramming language provides a very handy way of creating threads and synchronizingtheirtask by
usingsynchronizedblocks.Youkeepshared resources withinthis block.
Without Synchronization
public class Table
{
//Method notSynchronized
void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e) { System.out.println(e); }
}
}
}
class Thread1 extends Thread
{
Table ob1;
Thread1(Table ob1)
{
this.ob1 = ob1;
}
public void run()
{
ob1.printTable(5);
}
}
class Thread2 extends Thread
{
Table ob1;
Thread2(Table ob1)
{
this.ob1 = ob1;
}
public void run()
{
ob1.printTable(100);
}
}
class TestSynchronization
{
public static void main(String args[])
{
// Only oneObject
Table obj = new Table();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
}
}
Output :
5
100
200
10
300
15
20
400
500
25
With Synchronization
public class Table
{
//Synchronized Method
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e) { System.out.println(e); }
}
}
}
class Thread1 extends Thread
{
Table ob1;
Thread1(Table ob1)
{
this.ob1 = ob1;
}
public void run()
{
ob1.printTable(5);
}
}
class Thread2 extends Thread
{
Table ob1;
Thread2(Table ob1)
{
this.ob1 = ob1;
}
public void run()
{
ob1.printTable(100);
}
}
class TestSynchronization
{
public static void main(String args[])
{
// Only oneObject
Table obj = new Table();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);
t1.start();
t2.start();
}
}
Output :
100
200
300
400
500
5
10
15
20
25
Q5. b) Write program to create an Applet which draw a circle
inside a triangle. Keep color of circle blue and triangle
yellow.
Answer : -
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DrawingExample
extends Applet
{
public void paint(Graphics g)
{
// x coordinatesof vertices
int x[] = { 200, 50, 350 };
// y coordinatesof vertices
int y[] = { 50, 300, 300 };
// Number of vertices
int vertices = 3;
// Create a Polygon with given x, y coordinates
Polygon p = new Polygon(x, y,
vertices);
// Draw a Triangle
g.setColor(Color.yellow);
g.fillPolygon(p);
// Draw a Circle
g.setColor(Color.blue);
g.fillOval(120, 135, 160, 160);
}
}
Q6. a) What is layout manager? Describe use of flow layout
and grid layout with the help of program code.
Answer : - Coming Soon
Q6. b) What is event driven program? Describe different
components of event in Java
Answer : - Coming Soon
Q7. a) Explain use of stream classes in Java. Write a java
program to read the contents of a given file and display it.
Answer : -
JavaStream Class
 ByteStream
1. InputStream
 FileInputStream
 ByteArrayInputStream
 ObjectInputStream
 PipedInputStream
 FilterInputStream
 BufferedInputStream
 DataInputStream
2. OutputStream
 FileOutputStream
 ByteArrayOutputStream
 ObjectOutputStream
 PipedOutputStream
 FilterOutputStream
 BufferedOutputStream
 DataOutputStream
 Character Stream
1. Reader
 BufferedReader
 CharArrayReader
 StringReader
 FilterReader
 InputStreamReader
 FileReader
2. Writer
 BufferedWriter
 CharArrayWriter
 StringWriter
 FilterWriter
 InputStreamWriter
 FileWriter
Read the Contents ofa given File
import java.io.*;
class CopyFile
{
public static void main(String args[])throws
IOException
{
FileInputStream Fread =new
FileInputStream("File1.txt");
int c;
while((c=Fread.read()) != -1)
System.out.print((char)c);
Fread.close();
}
}
Q7. b) Explain use of Socket and DatagramPacket classes.
Answer : - Coming Soon
Q8. a) What is Servlet ? Explain Servlet life cycle. Also explain
use of GET and POST methods of Servlet.
Answer : - Servletcan be describedinmany ways, depending onthe context.
 Servlet is a technology whichis usedto create a web application.
 Servlet is an API that provides many interfaces and classes includingdocumentation.
 Servlet is an interfacethat mustbe implementedforcreating any Servlet.
 Servlet is a class thatextends the capabilities of the servers and responds to the incomingrequests. It
can respondto any requests.
 Servlet is a webcomponentthat is deployedonthe server to create a dynamic webpage.
Servlet Life Cycle
1. Loading Servlet Class -When the WebServer (e.g. Apache Tomcat) starts up, the WebContainer
deploy and loads all theservletclasses.
2. Creating instance ofServlet -Onceall theServlet classes loaded, theWebContainer creates
instances of each servletclass. Theservletinstanceis createdonly onceinthe Servlet LifeCycle.
3. Invoke init() method -Onceall theservletclasses areinstantiated, the init() methodis invoked
for eachinstantiated servlet. This methodinitializes theservlet. Thereare certain initparameters that
youcan specify inthedeploymentdescriptor(web.xml) file. Forexample, if aservlethas value>=0
then its init() methodis immediately invokedduringwebcontainerstartup.
Syntax of the init( ) method is givenbelow:
public voidinit(ServletConfigconfig) throws ServletException
Theinit( ) method is calledonly onceduringthe lifecycleof servlet.
4. Invoke service()method -Eachtime the web serverreceives a request forservlet, itspawns a new
thread that calls service() method. If theservletis GenericServlet thentherequest is served
by the service() methoditself,if theservletis HttpServlet thenservice() methodreceives
the request and dispatches it to the correcthandler method basedon the type of request.
Theservice() methodis calledby thecontainerand servicemethodinvokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So youhavenothing to do with service() methodbutyou
overrideeither doGet() ordoPost()dependingonwhat typeof request youreceivefrom the
client.
Syntax of the service( ) methodis givenbelow:
public voidservice(ServletRequestrequest, ServletResponseresponse) throws ServletException,
IOException
5. Invoke destroy()method -WhenWeb Container shuts down(this usually happens whenwestop the
web server), itunloads all the Servlets and calls destroy() methodforeachinitializedServlets.
Syntax of the destroy( ) method is givenbelow:
public voiddestroy( )
GETMethod
TheGET methodsends the encodeduser informationappended to the page request. The page and the encoded
informationare separated by the ? (questionmark) symbol as follows−
http://www.questionsolves.com/Test?firstname=AMIT&lastname=DAS
TheGET methodis the default method to pass informationfrom browserto web serverand itproduces a long
string that appears in yourbrowser's Locationbox. Neverusethe GET methodif youhavepasswordor other
sensitiveinformationto pass to the server. The GET method has sizelimitation:only 1024characters canbe
usedin a request string.
This informationis passedusingQUERY_STRING headerand will beaccessiblethroughQUERY_STRING
environmentvariableand Servlet handles this type of requests usingdoGet() method.
POSTMethod
A generally morereliablemethod of passinginformationto a backend program is the POST method. This
packages the informationinexactly the sameway as GET method, but instead of sendingit as a text string after
a ? (questionmark) in the URL it sends it as a separate message. This messagecomes to thebackendprogram
inthe form of the standard inputwhichyoucan parse and usefor yourprocessing. Servlethandles this typeof
requests usingdoPost()method.
Servlets handles form data parsing automatically usingthefollowingmethods dependingonthe situation−
 getParameter()− Youcall request.getParameter() method to get the valueof a form parameter.
 getParameterValues()− Call this methodif the parameter appears more than once and returns
multiplevalues, forexamplecheckbox.
 getParameterNames()− Call this methodif youwant a completelistof all parameters in the current
request.
Q8. b) What is JDBC? Explain how connection is established in
JDBC.
Answer : - JDBCstands forJava DatabaseConnectivity. JDBCis aJavaAPI to connectand execute the query
withthe database. It is apart of JavaSE (Java Standard Edition). JDBCAPIuses JDBCdrivers to connectwiththe
database. There are four types of JDBCdrivers :
JDBC-ODBC Bridge Driver
TheJDBCType1 driver converts JDBCmethodcalls into ODBCfunctioncalls. Thebridgeis usually usedwhen
there is no pure-Java driver availableforaparticular database. Thedriver is implementedinthe
sun.jdbc.odbc.JdbcOdbcDriverclass andcomes withtheJava2 SDK, Standard Edition.
Advantages
 Almostany database forwhichODBCdriveris installed, canbeaccessed.
Disadvantages
 Performance degraded becauseJDBCmethod call is convertedinto the ODBCfunction calls.
 TheODBCdriverneeds to be installedonthe clientmachine.
Native-API Driver
TheNativeAPI driver uses the client-sidelibraries of thedatabase. The driverconverts JDBCmethodcalls into
nativecalls of the database API. It is not written entirely injava.
Advantages
 Better performancethan Type1sinceno jdbc to odbc translationis needed.
Disadvantages
 Thevendor clientlibrary needs to be installedonthe clientmachine.
 Cannot be used ininternet due the clientsidesoftwareneeded. (That means the Nativedriver needs to
be installedonthe each clientmachine)
 Notall databases givethe clientsidelibrary.
Net-Protocol Driver
TheNet-Protocol driveruses middleware(applicationserver) that converts JDBCcalls directly orindirectly
into the vendor-specific databaseprotocol. Itis fully writteninjava.
Advantages
 No clientsidelibrary is required becauseof applicationserverthat canperform many tasks like
auditing, loadbalancing, loggingetc.
 Can be used ininternet sincethere is no clientsidesoftware needed.
Disadvantages
 Requires database-specific codingto be done inthe middletier.
 Maintenanceof Network Protocol driverbecomes costly becauseitrequires database-specific coding
to be done inthe middletier.
Native-Protocol Driver
TheNative-protocol driverconverts JDBCcalls directly into thevendor-specific databaseprotocol. Itis fully
written in Javalanguage and installedinsidethe JavaVirtual Machineof the client.
Advantages
 Better performancethan all other drivers.
 No software is required at clientsideorserver side.
Disadvantages
 At clientside, aseparate driveris needed foreach database.
Q8. c) What is RMI? Explain RMI architecture.
Answer : - TheRMI(Remote MethodInvocation) is anAPI that provides amechanism to create distributed
applicationinjava. The RMIallows anobject to invokemethods onan object running in another JVM.
TheRMI provides remotecommunicationbetweenthe applications usingtwo objects stuband skeleton. RMI
uses stuband skeletonobject for communicationwiththeremoteobject. A remote objectis an object whose
method canbe invokedfrom another JVM.
 Stub -The stubis an object, acts as a gateway for the clientside. All theoutgoing requests are routed
through it. It resides at the clientsideand represents the remote object.
 Skeleton -Theskeletonis an object, acts as a gateway for the serversideobject. All the incoming
requests are routed through it.
Understanding requirements for the Distributed Applications
If any applicationperforms these tasks, itcanbe distributedapplication.
 Theapplicationneed to locatethe remote method
 It need to providethe communicationwiththeremote objects, and
 Theapplicationneed to loadthe class definitions fortheobjects.
TheRMI applicationhaveall thesefeatures, so it is calledthedistributed application.

More Related Content

Mcs 024 assignment solution (2020-21)

  • 1. BCA 4TH SEMESTER MCS-024 ASSIGNMENTSOLUTION (2020-21) Q1. a) What is Object Oriented Programming (OOP)? Explain its advantages. Also describe concept of data hidingin OOP. Answer : - Object-OrientedProgramming is amethodology orparadigm to designa program usingclasses and objects. It simplifies thesoftwaredevelopmentandmaintenance by providingsomeconcepts :  Object -Any entity that has state and behavioris knownas an object. An Objectcan be definedas an instanceof aclass.  Class - Collectionof objects is calledclass. Itis alogical entity. Aclass canalso bedefinedas a blueprint from whichyoucancreate an individual object. Class doesn'tconsumeany space.  Inheritance -Whenoneobject acquires all the properties and behaviors of a parent object, it is knownas inheritance.  Polymorphism -If one task is performedby different ways, itis knownas polymorphism. InJava, we usemethod overloadingand methodoverridingto achievepolymorphism.  Abstraction -Hidinginternal details and showingfunctionality is knownas abstraction. InJava, we useabstract class andinterface to achieveabstraction.  Encapsulation -Binding(orwrapping) codeand data together into a singleunit are knownas encapsulation. Ajava class is theexampleof encapsulation. Javabeanis the fully encapsulatedclass becauseall the data members are private here. Advantage ofObject Oriented ProgrammingSystem(OOPs) -  OOPs makes development andmaintenanceeasier whereas ina procedure-oriented programming language it is not easy to manage if codegrows as project sizeincreases.  OOPs provides datahidingwhereas ina procedure-oriented programminglanguage a global data can be accessedfrom anywhere.  OOPs provides theability to simulatereal-worldeventmuchmoreeffectively. Wecanprovidethe solutionof real word problem if we are usingthe Object-Oriented Programminglanguage. Data Hiding - Data hidingis asoftware developmenttechniquespecifically usedinobject-oriented programming(OOP) to hide internal object details (data members). Datahidingensures exclusivedataaccess to class members andprotects object integrity by preventing unintended or intended changes. Data hidingalso reduces system complexity forincreasedrobustness by limitinginterdependencies between software components. Q1. b) Explain different data types available in Java. Answer : - In Javadata types are dividedinto two groups :  Primitivedata types - includes byte, short, int, long, float, double, booleanandchar  Non-primitivedatatypes - suchas String, Arrays and Classes
  • 2. Primitive Data Types Data Type Size Description and Example byte 1 bytes Stores whole numbersfrom -128 to 127 Example: byte a = 10, byte b = -20; short 2 bytes Stores whole numbersfrom -32,768 to 32,767 Example: short s = 10000, shortr = -5000; int 4 bytes Stores whole numbersfrom -2,147,483,648to 2,147,483,647 Example: int a = 100000, intb= -200000; long 8 bytes Stores whole numbersfrom -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Note that you should end the valuewith an "L". Example: long a = 100000L, longb= -200000L; float 4 bytes Stores fractional numbers. Sufficientfor storing6 to 7 decimal digits Note that you should end the valuewith an "f": Example: float x = 234.5f; double 8 bytes Stores fractional numbers. Sufficientfor storing15 decimal digits Example: doubley = 12.3; boolean 1 bit Stores true or false values Example: char letter = 'A'; char 2 bytes Stores a single character/letter or ASCII values Example: Boolean b = false; Non-Primitive Data Types Non-primitivedatatypes are calledreference types becausethey refer to objects. Themain differencebetween primitiveandnon-primitivedatatypes are :  Primitivetypes are predefined (already defined) inJava. Non-primitivetypes arecreated by the programmer and is not definedby Java (except for String).  Non-primitivetypes canbeused to call methods to perform certain operations, whileprimitivetypes cannot.  A primitivetypehas always avalue, whilenon-primitivetypes canbenull.
  • 3. String -The String data type is usedto store a sequenceof characters (text). String values must besurrounded by doublequotes : Example - String message= "Hello World"; Q1. c) Describe features of Java programming language. Answer : - Theprimary objectiveof Java programminglanguage creationwas to make itportable, simpleand secureprogramming language. Apart from this, there are also someexcellentfeatures whichplay animportant rolein the popularity of this language. A listof mostimportantfeatures of Javalanguage is givenbelow.  Simple -Javais very easy to learn, and its syntax is simple, cleanandeasy to understand.  Object-Oriented -Javais anobject-oriented programming language. Everything inJava is an object. Object-oriented means we organize oursoftware as a combinationof different types of objects that incorporates both data and behavior. Basic concepts of OOPs are: o Object o Class o Inheritance o Polymorphism o Abstraction o Encapsulation  Platform Independent-Javacodeis compiledby thecompilerandconvertedinto bytecode. This bytecodeis a platform-independent codebecauseit can be run onmultipleplatforms, i.e., WriteOnce and Run Anywhere(WORA).  Secured -Javais best knownforits security. WithJava, wecan developvirus-freesystems. Javais securedbecause : o No explicit pointer o Java Programs run inside a virtual machinesandbox o Classloader : ClassloaderinJavais a part of the JavaRuntimeEnvironment(JRE) whichis usedto loadJava classes into theJavaVirtual Machinedynamically. Itadds security by separating the package for the classes of thelocal filesystem from thosethatare imported from network sources. o Bytecode Verifier : It checks the codefragments forillegal codethat canviolateaccess right to objects. o Security Manager : Itdetermines what resources a class canaccess suchas readingand writing to the local disk.  Robust -Robustsimply means strong. Javais robustbecause: o It uses strong memory management. o There is a lack of pointers that avoids security problems. o There is automatic garbage collectioninjava whichruns onthe JavaVirtual Machineto get rid of objects whichare not being usedby a Javaapplicationanymore. o There are exception handlingand the typecheckingmechanism inJava. All thesepoints make Javarobust.  Architecture Neutral -Javais architectureneutral becausethere are no implementationdependent features, forexample, the sizeof primitivetypes is fixed.  Portable -Java is portablebecause itfacilitates youto carry the Javabytecodeto any platform. It doesn't require any implementation.  Distributed -Javais distributedbecauseitfacilitates users to create distributedapplications inJava. RMIand EJB are used forcreating distributed applications. This featureof Javamakes us able to access files by callingthemethods from any machineon the internet.  Multithreaded-Athread is likea separate program, executing concurrently. Wecanwrite Java programs that deal withmany tasks at onceby definingmultiplethreads. Themainadvantage of multi-threading is that itdoesn't occupy memory foreachthread. It shares a commonmemory area.
  • 4.  Dynamic -Java is adynamic language. It supports dynamic loadingof classes.Itmeans classes are loadedon demand. Q2. a) What is a class? Define a class in Java and with the help of that class describe meaning of data members and member functions. Also describe use of different types of access spcifiers available in Java. Answer : -  A Class is auser defineddata-type whichhavedata members and member functions.  Data members are the data variables andmember functions arethe functions usedto manipulate these variables andtogether these data members and memberfunctions defines the properties and behaviorof the objects ina Class.  A class is likeablueprintforan object. class Student { //Data Members private int id; private String name; //Member Functions public static void main(String args[]) { id=10; name="Debabrata"; System.out.println(id + "t" + name); } } There are 4 types of access spcifiers inJava:  private -The privateaccess modifieris accessibleonly withinclass.  default -If youdon't useany modifier, itis treated as defaultbydefault. Thedefault modifieris accessibleonly withinpackage.  protected -Theprotected access modifieris accessiblewithinpackageandoutsidethe package but through inheritance only.  public -The public access modifieris accessibleeverywhere. Ithas the widestscopeamongall other modifiers.
  • 5. Q2. b) Describe advantages of abstract method. Write a java program to create a Shape class with an abstract method Find_Area( ). Inherit Circle and Rectangle classes from Shape class. Implement Find_Area( ) method in derived classes. Make necessary assumptions. Answer : - Amethod whichis declaredas abstract and does nothave implementationis knownas an abstract method. Example : abstract voidprintStatus( ); // No MethodBody If a class includes abstractmethods, thenthe class itself mustbedeclared abstract. Abstractionis a process of hidingthe implementationdetails andshowingonly functionality to theuser. Another way, it shows only essential things to theuser and hides the internal details, forexample, sendingSMS where youtype the text and sendthe message. Youdon't knowthe internal processingaboutthe message delivery. public abstract class Shape { // Abstract Method abstract void Find_Area(); } import java.io.*; public class Circle extends Shape { private double radius; // Inputthe valueof Radiusfrom the User void Input()throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the value of Radius ..."); radius = Double.parseDouble(br.readLine()); } // Calculate the area of a Circle based on given Input void Find_Area() {
  • 6. double area = 3.14 * radius * radius; System.out.println("Area of the Circle is = " + area); } } import java.io.*; public class Rectangle extends Shape { private double length; private double breadth; // Inputthe valueof Length and Breadth from the User void Input()throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the value of Length ..."); length = Double.parseDouble(br.readLine()); System.out.println("Enter the value of Breadth ..."); breadth = Double.parseDouble(br.readLine()); } // Calculate the area of a Rectangle based on given Input void Find_Area() { double area = length * breadth; System.out.println("Area of the Rectangle is = " + area); } } import java.io.*; public class CallMethod { public static void main(String args[])throws IOException { Circle ob1 = new Circle(); Rectangle ob2 = new Rectangle();
  • 7. // Calculate the Area of a Circle ob1.Input(); ob1.Find_Area(); // Calculate the Area of a Rectangle ob2.Input(); ob2.Find_Area(); } } Output : Enter the valueof Radius... 10.5 Area of the Circle is = 346.185 Enter the valueof Length ... 20 Enter the valueof Breadth ... 10 Area of the Rectangle is = 200. Q3. a) Explain use(s) of following keywords of Java with the help of program/example. i. final ii. finally iii. super Answer : - final Keyword  Final is a keywordornon-access modifierinjava.  It can be apply withclass, variables, andmethods.  If youmakeany class as final class thenyoucannotinherit(extends) this class. If youmakeany variableas final variablethen youcannot change the valueof this variableafter initialization. If you makeany methodas final methodthen youcannot overridethis method.  If we declarefinal variablealongwith static keywordwill becomeaconstants. Example : class Speed { //final variable
  • 8. final int speedlimit=90; void run() { speedlimit=400; } public static void main(String args[]) { Speed obj=new Speed(); obj.run(); } } Output : CompileTimeError finally Keyword -  Thefinally keywordis usedto create a block of codethat follows atry block.  Javafinally block of codeis usedto execute important codesuchas closingconnection, stream etc.  Javafinally block is alwaysexecutedwhether exception is handledor not. Example : class TestFinallyBlock { public static void main(String args[]) { try { int n=5/0; System.out.println("Answer = " + n); } catch(Exception e) { System.out.println(e); } finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } Output :
  • 9. java.lang.ArithmeticException: / by zero finally block is alwaysexecuted rest of the code... super Keyword -We canuse superkeywordto access the data member and methods of parent class. Itis used if parent class andchildclass havesamemethods orvariables. Example : //Parent Class class Base { int fact; void Factorial(int n) { fact=1; for(int i=1;i<=n;i++) fact=fact*i; } } //Child Class class Derived extends Base { void Factorial(int n) { //Call the OverridingMethod of ParentClass super.Factorial(n); System.out.println("Factorial = "+super.fact); } } Q3. b) What is interface? How interface is different from abstract class? Write a program in Java to explain how interfaces are implemented. Answer : - Likea class, aninterfacecan havemethods and variables, butthe methods declared ininterface are by default abstract (only methodsignature, no body). Interfaces specify whata class mustdo andnot how. A class thatis declared withabstract keyword, is knownas abstract class injava. It canhave abstract and non- abstract methods (methodwith body). Methodthat are declared withoutany body withinan abstract class are calledabstract method. Themethod body will bedefinedby its subclass. Abstractmethodcannever be final and static. Any class thatextends an abstract class mustimplementall theabstractmethods declared by the super class.
  • 10. Abstract Class Interface Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Abstract class doesn'tsupport multipleinheritance. Interface supportsmultiple inheritance. Abstract class can have final, non- final, static and non-static variables. Interface has only static and final variables. Abstract class can providethe implementation of interface. Interface can'tprovidethe implementation of abstract class. An abstract class can extend another Javaclass and implementmultiple Javainterfaces. An interface can extend another Java interface only. A Javaabstract class can have class memberslike private, protected, etc. Membersof a Javainterface are public by default. Java Interface Example interface Bank { double RateOfInterest(); double ATMcharges(); } class SBI implements Bank { public double RateOfInterest() { return 6.2; } public double ATMcharges() { return 100.0; } } class RBL implements Bank { public double RateOfInterest() { return 6.8; } } class InterestCheck { public static void main(String args[]) {
  • 11. Bank ob1=new SBI(); System.out.println("SBI Interest Rate = " + ob1.RateOfInterest()); System.out.println("SBI ATM Charges = " + ob1.ATMcharges()); Bank ob2=new RBL(); System.out.println("RBL Interest Rate = " + ob2.RateOfInterest()); } } Q4. a) What is polymorphism? Explain use of polymorphism in java programming. Answer : - PolymorphisminJavais aconceptby whichwe canperform a singleactionindifferent ways. There are two types of polymorphisminJava:compile-timepolymorphismandruntimepolymorphism. Run timePolymorphism alsoknownas methodoverriding. Methodoverridingmeans havingtwo or more methods withthe samename, samesignature but with different implementation. CompiletimePolymorphism also knownas methodoverloading. Methodoverloadingmeans havingtwo or moremethods with the samename but withdifferent signatures. Example ofPolymorphism class Bank { double getRateOfInterest() { return 0.0; } } class SBI extends Bank { double getRateOfInterest() { return 6.2; } } class ICICI extends Bank { double getRateOfInterest() { return 6.8; } } class AXIS extends Bank { double getRateOfInterest() { return 6.5; }
  • 12. } class TestPolymorphism { public static void main(String args[]) { Bank b; b=new SBI(); System.out.println("SBI Interest Rate = " + b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Interest Rate = " + b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Interest Rate = " + b.getRateOfInterest()); } } Q4. b) What is exception? What are different types of exceptions? Explain need of exceptions handling with the help of a program. Answer : - Exceptions are events that occurduring the execution of programs that distrupthe normal flowof instructions (example-divideby zero, array access outof bound, etc.). In Java, an exception is anobject that wraps an error event that occurred withina methodand contains :  Informationabout the error includingits type  Thestate of the program when the error occurred  Optionally, othercustom information Different Types ofJava Exceptions  ArithmeticException If we divideany numberby zero, there occurs an ArithmeticException. int a = 50/0; //ArithmeticException  NullPointerException If we havea null valueinany variable, performingany operation onthe variablethrows a NullPointerException.
  • 13. String s = null; System.out.println(s.length()); //NullPointerException  NumberFormatException Thewrong formatting of any valuemay occurNumberFormatException. SupposeI havea string variablethat has characters, convertingthis variableinto digitwill occurNumberFormatException. String s = "abc"; int i=Integer.parseInt(s); //NumberFormatException  ArrayIndexOutOfBoundsException If youare insertingany valueinthe wrong index, itwouldresult inArrayIndexOutOfBoundsException as shownbelow: int a[ ] = new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException There are 5 keywords whichareused inhandling exceptions inJava. Keyword Description try The "try" keyword isused to specify a block where we should place exception code. The try block mustbe followed by either catch or finally. It means, wecan't usetry block alone. catch The "catch" block is used to handlethe exception. It mustbe preceded by try block which meanswe can'tuse catch block alone. It can be followed by finally block later. finally The "finally"block is used to execute the importantcode of the program. It is executed whether an exception is handled or not. throw The "throw" keyword isused to throw an exception. throws The "throws" keyword isused to declareexceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is alwaysused with method signature. Java Exception Handling Example public class JavaExceptionExample
  • 14. { public static void main(String args[]) { try { // Codethat may raise exception int data=100/0; } catch(ArithmeticException e) { System.out.println(e); } System.out.println("Rest of the code..."); } } Output : java.lang.ArithmeticException:/by zero Rest of the code... Q5. a) What is multithreading? Explain advantages of multithreading. Describe use of setPriority and getPriority methods for Java multithreading. Also describe how threads are synchronized in Java with the help of a program. Answer : - Multithreadinginjava is a process of executing multiplethreads simultaneously.Threadis basically a lightweightsub-process, asmallestunitof processing. Multiprocessingandmultithreading, bothare usedto achievemultitasking. We usemultithreadingthan multiprocessingbecausethreads sharea commonmemory area. They do not allocateseparate memory area so saves memory, andcontext-switchingbetween the threads takes less time than process. JavaMultithreadingis mostly usedingames, animationetc. Advantages ofJava Multithreading  It does not block the userbecause threads are independent and youcanperform multipleoperations at sametime.  You canperform many operations together so it saves time.  Threads are independent so it does not affect other threads if exception occurina singlethread.
  • 15. setPriority()- The setPriority( ) methodof thread class is usedto change the thread's priority. Every thread has a priority whichis represented by the integer number between 1to 10. Syntax : public final voidsetPriority(inta) getPriority()- ThegetPriority( ) methodof thread class is usedto check the priority of the thread. Whenwe create a thread, ithas somepriority assignedto it. Priority of thread can either be assignedby the JVM or by the programmer explicitly whilecreatingthethread. Syntax : public final intgetPriority( ) Thread class provides 3constantproperties : 1. public static intMIN_PRIORITY 2. public static intNORM_PRIORITY 3. public static intMAX_PRIORITY Defaultpriority of a thread is 5(NORM_PRIORITY). Thevalueof MIN_PRIORITYis 1andthe valueof MAX_PRIORITYis 10. Example ofpriority ofa Thread class PriorityExample extends Thread { public void run() { System.out.println("running thread priority : "+Thread.currentThread().getPriority()); } public static void main(String args[]) { PriorityExample p1=new PriorityExample(); p1.setPriority(Thread.MAX_PRIORITY); p1.start(); } } Output : running thread name : Thread-0 running thread priority : 10 Java - Thread Synchronization When we start two or more threads withina program, there may be a situationwhen multiplethreads try to access thesame resourceand finally they canproduce unforeseenresult due to concurrency issues. For example, if multiplethreads try to write withina samefilethen they may corrupt the data because one of the threads can overridedata orwhileone thread is openingthe samefileat the sametimeanother thread might be closingthesamefile.
  • 16. So there is a need to synchronizetheactionof multiplethreads and make surethat only onethread canaccess the resource at a givenpoint intime. This is implementedusingaconceptcalledmonitors. Eachobjectin Javais associatedwitha monitor, whichathread canlock orunlock. Only onethread at a timemay holda lock ona monitor. Javaprogramming language provides a very handy way of creating threads and synchronizingtheirtask by usingsynchronizedblocks.Youkeepshared resources withinthis block. Without Synchronization public class Table { //Method notSynchronized void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(500); } catch(Exception e) { System.out.println(e); } } } } class Thread1 extends Thread { Table ob1; Thread1(Table ob1) { this.ob1 = ob1; } public void run() { ob1.printTable(5); } }
  • 17. class Thread2 extends Thread { Table ob1; Thread2(Table ob1) { this.ob1 = ob1; } public void run() { ob1.printTable(100); } } class TestSynchronization { public static void main(String args[]) { // Only oneObject Table obj = new Table(); Thread1 t1=new Thread1(obj); Thread2 t2=new Thread2(obj); t1.start(); t2.start(); } } Output : 5 100 200 10 300 15 20 400 500 25 With Synchronization
  • 18. public class Table { //Synchronized Method synchronized void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(500); } catch(Exception e) { System.out.println(e); } } } } class Thread1 extends Thread { Table ob1; Thread1(Table ob1) { this.ob1 = ob1; } public void run() { ob1.printTable(5); } } class Thread2 extends Thread { Table ob1; Thread2(Table ob1) { this.ob1 = ob1; } public void run() { ob1.printTable(100);
  • 19. } } class TestSynchronization { public static void main(String args[]) { // Only oneObject Table obj = new Table(); Thread1 t1=new Thread1(obj); Thread2 t2=new Thread2(obj); t1.start(); t2.start(); } } Output : 100 200 300 400 500 5 10 15 20 25 Q5. b) Write program to create an Applet which draw a circle inside a triangle. Keep color of circle blue and triangle yellow. Answer : - import java.applet.*; import java.awt.*; import java.awt.event.*; public class DrawingExample extends Applet
  • 20. { public void paint(Graphics g) { // x coordinatesof vertices int x[] = { 200, 50, 350 }; // y coordinatesof vertices int y[] = { 50, 300, 300 }; // Number of vertices int vertices = 3; // Create a Polygon with given x, y coordinates Polygon p = new Polygon(x, y, vertices); // Draw a Triangle g.setColor(Color.yellow); g.fillPolygon(p); // Draw a Circle g.setColor(Color.blue); g.fillOval(120, 135, 160, 160); } } Q6. a) What is layout manager? Describe use of flow layout and grid layout with the help of program code. Answer : - Coming Soon Q6. b) What is event driven program? Describe different components of event in Java Answer : - Coming Soon Q7. a) Explain use of stream classes in Java. Write a java program to read the contents of a given file and display it. Answer : -
  • 21. JavaStream Class  ByteStream 1. InputStream  FileInputStream  ByteArrayInputStream  ObjectInputStream  PipedInputStream  FilterInputStream  BufferedInputStream  DataInputStream 2. OutputStream  FileOutputStream  ByteArrayOutputStream  ObjectOutputStream  PipedOutputStream  FilterOutputStream  BufferedOutputStream  DataOutputStream  Character Stream 1. Reader  BufferedReader  CharArrayReader  StringReader  FilterReader  InputStreamReader  FileReader 2. Writer  BufferedWriter  CharArrayWriter  StringWriter  FilterWriter  InputStreamWriter  FileWriter Read the Contents ofa given File import java.io.*; class CopyFile { public static void main(String args[])throws IOException { FileInputStream Fread =new FileInputStream("File1.txt"); int c; while((c=Fread.read()) != -1) System.out.print((char)c); Fread.close(); } }
  • 22. Q7. b) Explain use of Socket and DatagramPacket classes. Answer : - Coming Soon Q8. a) What is Servlet ? Explain Servlet life cycle. Also explain use of GET and POST methods of Servlet. Answer : - Servletcan be describedinmany ways, depending onthe context.  Servlet is a technology whichis usedto create a web application.  Servlet is an API that provides many interfaces and classes includingdocumentation.  Servlet is an interfacethat mustbe implementedforcreating any Servlet.  Servlet is a class thatextends the capabilities of the servers and responds to the incomingrequests. It can respondto any requests.  Servlet is a webcomponentthat is deployedonthe server to create a dynamic webpage. Servlet Life Cycle 1. Loading Servlet Class -When the WebServer (e.g. Apache Tomcat) starts up, the WebContainer deploy and loads all theservletclasses. 2. Creating instance ofServlet -Onceall theServlet classes loaded, theWebContainer creates instances of each servletclass. Theservletinstanceis createdonly onceinthe Servlet LifeCycle. 3. Invoke init() method -Onceall theservletclasses areinstantiated, the init() methodis invoked for eachinstantiated servlet. This methodinitializes theservlet. Thereare certain initparameters that youcan specify inthedeploymentdescriptor(web.xml) file. Forexample, if aservlethas value>=0 then its init() methodis immediately invokedduringwebcontainerstartup. Syntax of the init( ) method is givenbelow: public voidinit(ServletConfigconfig) throws ServletException Theinit( ) method is calledonly onceduringthe lifecycleof servlet. 4. Invoke service()method -Eachtime the web serverreceives a request forservlet, itspawns a new thread that calls service() method. If theservletis GenericServlet thentherequest is served by the service() methoditself,if theservletis HttpServlet thenservice() methodreceives the request and dispatches it to the correcthandler method basedon the type of request. Theservice() methodis calledby thecontainerand servicemethodinvokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So youhavenothing to do with service() methodbutyou overrideeither doGet() ordoPost()dependingonwhat typeof request youreceivefrom the client. Syntax of the service( ) methodis givenbelow: public voidservice(ServletRequestrequest, ServletResponseresponse) throws ServletException, IOException
  • 23. 5. Invoke destroy()method -WhenWeb Container shuts down(this usually happens whenwestop the web server), itunloads all the Servlets and calls destroy() methodforeachinitializedServlets. Syntax of the destroy( ) method is givenbelow: public voiddestroy( ) GETMethod TheGET methodsends the encodeduser informationappended to the page request. The page and the encoded informationare separated by the ? (questionmark) symbol as follows− http://www.questionsolves.com/Test?firstname=AMIT&lastname=DAS TheGET methodis the default method to pass informationfrom browserto web serverand itproduces a long string that appears in yourbrowser's Locationbox. Neverusethe GET methodif youhavepasswordor other sensitiveinformationto pass to the server. The GET method has sizelimitation:only 1024characters canbe usedin a request string. This informationis passedusingQUERY_STRING headerand will beaccessiblethroughQUERY_STRING environmentvariableand Servlet handles this type of requests usingdoGet() method. POSTMethod A generally morereliablemethod of passinginformationto a backend program is the POST method. This packages the informationinexactly the sameway as GET method, but instead of sendingit as a text string after a ? (questionmark) in the URL it sends it as a separate message. This messagecomes to thebackendprogram inthe form of the standard inputwhichyoucan parse and usefor yourprocessing. Servlethandles this typeof requests usingdoPost()method. Servlets handles form data parsing automatically usingthefollowingmethods dependingonthe situation−  getParameter()− Youcall request.getParameter() method to get the valueof a form parameter.  getParameterValues()− Call this methodif the parameter appears more than once and returns multiplevalues, forexamplecheckbox.  getParameterNames()− Call this methodif youwant a completelistof all parameters in the current request. Q8. b) What is JDBC? Explain how connection is established in JDBC. Answer : - JDBCstands forJava DatabaseConnectivity. JDBCis aJavaAPI to connectand execute the query withthe database. It is apart of JavaSE (Java Standard Edition). JDBCAPIuses JDBCdrivers to connectwiththe database. There are four types of JDBCdrivers : JDBC-ODBC Bridge Driver
  • 24. TheJDBCType1 driver converts JDBCmethodcalls into ODBCfunctioncalls. Thebridgeis usually usedwhen there is no pure-Java driver availableforaparticular database. Thedriver is implementedinthe sun.jdbc.odbc.JdbcOdbcDriverclass andcomes withtheJava2 SDK, Standard Edition. Advantages  Almostany database forwhichODBCdriveris installed, canbeaccessed. Disadvantages  Performance degraded becauseJDBCmethod call is convertedinto the ODBCfunction calls.  TheODBCdriverneeds to be installedonthe clientmachine. Native-API Driver TheNativeAPI driver uses the client-sidelibraries of thedatabase. The driverconverts JDBCmethodcalls into nativecalls of the database API. It is not written entirely injava.
  • 25. Advantages  Better performancethan Type1sinceno jdbc to odbc translationis needed. Disadvantages  Thevendor clientlibrary needs to be installedonthe clientmachine.  Cannot be used ininternet due the clientsidesoftwareneeded. (That means the Nativedriver needs to be installedonthe each clientmachine)  Notall databases givethe clientsidelibrary. Net-Protocol Driver TheNet-Protocol driveruses middleware(applicationserver) that converts JDBCcalls directly orindirectly into the vendor-specific databaseprotocol. Itis fully writteninjava.
  • 26. Advantages  No clientsidelibrary is required becauseof applicationserverthat canperform many tasks like auditing, loadbalancing, loggingetc.  Can be used ininternet sincethere is no clientsidesoftware needed. Disadvantages  Requires database-specific codingto be done inthe middletier.  Maintenanceof Network Protocol driverbecomes costly becauseitrequires database-specific coding to be done inthe middletier. Native-Protocol Driver TheNative-protocol driverconverts JDBCcalls directly into thevendor-specific databaseprotocol. Itis fully written in Javalanguage and installedinsidethe JavaVirtual Machineof the client.
  • 27. Advantages  Better performancethan all other drivers.  No software is required at clientsideorserver side. Disadvantages  At clientside, aseparate driveris needed foreach database. Q8. c) What is RMI? Explain RMI architecture. Answer : - TheRMI(Remote MethodInvocation) is anAPI that provides amechanism to create distributed applicationinjava. The RMIallows anobject to invokemethods onan object running in another JVM. TheRMI provides remotecommunicationbetweenthe applications usingtwo objects stuband skeleton. RMI uses stuband skeletonobject for communicationwiththeremoteobject. A remote objectis an object whose method canbe invokedfrom another JVM.  Stub -The stubis an object, acts as a gateway for the clientside. All theoutgoing requests are routed through it. It resides at the clientsideand represents the remote object.  Skeleton -Theskeletonis an object, acts as a gateway for the serversideobject. All the incoming requests are routed through it. Understanding requirements for the Distributed Applications If any applicationperforms these tasks, itcanbe distributedapplication.  Theapplicationneed to locatethe remote method  It need to providethe communicationwiththeremote objects, and  Theapplicationneed to loadthe class definitions fortheobjects.
  • 28. TheRMI applicationhaveall thesefeatures, so it is calledthedistributed application.