17
OOPS With Java-1 1.Give the features of Java. Java defines data as objects with methods that support the objects. Java is purely object-oriented and provides abstraction, encapsulation, inheritance and polymorphism. Even the most basic program has a class. Any code that you write in Java is inside a class. Java is tuned for Web. Java programs can access data across the Web as easily as they access data from a local system. You can build distributed applications in Java that use resources from any other networked computer. Java is both interpreted and compiled. The code is complied to a bytecode that is binary and platform independent. When the program has to be executed, the code is fetched into the memory and interpreted on the user’s machine. As an interpreted language, Java has simple syntax. When you compile a piece of code, all errors are listed together. You can execute only when all the errors are rectified. An interpreter, on the other hand, verifies the code and executes it line by line. Only when the execution reaches the statement with error, the error is reported. This makes it easy for a programmer to debug the code. The drawback is that this takes more time than compilation. Compilation is the process of converting the code that you type, into a language that the computer understands – machine language. When you compile a program using a compiler, the compiler checks for syntactic errors in code and list all the errors on the

Bt0074 oops with java

Embed Size (px)

Citation preview

Page 1: Bt0074 oops with java

OOPS With Java-1

1.Give the features of Java.

Java defines data as objects with methods that support the objects. Java is purely object-oriented and provides abstraction, encapsulation, inheritance and polymorphism. Even the most basic program has a class. Any code that you write in Java is inside a class.

Java is tuned for Web. Java programs can access data across the Web as easily as they access data from a local system. You can build distributed applications in Java that use resources from any other networked computer.

Java is both interpreted and compiled. The code is complied to a bytecode that is binary and platform independent. When the program has to be executed, the code is fetched into the memory and interpreted on the user’s machine. As an interpreted language, Java has simple syntax.

When you compile a piece of code, all errors are listed together. You can execute only when all the errors are rectified. An interpreter, on the other hand, verifies the code and executes it line by line. Only when the execution reaches the statement with error, the error is reported. This makes it easy for a programmer to debug the code. The drawback is that this takes more time than compilation.

Compilation is the process of converting the code that you type, into a language that the computer understands – machine language. When you compile a program using a compiler, the compiler checks for syntactic 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 compiles the code to a bytecode that is understood by the Java environment.

Page 2: Bt0074 oops with java

Bytecode is the result of compiling a Java program. You can execute this code on any platform. In other words, due to the bytecode compilation process and interpretation by a browser, Java programs can be executed on a variety of hardware and operating systems. The only requirement is that the system should have a Java-enabled Internet browser. The Java interpreter can execute Java code directly on any machine on which a Java interpreter has been installed.

Thanks to bytecode, a Java program can run on any machine that has a Java interpreter. The bytecode supports connection to multiple databases. Java code is portable. Therefore, others can use the programs that you write in Java, even if they have different machines with different operating systems.

Java forces you to handle unexpected errors. This ensures that Java programs are robust (reliable), bug free and do not 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 interpreter-based language like BASIC since it is 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 a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded and dynamic language.’

2. How do you execute a Java program?

Page 3: Bt0074 oops with java

The programs that you write in Java should be saved in a file, which has the following name format: program is a set of instructions. In order to execute a program, the operating system needs to understand the language. The only language an operating system understands is in terms of 0’s and 1’s i.e. the binary language.

.Before the Java virtual machine (VM) can run a Java program, the program's Java source code must be compiled into byte-code using the javac compiler. Java byte-code is a platform independent version of machine code; the target machine is the Java VM rather than the underlying architecture. To compile a Java source code file Foo.java, you would do the following:

% javac -g Foo.java

The -g command line option is optional, but we recommend using it as it makes debugging easier.

If there are no errors in your source file, the Java compiler will produce one or more .class files (one .class file for each class defined in the Foo.java source file). For example, the results of a successful compile of Foo.java will produce a byte-code version of the class in a file named Foo.class.

Every public class that you write must be in a separate .java file where the first part of the file name is identical to the class name. The .java file additionally can contain code for protected and private classes.

In Java, the program is compiled into bytecode (.class file) that run on the Java Virtual Machine, which can interpret and run the program on any operating system. This makes Java programs platform-independent.

At the command prompt, type

