ADVANCE JAVA
May 2010
Paper Code: CSE-404-E
Q.1. How object oriented programming language concepts are better than structured programming ? Explain inheritance with example.
Ans : Object-oriented programming(OOP) is a programming paradigm using "objects"- data structures consisting of data fields and methods together with their interactions - to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.
Object Oriented Programming(OOP) approache binds the dat and the functions that operate on that data into a single entity. Such as entity is called an object. Functions of an object can only access its data. You can't access the data directly. For example, if you want to read a data item in an object, you call a member function in the object, it will read the data item and return the value to you. This secures data from any changes from outside. Thus, OOP gives more emphasis on data.
A C++ program typically consists of a number of objects which communicate with each other by calling one another's member functions. Calling an object's member functions is also referred to as sending a message to the object. The organization of a C++ program is shown in fig.
figure here--------
Objects are independent of each other. They are responsible for managing their own state and offering services to other objects. Therefore, new objects can be easily added whenever necessary.
OOP have the following features.
- OOP is more data oriented.
- Programs are made up of objects which model real-world entities.
- Data and Functions are binded together in an object.
- Data security exists.
- Objects communicate through functions.
- Objects communicate through functions.
- Addition of new data and function(i.e. object) is easy.
- OOP follows bottom-up approach.
- Single Inheritance: In this type of inheritance, a single sub class is derived from a single base class.
- Multiple Inheritance: In Multiple Inheritance, there is more than one base class from which the child class is derived. This results in the duplication of data with the derived class. Java does not directly support multiple inheritance. This is because different classes may have different variables with same name that may be cotradicted and can cause confusions in JVM, thus resulting in errors. We can extend one class only to avoid ambiguity problem with JVM. In interface we have to define the functions.
- Multilevel Inheritance: In this inheritance, a class derives another class, and from the derived class, another sub class is derived.
- Hybrid Inheritance: There may occur situations where we need to apply two or more type of inheritance in the design of a program. For each cases, hybrid inheritance is used.
Ans. Methods of URL Connection : A framework is provided by Java, using java.net package through several interfaces, classes, and abstract classes for handling URL(Uniform Resource Locator). Using this framework, we can easily create sum function of web browser and can be embedded in an application.
Before discussing the concept in-depth let's have a description about two important classes is given below :
(i) Class URI : The term URI stands for Uniform Resource Identifier. It create an instance of URL, and those are used to parse the string, and also providing various methods. Every URL, is a URI, but not every URI, is a URL.
On the base of conceptual difference between URIs and URLs, two different classes are given with their characteristics and functionalities.
(ii) Class URL : Without URL, browser cannot make out the information about web. URL identifies a resource anywhere on the Internet. The introduction or URLs came up with WWW.
Web is a collection of protocols and different file formats.
Table: Methods of Java-net.URL class----
(iii) Class URLConnection : The class URLConnection gives some additional information about web resource. The class provides some methods by which you can send the request to server. The class is actually abstract. There is only constructor to create instance of URLConnection.
URLConnection(URL urlString) creates a new URLConnection object for the URL urlString. This constructor can be called only by a subclass of the URLConnection class; and subclass will gives the implementations of the various URLConnection methods for a specific protocol.
Example :
URL http_url = new URL("http://www.posthatke.com") ;
URLConnection urlc = new URL Connection(fttp_url ) ;
There is another way to create an instance of URL Connection, by invoking the openConnection() method of URL class, that return an object of URLConnection
Example :
URL http_url = new URL( "http//www.posthatke.com") ;
URLConnection urlc = http_url.openconnection() ;
Table : Method of java.net.URLConnection class
E-Mail server : A socket will be created, connect to port 25, which is SMTP port number. Simple mail transfer Protocol describes the format in which e-mail message will be sent. In UNIX OS, sendmail daemon was already implemented to support this features.
Example :
import Java.io.BufferedReader;
import Java.io.FileReader;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.io.OutputStream;
import Java.io.OutputStreamWriter;
import Java.io.PrintWriter;
import Java.net.InetAddress;
import Java.net.Socket;
import Java.net.UnknownHostException;
public class SMTPDemo {
public static void main (String args[] throws IOException, UnknownHostException {
String msgFile = "file.txt";
String from = "java2s@java2s.com";
String to = "yourEmail@yourServer.com";
String mailHost = "yourHost";
SMTP mail = new SMTP(mailHost);
if(mail != null) {
if (mail.send(new FileReader (msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP sever failed !");
}
}
System.out.pritnln("Done");
}
static class SMTP {
private final static int SMTP_PORT = 25;
Inetdderess mailHost;
Inetddress localHost;
BufferedReader in;
Public SMTP (String host) throws UnknownHostException {
mailHost = InetAddress.getByName (host);
localHost = InetAddress.getLocalHost ( );
System.out.println("mailhost = "+ mailHost );
System.out.println("localhost = "+ localHost);
System.out.println("SMTP construtor done\n");
}
public boolean send (FileReader msgFileReader, String from, String to ) throws IOException {
Socket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = new Socket(mailHost, SMTP_PORT);
if (smtpPipe == null) {
return false; }
inn = smtpPipe.getInputStream( );
outt = smtpPipe.getOutputStream( );
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn = = null \\ out= = null) {
System.out.println("Failed to open streams to socket.");
return false;
}
StringinitialID = in.read.Line( );
System,out.println(initialID);
System.out.println("HELO " + localhost.getHostName( ));
out.println("HELO " + localhost.getHostName( ));
String welcome = in.readLine ( );
System.out.println(welcome);
System.out.println("MAIL From:<" + from + ">");
out.println("MAIL From:<" + from + ">");
String senderOK = in.readLine( );
System.out.println(senderOK);
System,out.println("RCPT TO:<" + to + ">");
out.println("RCPT TO:<" + to + ">");
String RecipientOK = in.readLine( );
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
While((line = msg.readLine ( )) != null ) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine( );
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
Q.3. Explain the following networking concepts :
(i) Advanced connection management
(ii) Metadata.
Ans. (i) Advanced Connection Manangement : Networking means transmitting data from one device to another device on the network, but both must use the same protocol for transmission. There is an array of stack, called protocol stack, that involves everything from giving the data to physical device by converting that in voltage pulse to delivering data streams to applications for which it was destined to.
Fig : Stack of layer
Each layer provides an abstraction and dedicated to a specific fix set of job. The intermediate layers also work as an interface between its upward and downward layer, first and then the last.
Each layer communicates only with its immediate above and below layers. Encapsulation and decapsulation are two mechanism, that embed each layer's packets into the immediately below layer packet, and reverse the process at the data moves up at the receiving machine, respectively.
As internet is a bunch of networks of different types of environments. The internet is exclusively the worldwide set of connections of TCP/IP networks which use IP address and protocols under the
Q.5. What are Java swing ? How to implement a tree using Java swing. (20)
Ans. Java swing : Swing is a set of packages that are built on top of AWT which provides a large number of inbuilt predefined classes.
Swing class provides a large set of components such as toolbars, progressbar, text fields and timers. Swings provides a large set of built-in controls such as tree, image buttons, sliders, tabbed panes, toolbars, tables, color choosers etc.
Swing provides several UI components of which, few are:
- JOptionPane : Mkes it easy to pop up a standard dialog box.
- JPanel : A generic lightweight container.
- JpasswordField : It allows the editing of a line of text where the user views some special characters in place of original characters.
- JPopupMenu : It provides a pop-up menu.
- JProgressBar : It is a component that displays an integer value within an interval.
- JRadioButton : A radio button cn be selected or deselected displaying its state.
- JScrollBar : It gives an implementation of the scrollbar.
- JSeparator : It provides a menu separator.
- JSlider : It is a component that lets the user select a value by sliding knob.
- JTable : It presents the data in a two-dimensional format.
import Java.awt.*;
import Javax.swing.*;
import Javax.swing.tree.*;
import Java.awt.event.*;
public class SimpleTree extends JFrame {
public static void main(string[] args) {
new simple tree();
public SimpleTree() {
super("Creating a Simple JTree") ;
WindowUtilities.setNativeLookAndFeel() ;
addWindowListener(new ExitListener()) ;
Container content = getContentPane() ;
Object[] hierarchy = {"1. CHAPTER 1",
new Object[] { "1.1 INTRODUCTION TO JAVA",
"1.1.1 History of JAVA",
"1.1.2 JAVA and Internet",
"1.1.3 JAVA Virtual Machine",
"1.1.4 JAVA's Magic : The Byte Code",
"1.1.5 Features of JAVA',
"1.1.6 JAVA Environment"},
new Object[]{ "1.2 DATA TYPES & OPERATORS"},
new Object[] { "1.3 ARRAYS",
"1.3.1 Declaration of Array Variables",
"1.3.2 Array Construction",
"1.3.3 Initialization of Array",
"1.3.4 Array Access",
"1.3.5 Arrays of Characters"},
new Object[] { "1.4 CONTROL STATEMENTS"},
new Object[] { "1.5 A SAMPLE PROGRAM IN JAVA"},
new Object[] { "1.6 CLASSES & METHODS",
"1.6.1 Constructor",
"1.6.2 Garbage Collection"},
new Object[] {"1.7 INHERITANCE",
"1.7.1 Single Inheritance",
"1.7.2 Multiple Inheritance",
"1.7.3 Multilevel Inheritance",
"1.7.4 Hybrid Inheritance",
new Object[] {"1.8 INTERFACE"},
new Object[] {"1.9 PACKAGES"},
new Object[] {"1.10 EXCEPTION HANDLING",
"1.10.1 try and catch with multiple catch clause,"
"1.10.2 throw and throws",
"1.10.3 finally"},
new Object[] {"1.11 MULTITHREADING",
"1.11.1 States of Thread"},
new Object[] {"1.12 COLLECTIONS"},
new Object[] {"1.13 I/O STREAMS",
"1.13.1 Working with InputStream and OutputStream",
"1.13.2 Working with Reader and Writer"},
new Object[] {"1.14 AWT"},
new Object[] {1.15 APPLET PROGRAMMING",
DefaultMutableTreeNode root = processHierarchy(hierarchy) ;
JTree tree = new JTree(root) ;
content.add(new JScrollPane(tree), BorderLayout.CENTER ;
setSize(275, 300) ;
setVisible(true) ;
}
private DefaultMutableTreeNode processHierarchy (object[] hierarchy) {
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(hierarchy[0]) ;
DefaultMutableTreeNode child;
for(int i=1; i<hierarchy,length; i++) {
object nodeSpecifier = hierarchy[i] ;
if (nodSpecifier instanceofobject[]) // Ie node with children
child = processHierarchy((object[]) nodeSpecifier) ;
else
child = new DefaultMutableTreeNode(nodeSpecifier) ; // le Leaf
node.add(child) ;
}
return(node) ;
}}
import Javax.swing.*;
import Java.awt.;
public class WindowUtilities {
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) ;
} catch(Exception e) {
System.out.println(" Error setting native LAF : " +e) ;
} }
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCross PlatformLookAndFeelClassName());
} catch(Exception e) {
system.out.println("Error setting Java LAF : "+e) ;
} }
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel") ;
} catch(Exception e) {
System.out.println("Error setting MotifLAF : "+e ) ;
}
}
public static JFrame openInJFrame(Container content, int Width, int height, String title, Color bgColor) {
JFrame frame = new JFrame(title) ;
frame.setBackground(bgColor) ;
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content) ;
frame.addWindowListener(new ExitListener() ) ;
frame.setVisible(true) ;
return(frame) ;
}
public static JFrame openInJFrame(Container content, int width, int height, String title ;
{
return (openInJFrame( content, width, height, title, color.white ) ) ;
}
public static JFrame openInJFrame(Container content, int width, int height) {
return(openInJFrame(content, width, height, content.getClass().getName(), Color.white)) ;
}
}
import Java.awt.* ;
import Java.awt.event.* ;
public class ExitListner extends WindoAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0) ;
}
}
The output interface would look like :
Figure here---------
Q. What are digital Signatures ? Explain.
Ans. Digital signature is an important cryptographic primitives used for uthentication, authoriztionand non-repudiation. An asymmetric encryption algorithm such as RSA can be used to create and verify digital signature. The simplest form of the protocol works as follows :
- Sender encrypts the document with its private key, thereby singing the document.
- Sender sends the signed document to receiver.
- Receiver deciphers the document with Sender's public key, thereby verifying the signature.
A digital signature must meet the following two properties.
- It must be unforgettable : If an entity sings a document M with signature S(M), it is not possible for other entity to produce the same pair <M,S(M)>.
- It must be authentic : If someone R receives a digital signature from S, R must be able to verify that the signature is really from S.
If the message is altered, then the finger print of the altered message will not match the fingerprint of the original message. If the message and its fingerprint are delivered separately, then the recipient can check whether the message has been tampered or not. Public key cryptography is based on the notion of public key and private key. Even though everyone knows your public key, they won't compute your private key in your lifetime, no matter how many computing resources they have available. It may seem difficult to believe that nobody can compute the private key from the public keys, but nobody has ever found an algorithm to do this for the encryption algorithms. If the keys are sufficiently long brute force would require more computations. There are two kinds of public\private key pairs : for encryption and for authentication. If anyone sends you a message that was encrypted with your public encryption key, then you can decrypt it with your private decryption key. The verification passes only for messages that you signed and it fails if anyone else used his to sign the message.
- Java threads and Interrupts in Java programming language
- Abstract classes and Generic function in Java
- Callback functions in Java Programming language
- Constructors in programming language
- Static components and constants concept in programming language
- Data encapsulation in programming language.
- Java threads and Interrupts in Java programming language