Bt0074 oops with java2

14
OOPS With Java-2 What is bytecode? Explain. 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.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.a Java Copy © Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Transcript of Bt0074 oops with java2

Page 1: Bt0074 oops with java2

OOPS With Java-2

What is bytecode? Explain.

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

Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode. This may come as a bit of surprise.Translating a Java program into bytecode helps it to run much easier in a wide variety of environments.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 2: Bt0074 oops with java2

The reason is straightforward: only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all interpret the same Java bytecode. If a Java program was compiled to native code, then different versions of the same program should exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the interpretation of bytecode is the easiest way to create truly portable programs.

2. How do you compile a Java program?

The programs that you write in Java should be saved in a file, which has the following name format: <class_name>.java

Compiling

A 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. Programs written in language such as C and C++ are converted to binary code during the compilation process. However, that binary code can be understood only by the operating system for which the program is compiled. This makes the program or application as operating system dependent.

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.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 3: Bt0074 oops with java2

3. What do you mean by operator precedence?

When more than one operator is used in an expression, Java will use operator precedence rule to determine the order in which the operators will be evaluated. For example, consider the following expression:Result=10+5*8-15/5

In the above expression, multiplication and division operations have higher priority over the addition and subtraction. Hence they are performed first. Now, Result = 10+40-3.

Addition and subtraction has the same priority. When the operators are having the same priority, they are evaluated from left to right in the order they appear in the expression. Hence the value of the result will become 47. In general the following priority order is followed when evaluating an expression:

· Increment and decrement operations.

· Arithmetic operations.

· Comparisons.

· Logical operations.

· Assignment operations.

To change the order in which expressions are evaluated, parentheses are placed around the expressions that are to be evaluated first. When the parentheses are nested together, the expressions in the innermost parentheses are evaluated first. Parentheses also improve the readability of the expressions. When the operator precedence is not clear, parentheses can be used to avoid any confusion.

4. What is an array? Explain with examples.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 4: Bt0074 oops with java2

An array represents a number of variables which occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All elements in an array must be of the same data type. For example, you cannot have one element with int data type and another belonging to the boolean data type in the same array. An array is a collection of elements of the same type that are referenced by a common name. Each element of an array can be referred to by an array name and a subscript or index. To create and use an array in Java, you need to first declare the array and then initialize it. The syntax for creating an array is:

data- type [ ] variablename;

Example:

int [ ] numbers;

The above statement will declare a variable that can hold an array of int type variables. After declaring the variable for the array, the array needs to be allocated in memory. This can be done using the new operator in the following way:

numbers = new int [10];

This statement assigns ten contiguous memory locations of the type int to the variable numbers. The array can store ten elements. Iteration can be used to access all the elements of the array, one by one.

5. How will you implement inheritance in Java?

Inheritance can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 5: Bt0074 oops with java2

specialized version of a superclass. Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. You can also define class members that are only exposed to other members of the same package. Using the keyword interface,

Inheritance is one of the cornerstones of object-oriented programming, because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.

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

· The method name and the order of arguments should be identical to that of the superclass method.

· The return type of both the methods must be the same.

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

· An overriding method cannot raise more exceptions than those raised by the superclass.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 6: Bt0074 oops with java2

6. Explain different kinds of Exceptions in Java.

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.

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 VirtualMachineErrorJava 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:

- Using an object without allocating memory for it.

- Calling the methods of a null object.

- Accessing or modifying the attributes of a null object.

· ArrayIndexOutOfBounds Exception

This exception is thrown when an attempt is made to access an array element beyond the index of the array. For example, if you try to access the eleventh element of an array that has only ten elements, the exception will be thrown.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 7: Bt0074 oops with java2

7. What are the uses of stream class?

Stream Classes are classified as FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream, DataInputStream, and DataOutputStream classes.The 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:

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 AWT? Explain.

The Abstract Windowing Toolkit, also called as AWT is a set of classes, enabling the user to create a user friendly, Graphical User Interface

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 8: Bt0074 oops with java2

(GUI). It will also facilitate receiving user input from the mouse and keyboard. The AWT classes are part of the java.awt package. The user interface consists of the following three:· Components – Anything that can be put on the user interface. This includes buttons, check boxes, pop-up menus, text fields, etc.

· Containers – This is a component that can contain other components.

· Layout Manager – These define how the components will be arranged in a container.

The statement import java.awt.*; imports all the components, containers and layout managers necessary for designing the user interface.

The AWT supplies the following components.

· Labels (java.awt.Label)

· Buttons (java.awt.Button)

· Checkboxes (java.awt.Checkbox)

· Single- line text field (java.awt.TextField)

· Larger text display and editing areas (java.awt.TextArea)

· Pop-up lists of choices (java.awt.Choice)

· Lists (java.awt.List)

· Sliders and scrollbars (java.awt.Scrollbar )

· Drawing areas (java.awt.Canvas)

· Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem )

· Containers (java.awt.Panel, java.awt.Window and its subclasses)

9. What are the different components of an event?

An event comprises of three components:

· Event Object – When the user interacts with the application by pressing a key or clicking a mouse button, an event is generated. The operating system traps this event and the data associated with it, for example, the time at which the event occurred, the event type (like a keypress or a mouseclick). This data is then passed on to the application to which the event belongs.

In Java, events are represented by objects that describe the events themselves.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 9: Bt0074 oops with java2

Java has a number of classes that describe and handle different categories of event.

· Event Source – An event source is an object that generates an event. For example, if you click on a button, an ActionEvent object is generated. The object of the ActionEvent class contains information about the event.

· Event-handler – An event-handler is a method that understands the event and processes it. The event-handler method takes an event object as a parameter.

10. Draw and explain the JDBC Application Architecture.

Connection to a DatabaseThe java.sql package contains classes that help in connecting to a database, sending SQL statements to the database, and processing query results.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 10: Bt0074 oops with java2

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 getConnection() method of the DriverManager class attempts to locate the driver that can connect to the database represented by the JDBC URL passed to the getConnection() method.

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>

· <protocol> in a JDBC URL is always jdbc.

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

· <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);

Using the Statement Object You can use the statement object to send simple queries to the database as shown in the sample QueryApp program.

The Statement object allows you to execute simple queries. It has the following three methods that can be used for the purpose of querying:

§ The executeQuery() method executes a simple query and returns a single ResultSet object.

§ The executeUpdate() method executes an SQL INSERT, UPDATE or DELETE statement.

§ The execute() method executes an SQL statement that may return multiple results.

The ResultSet Object

The ResultSet object provides you with methods to access data from the table.

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/

Page 11: Bt0074 oops with java2

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=?”);

The prepareStatement(), method of the Connection object takes an SQL statement as a parameter. The SQL statement can contain placeholders that can be replaced by INPUT parameters at runtime.

The ‘?’ symbols is a placeholder that can be replaced by the INPUT parameters at runtime.

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();

Copy© Milan K Antony | [email protected] | http://solveditpapers.blogspot.in/