1. NAME:- MOHD. SHAHNAWAZ ALAM
ROLL NO:-
COURSE:-B.SC (IT)
SEMESTER: - THIRD
BOOK NO:- BT0074(OOPS WITH JAVA)
SESSION:- SPRING 2012
1. Give the features of Java.
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the
important key feature of java language that makes java as the most powerful language.
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of
the important key feature of java language that makes java as the most powerful
language. Not even a single language is idle to this feature but java is more closer to
this feature. The programs written on one platform can run on any platform provided the
platform must have the JVM.
Simple
There are various features that makes the java as a simple language. Programs are
easy to write and debug because java does not use the pointers explicitly. It is much
harder to write the java programs that can crash the system but we can not say about
the other programming languages. Java provides the bug free system due to the strong
memory management. It also has the automatic memory allocation and deallocation
system.
Object Oriented
To be an Object Oriented language, any language must follow at least the four
characteristics.
2. Inheritance : It is the process of creating the new classes and using the behavior
of the existing classes by extending them just to reuse the existing code and
adding the additional features as needed.
Encapsulation: : It is the mechanism of combining the information and providing
the abstraction.
Polymorphism: : As the name suggest one name multiple form, Polymorphism is
the way of providing the different functionality by the
functions having the same name based on the signatures of the methods.
Dynamic binding : Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.
As the languages like Objective C, C++ fulfills the above four characteristics yet they
are not fully object oriented languages because they are structured as well as object
oriented languages. But in case of java, it is a fully Object Oriented language because
object is at the outer most level of data structure in java. No stand alone methods,
constants, and variables are there in java. Everything in java is object even the primitive
data types can also be converted into object by using the wrapper class.
Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It
provides the powerful exception handling and type checking mechanism as compare to
other programming languages. Compiler checks the program whether there any error
and interpreter checks any run time error and makes the system secure from crash. All
of the above features makes the java language robust.
Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet
programmers can call functions on these protocols and can get access the files from
any remote machine on the internet rather than writing codes on their local system.
Portable
The feature Write-once-run-anywhere makes the java language portable provided that
the system must have interpreter for the JVM. Java also have the standard data size
irrespective of operating system or the processor. These features makes the java as a
portable language.
3. Dynamic
While executing the java program the user can get the required files dynamically from a
local drive or from a computer thousands of miles away from the user just by connecting
with the Internet.
Secure
Java does not use memory pointers explicitly. All the programs in java are run under an
area known as the sand box. Security manager determines the accessibility options of a
class like reading and writing a file to the local disk. Java uses the public key encryption
system to allow the java applications to transmit over the internet in the secure
encrypted form. The bytecode Verifier checks the classes after loading.
Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted the performance slow but the advance version of
JVM uses the adaptive and just in time compilation technique that improves the
performance.
Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you
will be more delighted to know another feature of Java which is Multithreaded.
Java is also a Multithreaded programming language. Multithreading means a single
program having different threads executing independently at the same time. Multiple
threads execute instructions according to the program code in a process or a program.
Multithreading works the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded
programs not even a single thread disturbs the execution of other thread. Threads are
obtained from the pool of available ready to run threads and they run on the system
CPUs. This is how Multithreading works in Java which you will soon come to know in
details in later chapters.
Interpreted
We all know that Java is an interpreted language as well. With an interpreted language
such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into
computations. Thus, Java as an interpreted language depends on an interpreter
4. program.
The versatility of being platform independent makes Java to outshine from other
languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality.
Due to this any error occurring in the program gets traced. This is how it is different to
work with Java.
Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural
neutral language as well. The growing popularity of networks makes developers think
distributed. In the world of network it is essential that the applications must be able to
migrate easily to different computer systems. Not only to computer systems but to a
wide variety of hardware architecture and Operating system architectures as well. The
Java compiler does this by generating byte code instructions, to be easily interpreted on
any machine and to be easily translated into native machine code on the fly. The
compiler generates an architecture-neutral object file format to enable a Java
application to execute anywhere on the network and then the compiled code is
executed on many processors, given the presence of the Java runtime system. Hence
Java was designed to support applications on network. This feature of Java has thrived
the programming language.
2. How do you execute a Java program?
Most often in your Java programs you will find a need to execute system DOS commands.
You can execute any system commands that are OS specific and then read the output of
the system command from your Java program for further processing within the Java
program.
This sample Java Program executes the 'dir' command reads the output of the dir
command prints the results. This is just for understanding the concept, however, you may
execute just about any command using this Runtime.getRuntime().exec() command.
import java.io.*;
public class doscmd
6. }
3. What are the different types of operators used in Java?
Operators play an important role in Java. There are three kinds of operators in Java. They are (i)
Arithmetic Operators (ii) Comparison / Relational Operators and (iii) Logical Operators
3.2.1 Arithmetic Operators
Addition, Subtraction, Multiplication, Division and Modulus are the various arithmetic
operations that can be performed in Java.
Table 3.1: List of Arithmetic Operators
Operator Meaning Use Meaning
+ Addition op1+op2 Adds op1 and op2
- Subtraction op1-op2 Subtracts op2 from op1
* Multiplication op1*op2 Multiplies op1 and op2
/ Division op1/op2 Divides op1 by op2
% Modulus op1 % op2 Computes the remainder of
dividing op1 by op2
3.2.2 Increment and Decrement Operators
The increment operator is ++ and decrement operator is –. This is used to add 1 to the value of a
variable or subtract 1 from the value of a variable. These operators are placed either before the
variable or after the variable name. The example below shows the use of these operators.
Figure 3.4: Program Compilation and Running
When the operator ++ is placed after the variable name, first the assignment of the value of the
variable takes place and then the value of the variable is incremented. This operation is also
called post increment. Therefore the value of y1 will remain as 5 and the value of x1 will be 6.
When the operator is placed before the variable, first increment of the variable takes place and
then the assignment occurs. Hence the value x2 and y2 both will be 6. This operation is also
called as pre increment. Similarly – – operator can be used to perform post decrement and pre
decrement operations. If there is no assignment and only the value of variable has to be
incremented or decremented then placing the operator after or before does not make difference.
7. 3.2.3 Comparison Operators
Comparison operators are used to compare two values and give the results.
Table 3.2: List of Comparison Operators in Java
Operator Meaning Example Remarks
== Equal op1 = = op2 Checks if op1 is equal to
op2
!= Not Equal op1 != op2 Checks if op1 is not equal
to op2
< Less than op1 < op2 Checks if op1 is less than
op2
> Greater than op1 > op2 Checks if op1 is greater
than op2
<= Less than or equal op1 <= op2 Checks if op1 is less than
or equal to op2
>= Greater than or equal op1 >= op2 Checks if op1 is greater
than or equal to op2
3.2.4 Logical Operators
Logical operators are used to perform Boolean operations on the operands.
Table 3.3: List of Logical Operators in Java
Operator Meaning Example Remarks
&& Short-circuit AND op1 && op2 Returns true if both are true. If
op1 is false, op2 will not be
evaluated and returns false.
|| Short-circuit OR op1 || op2 Returns true if anyone is true.
If op1 is true, op2 will not be
evaluated and returns true.
! Logical unary NOT !op Returns true if op is false.
& Logical AND Op1 & op2 Returns true if both are true.
Always op1 and op2 will be
evaluated.
| Logical OR Op1 | op2 Returns true if anyone is true.
Always op1 and op2 will be
evaluated.
4. What are the various character extraction functions available in
Java?
8. charAt( )
To extract a single character from a String, you can refer directly to an individual character via the
charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must be
nonnegative and specify a location within the string. charAt( ) returns the character at the specified
location. For example,
char ch;
ch = "abc".charAt(1);
assigns the v0alue "b" to ch.
getChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method. It has
this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an
index that is one past the end of the desired substring. Thus, the substring contains the characters
from sourceStart through sourceEnd–1. The array that will receive the characters is specified by
target. The index within target at which the substring will be copied is passed in targetStart. Care
must be taken to assure that the target array is large enough to hold the number of characters in the
specified substring. The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Here is the output of this program:
9. demo
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is
called getBytes( ), and it uses the default character-to-byte conversions provided by the platform.
Here is its simplest form:
byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a
String value into an environment that does not support 16-bit Unicode characters. For example,
most Internet protocols and text file formats use 8-bit ASCII for all text interchange.
toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest way is
to call toCharArray( ). It returns an array of characters for the entire string. It has this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the
same result.
5. What are the various types of relationships?
Java represents two types of relationships:-
1.IS-A relationship
2.HAS-A relationship
IS-A Relationship:-In object oriented programming,the concept of IS-A is a totally based on
Inheritance(extends) and Interface implementation(implements).It is just like saying "A is a B type of
thing".For example ,5-Star is a chocolate,Subaru Impreza is a car etc.
It is key point to note that you can easily identify the IS-A relationship .Wherever you see an extends
keyword or implements keyword in a class declaration,then this class is said to be passed IS-A
relationship.
For Example:-
class Car{
10. // lots of complex work
}
class Impreza extends Car{
//Impreza extends and thus inherit all methods from Car (except final and static)
//Impreza can also define all his specific functionality
}
From the above code we can say "Car is a Vehicle","Impreza is a Car", this in turn reflects a transitive
relationship that "Impreza is a Vehicle".
The relationship can be shown as below:-
Arrow direction from subclass to super class
HAS-A Relationship:-HAS-A relationship has nothing to do with Inheritance rather it is based on the
usage of various variables and methods of other class.We can say "A HAS-A B if the code in class A has
reference to an instance of B".Make it more clear look at following example:-
public class Car{}
class Impreza extends Car{
private Subaru_feature subaru_features;
}
As you can see Impreza HAS-A instance variable of type Subaru.That is we can say "Impreza HAS-A
Subaru_feature ".Simply here Impreza has a reference type of Subaru_feature.Impreza can use the
reference variable to invoke the subaru features without caring about the Subaru_feature code.HAS-A
relationship is indicated by following figure:-
11. HAS-A relationship makes each and every class a specialist class.Making specialists classes has
numerous benefits including reduction in bugs,easily tractable errors,Less complex code,reduction in
code redundancy and most of code is easily understandable.The more specialist a class is the code reuse
is even better.Its a good Object Oriented practice to use HAS-A relationship
6. Differentiate between errors and exceptions.
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory
error. These JVM errors and you can not repair them at runtime.Though error can
be caught in catch block but the execution of application will come to a halt and is
not recoverable.
While exceptions are conditions that occur because of bad input etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the
cases it is possible to recover from an exception (probably by giving user a
feedback for entering proper values etc.)
7. Give the syntax for FilelnputStream and FileOutputStream
classes.
FileInputStream.read
Syntax 1
public native int read() throws IOException
Returns
the next byte of data, or -1 if the end of the file is reached.
Description
Reads a byte of data from this input stream. This method blocks if no input is yet available.
12. Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream
FileOutputStream.FileOutputStream
Syntax 1
public FileOutputStream( String name ) throws IOException
Parameters
name
the system-dependent filename.
Description
Creates an output file stream to write to the file with the specified name.
Exceptions
IOException if the file could not be opened for writing.
Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the
name argument to see if the application is allowed write access to the file.
8. What is an applet? Explain with an example.
Applet is java program that can be embedded into HTML pages. Java applets runs on the java
enables web browsers such as mozila and internet explorer. Applet is designed to run remotely
on the client browser, so there are some restrictions on it. Applet can't access system resources
on the local computer. Applets are used to make the web site more dynamic and entertaining.
Example program
import java.awt.*;
import java.applet.*;
public class HelloJavaProgram extends Applet{
String str;
Public void init()
13. {
str=getParameter (“String”);
if(str==null)
str=”Java”;
str=”Hello” + str;
}
public void paint(Graphics g)
{
g.drawString (str,10,100);
}
}
Compile this program and the .class file will be generated.
HTML file for HelloJavaProgram applet
<html>
<head>
<title> Welcome to Java Applet </title>
</head>
<body>
<applet code=” HelloJavaProgram.class” width= 400 height=200>
<param name=”String” value=”Applet!”>
</applet>
</body>
</html>
Save this file as HelloJavaParam.html and then run applet using the applet viewer as follows:
appletviewer HelloJavaProgram.html
9. Give the use of adapter class.
In java programming language, adapter class is used to implement an interface having a set of
dummy methods. The developer can then further subclass the adapter class so that he can
override to the methods he requires. Implementing an interface directly, requires to write all the
dummy methods. In general an adapter class is used to rapidly construct your own Listener
class to field events.
Java programming language also have a design adapter named adapter. The Adapter design
pattern is also used to join to two unrelated interfaces so that can work together. The joint
between these two interfaces is termed as Adapter. This is something like the conversion of
interface of one class into interface. This is done by using an Adapter.
10. What is JDBC? Explain.
14. JDBC is Java application programming interface that allows the Java programmers to access
database management system from Java code. It was developed by JavaSoft, a subsidiary of
Sun Microsystems
Java Database Connectivity in short called as JDBC. It is a java API which enables the java
programs to execute SQL statements. It is an application programming interface that defines
how a java programmer can access the database in tabular format from Java code using a set
of standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple
implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in Relational
Database Management system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the
correct Java packages and drivers and registering them with the JDBC Driver Manager that is
used as a connection factory for creating JDBC connections which supports creating and
executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the
backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know that
Java is platform independent, so JDBC makes it possible to write a single database application
that can run on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for
accessing and managing database, but the difference is that JDBC is designed specifically for
Java programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to
your query.