javac <filename>.java

to compile the Java program.

Executing

When the code is compiled and error-free, the program can be executed using the command:

java <class filename>

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 OperatorsAddition, Subtraction, Multiplication, Division and Modulus are the various arithmetic operations that can be performed in Java.Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.

Page 4: Bt0074 oops with java

The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.

Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators:greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=).All relational operators are binary operators, and their operands are numeric expressions.

Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators. An example program is shown below that demonstrates the different relational operators in java.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 nameComparison operators are used to compare two values and give the resultsLogical operators are used to perform Boolean operations on the operands.Logical operators return a true

or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type. An example program is shown below that demonstrates the different Logical operators in java.Java provides Bit wise operators to manipulate the contents of variables at the bit level.

These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise

Page 5: Bt0074 oops with java

operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An example program is shown below that demonstrates the different Bit wise operators in java.

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

4. What are the various character extraction functions available in Java?

The String class provides a number of ways in which characters can be extracted from a String object. Each is examined here. Although the characters that comprise a string within a String object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero. charAt( )

Page 6: Bt0074 oops with java

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:

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

Page 7: Bt0074 oops with java

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?

Relationships are classified as followsA Kind-Of relationship.· A Is-A relationship.· A Part-Of-relationship.· A Has-A relationship.A-Kind-Of Relationship

Taking the example of a human being and an elephant, both are ‘kind-of’ mammals. As human beings and elephants are ‘kind-of’ mammals, they share the attributes and behaviors of mammals. Human being and elephants are subset of the mammals class. The following figure depicts the relationship between the Mammals and Human Being classes

Is-A Relationship

Let’s take an instance of the human being class – peter, who ‘is –a’ human being and, therefore, a mammal. The following figure depicts the ‘is –a’ relationship.

Page 8: Bt0074 oops with java

Has-A

Relationship/Part-Of Relationship

A human being has a heart. This represents has-a relationship. Heart is a part of the human being. This represents part-of relationship. The following figure depicts the relationship between a human being and a heart.

6. Differentiate between errors and exceptions.

The term exception denotes an exceptional event. It can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instruction.Error-handling becomes a necessity when you develop applications that need to take care of unexpected situations. The unexpected situations that may occur during program execution are:

· Running out of memory.

· Resource allocation errors.

· Inability to find a file.

· Problems in network connectivity.

If an above-mentioned situation is encountered, a program may stop working. You cannot afford to have an application stop working or crashing, if the

Page 9: Bt0074 oops with java

requested file is not present on the disk. Traditionally, programmers use return values of methods to detect the errors that has occurred at runtime. A variable errno was used for a numeric representation of the error. When multiple errors has occurred in a method, errno would have only one value-that of the last error that occurred in the method.

Java handles exceptions in the object-oriented way. You can use a hierarchy of exception classes to manage runtime errors.

The class at the top of the exception classes hierarchy is Throwable class. Two classes are derived from the Throwable class – Error and Exception. The Exception class is used for the exceptional conditions that has to be trapped in a program. The Error class defines a condition that does not occur under normal circumstances. In other words, the Error class is used for catastrophic failures such as VirtualMachineError. These classes are available in the java.lang package.

Java has several predefined exceptions. The most common exceptions that you may encounter are described below.

· Arithmetic Exception

This exception is thrown when an exceptional arithmetic condition has occurred. For example, a division by zero generates such an exception.

· NullPointer Exception

This exception is thrown when an application attempts to use null where an object is required. An object that has not been allocated memory holds a null value. The situations in which an exception is thrown include:

7. Give the syntax for FileInputStream and FileOutputStream classes.

These streams are classified as mode streams as they read and write data from disk files. The classes associated with these streams have constructors that allow you to specify the path of the file to which they are connected. The FileInputStream class allows you to read input from a file in the form of a stream. The FileOutputStream class allows you to write output to a file stream.Example:

Page 10: Bt0074 oops with java

FileInputStream inputfile = new FileInputStream (“Employee.dat”);

FileOutputStream outputfile = new FileOutputStream (“binus.dat”);

The BufferedInputStream and BufferedOutputStream Classes

