[ FALL, 2015] ASSIGNMENT
OOPS with JAVA
Q. No. 1. Describe the features of java
programming language.
Answer: Java defines data as object with methods that support the
objects. Java is purely object-oriented language and hence supports
object-oriented features such as encapsulation, abstraction, polymorphism, and
inheritance. Everything in Java is modeled as a class and any code that you
write in Java must be wrapped inside a class.
Java is tuned
for Web. Data accessing across the web in Java is like accessing the local file
system. You can build distributed application in Java that use resources from
any other networked computer.
Java is
interpreted as well as compiled language. The java code is first compiled to a bytecode
file which is in a binary, platform independent format. When the program
has to be executed, this byte is fetched into the memory and interpreted on the
user’s machine. As an interpreted language, java has simplex syntax.
Compilation is the process of converting the
human readable code into a language that the computer understand- machine
language. When you compile a program using a compiler, the compiler checks for
synthetic errors in code and list all the errors on the screen. You have to
rectify the errors and recompile the program to get the machine language code.
The Java compiler, instead of compiling directly into a machine language,
compiles the code to an intermediate bytecode that is understood by the Java
environment.
A Java
program can run on any machine that has a Java interpreter. The bytecode
supports connection to multiple databases. This makes the Java code portable.
Java forces
you to handle unexpected errors. This ensures that Java programs are robust,
bug free and do nor crash. Due to strong type-checking done by Java on the
user’s machine, any changes to the program are tagged as error and the program
will not execute. Java is, therefore, secure.
Java is faster
than other interpreted-based language like BASIC since it is both compiled and
interpreted.
Multithreading is the ability of an application to
perform multiple tasks at the same time. You can create multithreading programs
using Java. The core of Java is also multithreaded.
The following
definition of Java by Sun Microsystems lists all the features of Java.
‘Java is
simple, object-oriented, distributed, interpreted, robust, secure,
architecture, neutral, portable, high-performance, multi-threated and dynamic
language’.
Q. No. 2. Explain
any four function can be used for string comparison. Write a program to reverse
a string.
Answer: The String class provides several
methods to compare string or substrings within strings. They are examined here.
Equals()
and equalsIgnoreCase()
To compare two strings for equality,
use equals( ). It has this general form:
boolean equals(Object str);
Here, str is the String object
being compared with the invoking String object. It returns true if
the strings contain the same characters in the same order, and false otherwise.
The comparison is case-sensitive. To
perform a comparison that ignores case differences, call equalsIgnoreCase( ).
When it compares two strings, it considers A-Z to be the same as a-z.
It has this general form:
boolean equalsIgnoreCase(String str);
Here, str is the String object
being compared with the invoking String object. It, too, returns true
if the strings contain the same characters in the same order, and false otherwise.
regionMatches( )
The regionMatches( ) method
compares a specific region inside a string with another specific region in
another string. There is an overloaded form that allows you to ignore case in
such comparisons. Here are the general forms for these two methods:
boolean regionMatches(int startIndex,
String str2, int str2StartIndex, int numChars);
boolean regionMatches(boolean ignoreCase,
int startIndex, String str2, int str2StartIndex, int numChars);
For both versions, startIndex specifies
the index at which the region begins within the invoking String object.
The String being compared is specified by str2. The index at
which the comparison will start within str2 is specified by str2StartIndex.
The length of the substring being compared is passed in numChars. In the
second version, if ignoreCase is true, the case of the characters
is ignored. Otherwise, case is significant.
equals( ) Versus ==
It is important to understand that the equals(
) method and the == operator perform two different operations. As
just explained, the equals( ) method compares the characters inside a String
object. The == operator compares two object references to see
whether they refer to the same instance. The following program shows how two
different String objects can contain the same characters, but references
to these objects will not compare as equal.
compareTo( )
Often, it is not enough to simply know
whether two strings are identical. For sorting applications, you need to know
which is less than, equal to, or greater than the next. A string
is less than another if it comes before the other in dictionary order. A string
is greater than another if it comes after the other in dictionary order. The String
method compareTo( ) serves this purpose. It has this general form:
int compareTo(String str);
Here, str is the String being
compared with the invoking String.
Reverse string
using StringBuffer class
class InvertString
{
publicstaticvoid main(String args[])
{
StringBuffer a = new StringBuffer("Java programming is
fun");
System.out.println(a.reverse());
}
}
Output of program:
Reverse of string is:
nuf si gnimmargorp avaj
Q.
No. 3. Describe with the help of an example the implementation of inheritance.
Answer:Implementing Inheritance in Java
The extends keyword is
used to derive a class from a superclass, or in other words, extend the
functionality of a superclass.
Syntax
public class <subclass_name>
extends <superclass_name>
Example
public class Confirmed extends Ticket
{
}
Rules for Overriding Methods
v The method name and the order of arguments should be
identical to that of the superclass method.
v The return type of both the methods must be the same.
v The overriding method cannot be less accessible than the
method it overrides. For example, if the method to override is declared as
public in the superclass, you cannot override it with the private keyword in
the subclass.
v An overriding method cannot raise more exceptions than
those raised by the superclass.
Example
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j:
" + i + " " + j);
}
}
// Create a subclass by extending class
A.
class B extends A {
int k;
void showk() {
System.out.println("k: " +
k);
}
void sum() {
System.out.println("i+j+k: "
+ (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
// The superclass may be used by
itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of
superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all
public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of
subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j
and k in subOb:");
subOb.sum();
}
}
The output from this program is shown
here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
As you can see, the subclass B includes
all of the members of its superclass, A. This is why subOb can
access i and j and call showij ( ). Also, inside sum (
), i and j can be referred to directly, as if they were part
of B.
The general form of a class declaration
that inherits a superclass is shown here:
class subclass-name extends superclass-name
{
// body of class
}
You can only specify one superclass for
any subclass that you create. Java does not support the inheritance of multiple
superclasses into a single subclass. (This differs from C++, in which you can
inherit multiple base classes.) You can, as stated, create a hierarchy of
inheritance in which a subclass becomes a superclass of another subclass.
However, no class can be a superclass
of itself.
Q.
No. 4. Describe the catch and finally block statement with examples.
Answer:
The catch Block
You associate an exception-handler with
the try block by providing one or more catch handlers immediately after try
block. The following skeletal code illustrates the use of the catch block.
try
{
//statements that may cause an
exception
}
catch ()
{
// error handling code
}
The catch statement takes an object of
an exception class as a parameter. If an exception is thrown, the statements in
the catch block are executed. The scope of the catch block is restricted to the
statements in the preceding try block only.
The finally Block
When an exception is raised, the rest
of the statements in the try block are ignored. Sometimes, it is necessary to
process certain statements irrespective of whether an exception is raised or
not. The finally block is used for this purpose.
try
{
openFile();
writeFile(); //may cause an exception
}
catch (…..)
{
//process the exception
}
In the above example, the file has to
be closed irrespective of whether an exception is raised or not. You can place
the code to close the file in both the try and catch blocks. To avoid
duplication of code, you can place the code in the finally block. The code in
the finally block is executed regardless of whether an exception is thrown or
not. The finally block follows the catch blocks. You have only one finally
block for an exception-handler. However, it is not mandatory to have a finally
block.
finally
{
closeFile ();
}
Q. No. 5. Write a note on random access files and
serialization concept.
Answer: The term random
access means that data can be read from or written to random locations within a
file. In all the above mentioned streams,
data is read and written as a continuous stream of information. Java provides
the RandomAccessFile class to perform I/O operations at specified
locations within a file.
The RandomAccessFile class implements
the DataInput and DataOutput interfaces for performing I/O using
the primitive data types. The RandomAccessFile class also supports permissions
like read and write, and allows files to be accessed in read-only and
read-write modes.
Creating a Random Access File
There are two ways to create a random
access file - using the pathname as a string or using an object of the File
class.
RandomAccessFile (String pathname,
String mode);
RandomAccessFile (File name, String
mode);
Example:
randomFile = new RandomAccessFile (“iotets.txt”,”rw”);
or
File file1 = new File (“iotest.txt”);
RandomAccessFile randomFile = new
RandomAccessFile
(file1,”rw”);
(file1,”rw”);
The second argument is the mode
argument that determines whether you have read-only or read/write (rw) access
to the file.
Serialization:When you create a file using a text editor, it allows you
to store the text to a file. The text stored in the file is the data
encapsulated within the file object. This object is permanently available once
you store it on the disk. The capability of an object to exist beyond the
execution of the program that created is known as persistence.
In the above example, the file object
continues to exist even after the text editor stops executing. To make the file
object persistent, you have to carry out an important step: saving the file.
Saving the file object is called serialization. Serialization is
the key to implement persistence. It provides the capability for you to write
an object to a stream and read the object at a later stage.
JDK 1.2 provides the Serializable
interface in the java.io package to support object serialization. The
process of reading an object and writing it to a file stream is very simple.
The readObject() method of the ObjectInputStream class is used to
read objects from the stream.
The Objects that are read should be
cast to the appropriate class names. Similarly, the writeObject() method
of the ObjectOutputStream class writes objects to a stream.
Q. No. 6. Explain the following with examples:
1. The Connection Objects
2. The JDBC URL
3. The ResultSet Object
4. Using the PreparedStatement Object
Answer:
The Connection Objects
The Connection object represents
a connection with a database. You may have several Connection objects in an
application that connects to one or more databases.
Loading the JDBC-ODBC Bridge and
Establishing Connection
To establish a connection with a
database, you need to register the ODBC-JDBC Driver by calling the forName()
method from the Class class and then calling the getConnection()
method from the DriverManager class.
The JDBC URL
The JDBC URL is a string that provides
a way of identifying a database. A JDBC URL is divided into three parts:
<protocol>:<subprotocol>:<subname>
v <protocol> in a JDBC URL is always jdbc.
v <subprotocol> is the name of the
database connectivity mechanism. If the mechanism of retrieving the data is
ODBC-JDBC bridge, the subprotocol must be odbc.
v <subname> is used to identify the
database.
Example: JDBC URL
String url = “jdbc:odbc:MyDataSource”;
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(url);
The ResultSet Object
The ResultSet object provides you with
methods to access data from the table. Executing a statement usually generates
a ResultSet object. It maintains a cursor pointing to its current row of data.
Initially the cursor is positioned before the first row. The next()
method moves the cursor to the next row. You can access data from the ResultSet
rows by calling the getXXX() method where XXX is the data type.
The following code queries the database and process the ResultSet.
Using the PreparedStatement Object
You have to develop an application that
queries the database according to the search criteria specified by a user. For
example, the user supplies the publisher ID and wants to see the details of
that publisher.
select * from publishers where pub_id=?
To make it possible, you need to
prepare a query statement at runtime with an appropriate value in the where
clause.
The PreparedStatement object
allows you to execute parameterized queries. The PreparedStatement
object is created using the prepareStatement() method of the Connection
object.
stat=con.prepareStatement (“select * from
publishers where pub_id=?”);
Passing INPUT Parameters:
Before executing a PreparedStatement
object, you must set the value of each ‘?’ parameter. This is done by calling an appropriate setXXX()
method, where XXX is the data type of the parameter.
stat.setString(1, pid.getText());
ResultSet result=stat.executeQuery();
The following code makes use of the PreparedStatement
object :
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class PreparedQueryApp extends
Frame implements ActionListener
{
TextField pid;
TextField pname;
Button query;
static ResultSet result;
static Connection con;
static PreparedStatement stat;
public PreparedQueryApp()
{
super (“The Query
Application”);
setLayout (new GridLayout (5,1));
pid=new TextField (20);
pname=new TextField (50);
query=new Button (“Query”);
add(new Label (“Publisher ID:”));
add(pid);
add(new Label (“Publisher Name”));
add(pname);
add(query);
query.addActionListener (this);
pack ();
setVisible (true);
}
public static void main (String a[])
{
PreparedQueryApp obj =new
PreparedQueryApp ();
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Con=DriverManager.getConnection (“jdbc:odbc:MyDataSource”,”sa”,”“);
stat=con.prepareStatement (“select * from
publishers where pub_id =?”);
}
catch(Exception e){ }
obj.showRecord (result );
public void actionPerformed
(ActionEvent event)
{
if(event.getSource()==query)
{
try
{
stat.setString (1,pid.getText() );
result = stat.executeQuery();
result.next ();
}
catch(Exception e){}
showRecord (result);
}
}
public void showRecord (ResultSet
result)
{
try
{
pid.setText (result.getString(1));
pname.setText (result.getString(2));
}
catch (Exception e){}
}
}
In the above example:
v The PreparedStatement object is created using the prepareStatement()
method.
v The parameters of the PreparedStatement object are
initialized when the user clicks on the Query button.
v The query is then executed using the executeQuery()
method and the result is displayed in the corresponding controls.
No comments:
Post a Comment