ACOMPLETE TU SOLUTION
&PRACTICE SETS
[Link]. CSIT (VII Semester)
Al ects
Features FOR
New Syllabus
Model Questions-Answers
TU Questions-Answers
Model Questions Secs
2079
CONTENTIS
Advanced Java Programming (CSC409) 1-46
New Syllabus *i.. . .. .
Model Questions-Answers.. sssdsn. ..***** ***********"****""""**********************.3
TU Questions-Answers 2078. * ************** *****
******. LZ
Model Questions Sets For Practice
SET 1..... **********"***°°***
******* 39 SET 2..****°'***************° ***********..40
SET 3... ********** SET 4. 42
SET 5.. 43 SET 6...*****°*** 43
SET 7...
************** ************** °*o*****o**** 44 SET 8...
* *********°****°******"*°**************
45
Principles of Management (CSC411) 47-100
New Syllabus... *****" 47
Model Questions-Answers 49
TUQuestions-Answers 2078 75
Model Questions Sets For Practice
SET 1... *********
**..94
SET 2....... 5
SET 3...
**** * * * * * * *
.96
. SET 4... .97
SET 5...
O....e******* ..97 SET 6... 98
SET 7. * * . .99 SET 8... * * * * * * * * * 100
Network Security (CSC416) 101-130
New Syllabus... *************************************
101
Model Questions-Answers. ***** ************** ********** ***
103
TU Questions-Answers 2078.. ******* **** ***°**
114
Model Questions Sets For Practice
SET 1. * * * * * * * *
... 126 SET 2...****" 127
SET 3... ************ * * * * * * * * * * * * * * * * * * * .127 SET 4..***** 128
SET 5.. *** ***
.128 SET 6... 129
SET 7...
************* * * * * *
..129 SET 8. ***********
* * * * * *
. . 130
Data Warehousing and
Data Mining (CSC 410) 131-176
************ ***
************ 131
New Syllabus. ************ **********
Model Questions-Answers.. ************** *******"*******.. 133
2078.. ****** ***************ev 153
TU Questions-Answers
For Practice
Model Questions Sets
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
.170
* * * * * *
SET 2.. ***********"
.171
SET 1..
SET ********************************
...172 SET 4.... ************************** .173
SET ****************************** *****
...173 SET 6.. **************. .174
SET ***************************************°***
...175 SET 8.. ********** .176
.....
Software Project Management (CSC 415) 177-207
New Syllabus . .********************* 177
Model Questions-Answers. ********** ********* 179
TU Questions-Answers 2078...******** . 193
Model Questions Sets For Practice
SET 1.************************* ***** ..202 SET 2. *************** 203
SET 3..
*******************************************
....204 SET 4. 204
SET 5.. *********************************.205 SET 6. 205
SET 7.. ******
** ** ************** .206 SET 8.. .207
Advaneed Java Programming
New Syllabus
Full Marks:60+ 20+20
Course Title:
Advanced Java Programming
Course No: CSC409 Pass Marks: 24 +8+8
+Lab Credit Hrs.:3
Nature of the Course: Theory
Semester: VIlI
well
familiarizes students with basic
as as
This course
Course Description: to GUI and event-
Emphasis will be given
advanced features of Java Programming Servlets and
Database Connectivity, Socket Programming,
drivenprogramming
and Distributed Programming.
SP Technology,
Course Objectives
of this course is to
The main objective
Introduce basic concepts of Java Programming.
GUI programming and JDBC
Exemplify the concept of and servlet and JSP
Demonstrate socket
remote
programming. objects,
Technology
Course Contents (8)
Unit 1: Programming
in Java (8 Hrs.)
Path and Class Path variables, Sample
Architecture, Java Buzzwords,
1.1. Java
and Running Java Programs.
Java Program, Compiling Overloading, Access Privileges,
for each loop, Class and Object, Inheritance,
1.2 Arrays, and Static Modifiers, Packages,
Final
Interface, Inner Class,
Overriding. Throws, and Throw keywords,
1.3. Handling Exceptions: Try, Catch, Finally,
Creating Exception Class.
Writing
Multithreaded Programs,
Introduction, Thread States,
1.4. Concurrency: Thread Priorities
Thread Synchronization,
Thread Properties, Classes, Random
Stream Classes, Character Stream
1.5. Working with Files: Byte
File, Reading and Writing Objects. (10 Hrs.)
Access (10)
with Swing Life
Interface Components
Unit 2: User
of AWT, AWT vs. Swing,
Java Applets, Applet
2.1. Introduction: Concept Containers
Class Hierarchy, Component and Grid Layout,
Cycle, Swing Flow layout, Border Layout,
2.2. Layout Management:
No Layout,
Grid bag Layout, Group Layout. Scroll Pane, Labels,
Password Fields, Text Areas,
2.3. GUI Controls: Text Fields, Sliders
Radio Buttons, Borders, Combo Boxes, Buttons in
Check Boxes, Check Box and Radio
Menu Items,
2.4. Menu, Menu Item, Icons in and Accelerators,
Mnemonics
Keyboard
Menu Items, Pop-up Menus, Tooltips
Menu Items, Toolbars, Choosers, Internal
Enabling and Disabling Choosers, Color
Creating Dialogs, File
2.5. Option Dialogs, and Tables.
Frames, Frames, Tables,
Trees, (4)
Unit 3: Event Handling (4 Hrs.) Interfaces, Using Action Commands,
Listener
3.1. Event Handling Concept,
Window
Adapter Classes Mouse Event,
Events, Focus Events,
Events, Key
32.
Handling Action (4)
Event, Item Events
Unit 4: Database Connectivity (4
Hrs.) Configuration, Managing
Driver Types, JDBC
[Link] Architecture, JDBC Result Set, SQL Exceptions
Connections, Statements,
of CSIT 7h Somester
and Practice Sets
TU Solution
2 . A Complete
Prepared Statements, AM.
Sets and(Mulached
tiple
Operations using Java,Result Sets, Row
4.2 DDL and DML Updateable
Scrollable Result Sets,
Results,
Transactions, SQL Escapes.
Row Sets,
(5 Hrs) 5
Network Programming atocol (TCP),
(TCP), Use
User Datagram Protocoi (UDP), Por
Unit 5: Protocol
control
Transmission
5.1. Classes in JDK
Network
IP Address using UDP, Working
Socket rogramming using TCP, Socket programming
Class.
rking
5.2 with URL
Connection
with URL's, working Receiving Email
Mail APl, Sending and
5.3. Java
Unit 6: GUI with
JavaFX (3 Hrs.) (3)
Javarx Layouts: FlowPane, BorderPam
6.1. Introduction, JavaFX vs SWng
Hbox, VBox, GridPane
Controls: Label, extriela, Button, RadioButton, CheckBox.
6.2 JavaFX UI FileChooser.
Hyperlink, Menu, Tooltip,
Server pages (8 Hrs.) (8)
Unit 7: Servlets and Java
Web Container, Introductiorn
to
Serviets, Life cycle of servlets, The servlet
71,
APls, Writing Servlet Programs,
Keading Form Parameters, Processing
Forms, Handling HTTP Request and Kesponse (GET/ POST Request)
Cookies and Session.
Database Access with Servlets, Handling
7.2. Servlet vs. JSP, JSP Access Model, JSP Syntax (Directions, Declarations.
Expression, Scriplets, Comments), JSP Implicit Objects, Object Scop
Access with JSP.
Processing Forms, Database
Frameworks
7.3 Introduction to Java Web
Unit 8 RMI and CORBA (3 Hrs.) 3)
8.1 Introduction, of RMI, Architecture of RMI, Creating and Executing RMI
Applications
8.2 Introduction to CORBA, RMI vs. CORBA, Architecture of CORBA, IDL
Simple CORBA Program.
Laboratory Work
The laboratory work includes writing programs related to basic java programming
concepts, Designing GUL, Event Handling, JDBC, Network Programming, Web
Programming, and Distributed Programming. They also learn to develop web
applications using Java Web Frameworks.
Text Books:
Cay S. Horstmann, Core Java Volume i-Fundamentals, Pearson, Eleventh
Edition, 2018
2. Cay S. Horstmann, Core Java Volume l1-Advance Features, Pearson, Elevenu
Edition, 2019
3. Herbert Schildt, Java: The
Complete Reference, McGraw-Hill Educat
Eleventh Edition, 2018
Reference Book:
1. D.T. Editorial Services, Java 8
Programming Black Book, Dreamtech Press, 01
Advanced Java Programming..3
TRIBHUVAN UNIVERSITY
Institution of Science and Technology
MODEL QUESTIONS-ANSWERS
Course Title: Advanced Java Programming Full Marks: 60 +20 +20
Pass Marks: 24 +8+8
Course No: CSC409
Credit Hrs.3
Nature Course:
of the Theory +Lab
Semester: VII
Section A
(2 x 10 20)
Attempt any two questions.
1. What are the uses of final modifier? Explain each use of the modifier with
suitable example. (1+9)
modifier used for classes, attributes
Ans: The final keyword is a non-access
If we initialize a
and methods, which makes them non-changeable.
its value. If we
variable with the final keyword, then we cannot modify
subclasses.
declare a method as final, then it cannot be overridden by any
restrict the other classes to inherit
And, if we declare a class as final, we
or extend it.
a c c e s s modifiers and non-
There are two types of modifiers in java:
access modifiers. The access modifiers in java specity accessiblity
data member, method, constructor or class.
(scope) of a
four types of java access modifiers:
There are
1. private
2. default
3. protected
4. public static, abstract,
There are many non-access modifiers such
as
we wiil learn access
synichronized, native, volatile, transient etc. Here,
modifiers.
Private access modifier
within class. In following
The private access modifier is accessible only
and Simple. A class contains
example, we have created two classes A
are accessing these private
private data member and private method. We
time error.
members from outside the class, so there is compile
class A
private int data=40;
private void Message()
{
[Link]("Hello java");
public class Simple
public static void main(String args[])
A obj=new A() Time Error
[Link] ([Link]) ;//Compile
and Practice Sets
4 A Complete TU Solution of CSIT 7th Semester
Time Error
[Link] () ;//Compile
Default access modifier
If you don't use any modifier, it is treated as default by default. Tho
default modifier is accessible only within package. In following example
we have created two packages pack A and pack B. We are accessing the
class from outside its package, since A class is not public, so it cannot ha
be
accessed from outside the package.
//save by [Link]
package packA;
class A
void Message()
[Link]("Hello");
//save by [Link]
package packB;
import packA.*;
class B
public static void main(String args[])
A obj new A(); //Compile Time Error
[Link](); //Compile Time Error
In the above
example, the of
scope class A and its
default so it cannot be accessed method Message) is
from outside the
Protected access modifier package.
The protected access modifier is
outside the package but accessible within
through
modifier can be applied on the data inheritance package and
only. The protected
can't be member, method and access
applied the class. In
on
constructor. It
two packages packA and packB. The following example, we have
A created the
so can be
accessed from outside the class of But packA package is public,
this package is declared as package.
protected, so it can be . Message0 method
the class only
through
//save by [Link]
inheritance. accessed from outs oftside
package packA;
public class A
{
protected void
Message ()
[Link]("Hello") ;
1/save by [Link]
package packB;
Advanced Java Programming...5
import packA. *;
class B extends A
public static void main(String args[])
B obj new B();
[Link] ();
Output: Hello
public access modifier
The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.
Example: Java program showing use of public access modifier
Wsave by Ajava
package packA;
public class A
public void Message0
[Link]("Hello");
lsave by [Link]
package packB;
import packA. *;
class B
public static void main(String args|)
A obj = new A0;
obj.Message0;
Output: Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access within within outside package by outside
Modifierclass package subclass only package
N N N
Private Y
Y N N
Default Y
Protected Y Y Y N
Y Y Y
|Public Y
form with user id, password, ok
2. Write a program to create login
java such that pressing T
button, and cancel button. Handle key events id
performs login and pressing clears text boxes and púts focus on user
'c
box. user table having fields
Uid and Password in the
text Assume
database named account.
(10)
6 A
.
Complete TU Solution of CSIT 7th Semester and Practice Sets
Ans:
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
public class LoginFrame extends JFrame
JLabel userIdLabel, passwordLabel;
JTextField userIdTextField;
JPasswordField passwordField;
JButton okBtn, cancelBtn;
JFrame self;
public LoginFrame ()
self this;
userIdLabel new
JLabel("üser ID");
passwordLabel = new
JLabel("Password");
userIdTextField JTextField (20);
=
new
passwordField new JPasswordField (20);
okBtn new
=
JButton( "OK");
cancelBtn new
3JButton ("Cancel")
=
[Link] Listener(new ActionListener()
@Override
public void
actionPerformed(ActionEvent e)
new JFrame ()
{
JLabelmessagelabel new JLabel();
=
LoginService loginService nen
LoginService();
String user [Link]();
String password new String (passwordField.
getPassword ())
try {
if (loginService. isAuthenticated(user
password))
[Link]
("Login Success!")
else {
messageL [Link] ("Invalid
credentials! ");
catch (SQLException ex)
[Link]();
messagelabel. setText ([Link]
finally {
add(messagelabel)
setSize(200, 100)
Advanced Java Programming.. 7
setVisible(true);
[Link] (new MouseAdapter()
@Override
public void mouseClicked (MouseEvent e)
[Link] (e);
[Link]();
[Link](new KéyListener()
@Override
public void keyTyped (KeyEvent e)
@Override
public void keyPressed (KeyEvent e)
if ([Link]() ==
1')
[Link]();
else i f ([Link]() == 'c')
userIdTextField. setText("");
passwordField. setText ("");
userIdTextField .grabFocus();
@Override
public void keyReleased (KeyEvent e)
[Link] Focusable (true);
[Link] (300, 500);
[Link] Layout (new FlowLayout (FlowLayout. LEFT));
[Link](userIdLabel);
[Link](userIdTextField)
[Link](passwordLabel);
[Link](passwordField) ;
[Link](okBtn) ;
[Link] (cancelBtn);
[Link](true);
public static void main(String[] args)
new LoginFrame () ;
Solution of CSIT 7th Semester and Practice Sets
8 A Complete TU
[Link]
import [Link];
import [Link];
import [Link];
import java. [Link];
public class LoginService
Connection connection;
public LoginService()
public boolean isvalidUser (String user) throws
ows SoLE
SQLException
{ "SELECT Uid from I
user WHERE
String query
PreparedStatement ps = [Link]
[Link](1, user);
ResultSet rs = [Link]);
ent(query)
return [Link]();
Dublic boolean isAuthenticated ( String user, String passr
throws SQLException HOrd)
if (!isvalidUser (user)) return false;
String hashedPassword = "";
String query "SELECT Uid from user WHERE Uid =
Password = ?";
PreparedStatement ps = [Link] (query):
[Link](1, user);
[Link] (2, hashedPasSword);
ResultSet rs [Link]();
return [Link]();
3. Discuss various scopes of JSP objects briefly. Create a HTML file wih
principal, time and rate. Then create a JSP file that reads values from t
HTML form, calculates
simple
interest and displays
it. 4+6
Ans: The availability of a JSP
object for use from a particular place ot u
application is defined as the scope of that JSP [Link] scope
segregated into four
parts and they are page, request, sessi and
application.
Page Scope:
Fage scope means, the JSP object accessed only from within the same
where it was created. JSP implicit objects out,
exception, re pone
pageContext, config and page have page scope
//Example of JSP Page Scope
Jsp:useBean id="employee class="EmployeeBean" scope="pagee"/»
Request Scope:
A JSP object created using the page
that serves request scope can be aaccessed from anre
that request. More than page can serve asingle
a
sing
Implicit object request has the request one
1/Exmple of JSP
Request Scope scope.
Advanced Java Programming... 9
jsp:useBean id="employee" class="EmployeeBean" scope="request"/>
Session Scope?
Session scope means, the JSP object is accessible from pages that belong to
the same session from where it was created. Implicit object session has the
session scope.
1/Example of JSP Session scope
sjsp:useBean id="Employee" class="EmployeeBean" scope="session"/>
Application Scope
A JSP object created using the application scope can be accessed from any
has the
pages across the application. The implicit object application
application scope.
1/Ecmaple of JSP application scope.
jsp:useBean id="Employee" class="EmployeeBean" scope="application"/>
Second Part
[Link]
html>
<head
meta charset="UTF-8">
<title>Simple Interest</title»
</head
<body
h1>Simple InterestF</h1>
<form action="[Link]">
Enter the principal: <input type="text" name="principal"><br />
cbr /> Enter the time: <input type="text" name="time">xbr />
<br /> Enter the rate (%): <input type="text" name="rate"><br />
value="Calculate">
<br / <input type="submit"
</form>
</body
/html>
[Link]
<html
<head
<meta charset="UTF-8"
<title>1SP Page«/title
/head
body
double p = Double. parseDouble([Link] ("principal "))
double t = [Link]([Link]("time"));
double r = Double. parseDouble([Link]("rate"));
double interest (p * t r) / 100;
<h1
Simple Interest <K=interest X»
</h1
</body
</html
Sets
7h Semester and Praçtice
Solution of CSIT
TU
A Complete Section B
10.
(8 x5 40)
questions. of Employee class in the file
in
Attempt any eight that
writes objects
interest.
Write a java program of
class as your 5
4. Create
Employee
named [Link].
Ans: import [Link]. "; S e r i a l i z a b l e
implements
class Employee
p r i v a t e S t r i n g name;
private int age; int age)
name,
(String
public Employee
[Link] = name
[Link] = age;
@Override
public String toString()
"
name
Age:" + age;
"Name: +
return
class RWObject
static void main(String[] args)
public
new Employee ( "Arjun", 20);
Employee employee1
=
Employee employee2 = new Employee ( "Ram", 20)
try
FileOutputStream fileOutputStream = new File0utputStream
("[Link]");
ObjectoutputStream objectoutputStream = new ObjectOutputStream
(fileoutputStream) ;
1/Write object to file
objectOutputStream. writeObject (employee1) ;
objectoutputStream.write0bject(employee2) ;
[Link]() ;
[Link]();
FileInputStream fileInputStream new
FileInputStream("[Link]");
ObjectInputStream objectInputStream = new
(fileInputStream); ObjectInputStream
//Read Objects
Employee employee
(Employee) =
[Link]();
Employee employee3 (Employee)
objectInputStream read0bject ( ):
.
[Link](employee. toString () ):
[Link]();
objectInputStream. (employee3.toString0%
[Link]() ;
Advanced Java Programming... 11
catch (Exception e)
[Link]();
What are layout managers? Explain Gridbag layout with suitable example.
5.
(1+4)
Ans: The LayoutManagers are used to arrange components in a particular
manner. The Java LayoutManagers facilitates us to control the positioning
and size of the components in GUI forms. LayoutManager is an interface that
is implemented by all the classes of layout managers. There are the following
classes that represent the layout managers:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]. BoxLayout
[Link]
[Link]
[Link] etc.
GridBaglayout
The gridbag layout is a flexible layout manager that aligns components
vertically and horizontally, without requiring that the components be of the
same size. It maintains a dynamic rectangular grid of cells with each
component occupying one or more celis. Each components managed by a
grid bag layout is associated with an instance of GridBagConnstraints that
specifies how the component is arranges within its display area.
Example
package project3;
1/Java program to demonstrate GridBagLayout class.
import [Link].*
import [Link].*;
import [Link]
import javax. swing.";
public class GridbagDemo extends JFrame
GridbagDemo ()
setTitle ("GridBagLayoutDemo") ;
JPanel p = new JPanel () ;
[Link] (new GridBagl ayout( ));
GridBagConstraints c = new GridBagConstraints ();
[Link] = new Insets(2, 2, 2, 2);
[Link] = 0;
[Link] 0 ;
12.A Complete TU Solution of CSIT 7th Semester and Practice Sets
[Link] = 15;
[Link]=50;
[Link](new JButton("Java Swing"), c)5
[Link] = 1;
[Link] = 90;
[Link] = 40;
[Link](new JButton("Layout'"), c);
[Link] = 0;
[Link] 1;
[Link] = 20;
[Link] 20;
[Link] (new JButton ("Manager"), c);
[Link] = 10;
[Link] ='1;
[Link](new JButton("Demo*"), c);
WindowListener wndCloser =
new
WindowAd apter ()
public void windowClosing (WindowEvent e)
[Link](0);
1/ add the
actionwindowlistener
addWindowListener (wndCloser);
getContentPane().add
setsize(600, 400)
(p);
setVisible(true);
I/Main Method
public static void
main(String[] args)
new
GridbagDemo () ;
6. What is the use of action
command in event
example. handling? Explain with
Ans: Action command
is used to
handle event caused the (1+4)
Example by Buttons.
import javax. swing.*;
import [Link].*;
import [Link];
import [Link]
public class ActionDemo
extends JFrame
JLabel 11, 12,
implements ActionListener
JTextField t1, 13
JButton b1, b2; t2, t3;
public ActionDemo ()
super("Handling Action Event");
11 new
JLabel("Click button toon
get
t1
result") ;
JButton( "DemoJTextField
new
b1 new (20);
Button");
[Link](this)
Advanted Java Programming... 13
setLayout(new FlowLayout ([Link], 150, 19));
add(11);
add(t1);
add(b1);
setSize(400, 300);
setVisible(true);
public void actionPerformed(ActionEvent actionEvent)
str = [Link]
String ();
[Link]("You have clicked
"
str);
public static void main(String[] args)
new ActionDemo();
of the
the Demo Button, with the help
In the above example if clicked on
event done on
will be able to see the click
getActionCommand() method
we
the output. with
How it can be handled? Explain
causes SQL exception?
7. What
example. (1 +4)
the query.
execute or create
we may get exceptions
when we
Ans: In JDBC, under SQL
due to the Database or Driver
come
Exceptions that occur can handle the SQL Exception like
Exception. Using Exception handling,
we
we handle the normal exception.
It extends the Exception
SQLException is available in the [Link] package.
available in the Exception
class which means that we can use the methods
class in the SQLException class as well.
Example
package com. STH. JDBC;
import [Link];
import [Link];
import [Link];
inport [Link];
import [Link];
public class Exception_Example
public static void main(String[]
args) throws ClassNot FoundException
stub
I/ TODO Auto-generated method
employee_details set email="' martin@
String update_query "update 10011";
[Link]' where empNum1
[Link] ("oracle. [Link]");
try(Connection conn
[Link]("jdbc:oracle:thin
System/pass123@localhost:1521:XE"))
14..A Complete TU Solution
of CSIT 7h Semester and Practice Sets
Statement statemntl
= conn.
Createstatement () :
Resultset rs1 =null;
statemnt1 =[Link]();
[Link]( "Executing Update query
executelpdate method");
using
int return_rows [Link](updata
updateuery.
_query),
of Affected Rows
[Link]("No.
'+return roWSOwS,
catch(SQLException sqe)
[Link]("Error Code
[Link]( "sQL state =
"
+[Link]():
[Link]();
[Link]("Message [Link]()):
[Link]("printTrace /n");
[Link]() ;
. Write a java program using TCP such that client sends
and displays its factorial. The server number to seri
received from client. (5)
computes factorial of the numbe
Ans:
[Link]
import [Link].*;
import [Link].*
class factclient
public static void
main(String argv[]) throws Exception
String n
DatagramSocket clientSocket =new
byte []send=new DatagramSocket()%
byte[ 102]
byte []resive=new byte[102]
BufferedReader inFromUser
InputStreamReader (System. in) BufferedReader(n
new
[Link]("\n Enter Number ")5
[Link]();
InetAddress ipadd= [Link]
send=[Link]() [Link]("localhd
Datipadd,agramPacket
6878); sendPck=new DatagramPacket
DatagramPacket (send,
(send, send. lengt
Advanced Java Programming... 15
[Link](sendPck);
DatagramPacket resPck=new DatagramPacket (resive, resive.
length);
[Link](resPck);
String fact=new String ([Link]());
"
SERVER:
"
+n+"| +fact);
[Link]("FROM
=
[Link]()
[Link]
import [Link].*;
import [Link].*;
class factserver
{
public static void main(String argv[ 1) throws Exception
String num, res;
int i,no;
long fact;
[Link]("Server is ready")
DatagramSocket serverSocket = new DatagramSocket(6870);
byte [ ]send=new byte[102];
byte [ ]resive=new byte[102]
resPck=new
DatagramPacket (resive,
DatagramPacket
[Link]);
[Link](resPck);
num=new String([Link]());
num=[Link]();
no=[Link](num);
fact 1;
for(i-1; 1ic=no; i++)
fact=fact*i;
res=[Link](fact);
send=[Link] () i
InetAddress ipadd= [Link] () ;
int port=[Link]() ;
DatagramPacket sendPck=new
DatagramPacket(send, send. length, ipadd, port);
[Link] (sendPck) ;
16.A Complete TU Solulen of CSIT 7m Semester end Praethke Set
How JavaEx differs from Swing? Explain steps of creating GUI using
javaFx. (2 +3)
Ans: The key differences between JavaFX and Swing.
JavaFX Java Swing
JavaFX supports MVC very Swing supports MVC but is not
consistent with components.
friendly.
UI Swing has a more sophisticated set
|JavaFX also has some
lesser than of GUI items.
components but is
Swing
JavaFX is platform support for GUI| Swing is a standard toolkit for GUI
Applications.
JavaFX has UI Components but still Swing is the legacy library for GUI.
also has several
evolving It
components built over the Swing.
JavaFX can help rich
to create Swing can help to create UI
internet applications with modern components with a decent look.
UI.
JavaFX is also supported by IDEs Various IDEs support Swing.
but not as good as
Swing
Writing Sample Javafx Program
Here, we are creating a simple JavaFX application which prints hello world
on the console on clicking the button shown on the stage.
Step 1: Extend [Link] and override start)
Start0 method is the starting point of constructing a JavaFX application
therefore we need to first override start method of
[Link] class. Object of the class [Link] is
passed into the start(0 method therefore import this class and pass its object
into start method.
Step 2: Create a Button
A button can be created by instantiating the [Link] class.
For this, we have to import this class into our code. Pass the button label text
in Button class constructor.
Step 3: Create a layout and add button to it
JavaFX provides the number of layouts. We need to implement one of them
in order to visualize the
widgets properly. It exists at the top level of the
scene
graph and can be seen as a root node. All the other nodes
(buttons,
texts, etc.) need to be added to this layout. In this application, we have
implemented StackPane layout. It can be implemented by instantiating
[Link] class.
Step 4: Create a Scene
The layout needs to be added to a scene. Scene remains at the higher level in
the hierarchy of application structure. It can be created by instantiating
Advaneed Java Programming... 17
[Link] class. We need to pass the layout object to the scene class
constructor.
the Stage
Step 5: Prepare
[Link] class provides some important methods which are
to be called to set some attributes for the stage. We can set the
title
required
of the stage. We also need to call show) method without which, the stage
won't be shown.
for the button
Step 6: Create an event
event on the button. We need to
As our application prints hello world for an
call setOnAction() on the
create an event for the button. For this purpose,
button and define an anonymous class Event
Handler as a parameter to the
method handle() which
method. Inside this anonymous class, define a
contains the code for how the event is handled. In our case, it is printing
hello world on the console.
Step 7: Create the main method
which are required to
Till now, we have configured all the necessary things
this application is still incomplete.
develop a basic JavaFX application but
at the last, we need to create a
We have not created main method yet. Hence,
i.e. will call launch()
main method in which we will launch the application
to it.
method and pass the command line arguments
to demonstrate Steps of Writing JavaFX Programns
/Example: Program
import javafx. [Link];
import [Link]. Button;
import javafx. stage. Stage;
import [Link]. Scenej
import [Link]. layout. StackPane
Application //Step 1
public class HelloWorld extends
throws Exception
public void start(Stage primaryStage)
/Step 2
Buttonbtn1=new Button("Say, Hello World");
1/Step 3
StackPane root=new StackPane();
[Link] () . add(btnl);
1/Step 4
Scene scene=new Scene(root,400, 300);
1/Step 5
primaryStage. setScene (scene)
JavaFX Application");
[Link]("First
[Link]()
Semestor and Practice Sets
18.. A Complete
TU Solution of CSIT 7
1/Step 6
[Link](new Handler());
class Handler
implements EventH
tHandler<Action Event»
Contd..
@Override
handle(ActionEvent ae)
public void
[Link].
intln("hello world");
1/Step 7
public static void main (String[] args)
launch(args);
Output
First JavaFX Application
X
Say, Hetlo Wortd
10. What are
Servlet different ways of
Ans: The program using any onewriting servlet programs
programs? Write sa
servlet way. (1 +4)
example can be created
By by three ways.
implementing
By inheriting Servlet interface,
By inheriting GenericServlet class, (or)
HttpServlet class
Advaneed Java Programming... 19
The mostly used approach is by extending HttpServlet because it provides
http request sperific method such as doGet), doPost), doHead) etc.
Example:
import [Link].";
import [Link].*;
import [Link].*;
public class DemoServ. extends HttpServlet
public void doGet (HttpServletRequest req
HttpservletRes ponse res) throws ServletException,
IOException
[Link]("text/html");
Printwriter pw=[Link]()5
String name=[Link]("name");
[Link]("Welcome "+name)
11 How CORBA differs from RMI? Discuss the concepts of IDL briefly(2+3)
Ans: Major differences between RMI and CORBA are listed below.
RMI L CORBA
RMI stands for remote method | CORBA stands for Common Object
invocation Request Broker Architecture
It uses Java interface for It uses Interface Definition Language
implementation. (LDL) to separate interface from
innplementation.
CORBA passes objectsby value. CORBA passes objects by reference
Java RMl is a server-centricmodel. CORBAis a peer-to-peer system.
RMI uses the Java Remote Method CORBA use Internet Inter- ORB
Protocol as its underlying remote Protocol as its underlying remote
communication protocol. communication protocol.
RMI is slow in execution than CORBA is fast in execution than
CORBA. RMI.
Java IDL is a technology for distributed objects that is, objects interacting
to interact
on different platforms across a network. Java IDL enables objects
regardless of whether they're written in the Java programming language
or
another language such as C, C++, COBOL, or others.
An interface description language (or alternatively, interface definition
is a used to describe a
specification language
language), or IDL for short,
Software component's interface. IDLs describe an interface in a language
software
components
independent way, enabling communication between written in
that do not share a language for example, between components
-
Ctand components written in Java.
20A Complete TU Solution of CSIT 7h Somester and Practice Sots
We can't write actual programs in IDL because it lacks the logic a
control structures. We need to do anything useful with it. Inet low
both for primitive and class ad, IDL
concentrates on type definitions,
types, so
ample,youa
use it instead to define interfaces, not implementations. For ev
function used to calculate sales tax on an order might be defined like this:
float calculate_tax (-in float amount );
Here we have a function, calculate_tax, that receives a single input (bv.
float. The function also returns a val ue
parameter, amount, of type
implementation of the calculate ta type
float. Notice that there is no
functi
here; we provide that in our native language. nction declarations
are
collected into interfaces, which represent all the defined methods for a clas
These interfaces are defined using the standard curly braces. ToTo extendtthe lass.
above example, we might include the calculate_tax function, along
order interface, like this:
with
some other functions, in an
interface order
float calculate_tax ([in] float taxable_amount):
float calculate_total([in] item_list items);
bool place_order([in, out] item_list items) ;
12. When thread synchronization is necessary? Explain with suitable example
(1+4)
Ans: At times when more than one thread try to access a shared resource, we need
to ensure that resource will be used by only one thread at a time. The process
by which this is achieved is called synchronization. The synchronization
keyword in java creates a block of code referred to as critical section.
Syntax:
synchronized (object)
//statement to bé synchronized
Every Java object with a critical section of code gets a lock associated with
the object. To enter critical section a thread need to obtain the
corresponding objece's lock.
If we d not use syncronization, and let two or more threads access a
shared resource at the same time, it will lead to distorted
results.
Example:
class First
public void display(String msg)
[Link] ("["+msg);
try
Advanced Java Programming..21
[Link](1000);
catch(InterruptedException e)
[Link]();
[Link] ("]");
class Second extends Thread
String msg
First fobj
Second (First fp,Stringstr)
fobj=fp;
msg str;
start
public void run()
synchronized(fobj) //Synchronized block
[Link](msg);
public class Syncro
public static void main (String|] args)
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ssl- new Second (fnew, 'new");
Second ss2 new Second(fnew, "programmer");
Output
welcome
new
programmer]
22 A Complete TU Solutlen of CSIT 7 Semester and Practlce Sets
TRIBHUVAN UNIVERSITy
Institution of Science and Technology
TU QUESTiONS-ANSWERS 2078
Course Title: Advanced Java Programming Full Marks: 60 +
Course No: CSC409
Lab
Pass Marks: 24 20+
Nature of the Course: Theory +
+8+
Credit Hrs.
Semester: VII
Section A
Attempt any two questi
AWT with Swing. Write a GUI program (2 10 2
1. Compare
find sum and difference of two numbers. Use two text fieids
input and a label for output. The program should display
mponents
play sum if use
presses mouse and difference if user release mouse. (2+8)
Ans There are many differences between avaAW andswingthatare given bal.
Java AWT ava Swing elow:
AWT components are platform- Swing components are
dependent. independent. platform-
AWT components are heavyweight. Swing components are
AWT doesn't support pluggable Swing supports lightweight
feel pluggable look anc
look and feel.
AWT provides fewer Swing provides more
components than Swing. powerfu
Components.
AWT doesn'tfollows MVC. Swing follows MVC.
Program part,
import [Link].*
import [Link]. *;
import [Link];
import [Link];
class Addition extends JFrame implements ActionListener
Label 11, 12;
JTextField t1, t2, t3;
Button b1;
public Addition ()
11= JLabel("First Number: ");
new
[Link] (20, 10, 100, 20); l/x, y, width, height
t1 new JTextField (10) ;
[Link](120, 10, 100, 20);
12 new JLabel("
Second Number: ") ;
[Link]
t2
(20, 40, 100, 20);
=
new
JTextField (10);
[Link] (120, 40, 100, 20);
b1 new JButton("Sum");
[Link]
t3 new
(20, 70, 80, 20);
t3.
JTextField (10);
setBounds (120, 70, 100, 120);
add(11);
add(t1);