The BufferedInputStream class creates and maintains a buffer for an input stream. This class is used to increase the efficiency of input operations. This is done by reading data from the stream one byte at a time. The BufferedOutputStream class creates and maintains a buffer for the output stream. Both the classes represent filter streams.

The DataInputStream and DataOutputStream Classes

The DataInputStream and DataOutputStream classes are the filter streams that allow the reading and writing of Java primitive data types.

The DataInputStream class provides the capability to read primitive data types from an input stream. It implements the methods presents in the DataInput interface.

8. What is an applet? Explain with an example.

An applet is a Java program that can be embedded in a web page. Java applications are run by using a Java interpreter. Applets are run on any browser that supports Java. Applets can also be tested using the appletviewer tool included in the Java Development Kit. In order to run an applet it must be included in a web page, using HTML tags. When a user browses a web server and it runs applets on the user’s system. Applets have certain restrictions put on them.· They can not read or write files on the user’s system.

· They can not load or run any programs stored on the user’s system.

All applets are subclasses of the Applet class in the java.applet package. Applets do not have main() method. All applets must be declared public. An applet displays information on the screen by using the paint method. This method is available in java.awt.Component class. This method takes an instance of the class Graphics as parameter. The browser creates an instance of Graphics class and passes to the method paint(). Graphics class provides a method drawString to display text. It also requires a position to be specified as arguments.

The Applet tag is used to embed an applet in an HTML document. The Applet

Page 11: Bt0074 oops with java

tag takes zero or more parameters.

The Applet Tag

The Applet tag is written in the body tag of an HTML document.

Syntax:

<APPLET

CODE = “name of the class file that extends java.applet.Applet”

CODEBASE = “path of the class file”

HEIGHT = “maximum height of the applet, in pixels”

WIDTH = “maximum width of the applet, in pixels”

VSPACE = “vertical space between the applet and the rest of the HTML”

HSPACE = “horizontal space between the applet and the rest of the HTML”

ALIGN = “alignment of the applet with respect to the rest of the web page”

ALT = “alternate text to be displayed if the browser does not support applets”

>

<PARAM NAME=“parameter_name” value=“value_of_parameter”>

……..

</APPLET>

The most commonly used attributes of the Applet tag are CODE, HEIGHT, WIDTH, CODEBASE and ALT. You can send parameters to the applet using the PARAM tag. The PARAM tag must be written between <APPLET> and </APPLET>

Example:

<applet

Code = “clock. class”

Height = 200

Page 12: Bt0074 oops with java

Width = 200 >

</applet>

9. Give the uses of adapter class.

The Java programming language provides adapter classes that implement the corresponding listener interfaces containing more than one method. The methods in these classes are empty. The listener class that you define can extend the Adapter class and override the methods that you need. The Adapter class is used for the WindowListener interface in the WindowAdapter class.

In the following program code, the adapter class has been used. This class has been used as an anonymous inner class to draw a rectangle within an applet. This example demonstrates the functionality of the mouse press. That is on every click of the mouse from top left corner, we get a rectangle on the release of the bottom right.Import java.applet.*;import java.awt.*;importjava.awt.event.*;

public class AdapterDemo extends Applet{public void init(){ addMouseListener(newMouseAdapter(){ int topX, bottomY;public void mousePressed(MouseEventme){topX=me.getX();bottomY=me.getY();}public voidmouseReleased(MouseEvent me){Graphics g = AdapterDemo.this.getGraphics();g.drawRect(topX, bottomY, me.getX()-topX, me.getY()-bottomY);}});}}

Page 13: Bt0074 oops with java

10. What is JDBC? Explain.

The JDBC API (Java Data Base Connectivity Application Program Interface) can access any kind of tabular data, especially data stored in a Relational Database. It works on top of ODBC (Open Data Base Connectivity) which was the driver for database connectivity since age old days but since ODBC was implemented in C so people from the VB background had some problems in understanding the implementation intricacies. Since JDBC works on top of ODBC we have something called as a JDBC-ODBC bridge to access the database. JDBC helps you to write Java applications that manage mainly three programming activities listed below namely:

a) connecting to a data source, like a database,b) sending queries and updating statements to the database and

c) retrieving and processing the results received from the database in answer to your query

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.

10.3 Database Management

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

Page 14: Bt0074 oops with java

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 thesame 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.