SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
1
OOPS with Java
BT0074 Part 2
2
1.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.
3
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. 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:
4
<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.
5
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.
6
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.
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:
7
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?
8
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 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>
9
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.
6. Explain different kinds of Exceptions in Java.
10
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
VirtualMachineError
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:
11
- 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.
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”);
12
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 (GUI). It will also facilitate receiving user input
from the mouse and keyboard. The AWT classes are part of the
13
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)
14
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. 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.
15
10.Draw and explain the JDBC Application Architecture.
Connection to a Database
The java.sql package contains classes that help in connecting to a
16
database, sending SQL statements to the database, and processing
query results.
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”;
17
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. 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
18
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();

Mais conteúdo relacionado

Mais procurados (20)

Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java platform
Java platformJava platform
Java platform
 
Java notes
Java notesJava notes
Java notes
 
Java notes
Java notesJava notes
Java notes
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java notes
Java notesJava notes
Java notes
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Java Notes
Java Notes Java Notes
Java Notes
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 
Java basic
Java basicJava basic
Java basic
 
Introduction
IntroductionIntroduction
Introduction
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 

Destaque

Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Techglyphs
 
Bt8901 objective oriented systems2
Bt8901 objective oriented systems2Bt8901 objective oriented systems2
Bt8901 objective oriented systems2Techglyphs
 
Bt0064 logic design1
Bt0064 logic design1Bt0064 logic design1
Bt0064 logic design1Techglyphs
 
Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)Techglyphs
 
Bt0064 logic design2
Bt0064 logic design2Bt0064 logic design2
Bt0064 logic design2Techglyphs
 
Bt0066 database management system2
Bt0066 database management system2Bt0066 database management system2
Bt0066 database management system2Techglyphs
 
Bt0066 database management system1
Bt0066 database management system1Bt0066 database management system1
Bt0066 database management system1Techglyphs
 
Bt9002 Grid computing 2
Bt9002 Grid computing 2Bt9002 Grid computing 2
Bt9002 Grid computing 2Techglyphs
 
Bt9002 grid computing 1
Bt9002 grid computing 1Bt9002 grid computing 1
Bt9002 grid computing 1Techglyphs
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Techglyphs
 
Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)Techglyphs
 
Elements analysis dfd_er_std
Elements analysis dfd_er_stdElements analysis dfd_er_std
Elements analysis dfd_er_stdAmmar Jamali
 

Destaque (12)

Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
Bt8901 objective oriented systems2
Bt8901 objective oriented systems2Bt8901 objective oriented systems2
Bt8901 objective oriented systems2
 
Bt0064 logic design1
Bt0064 logic design1Bt0064 logic design1
Bt0064 logic design1
 
Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)Bt0062 fundamentals of it(1)
Bt0062 fundamentals of it(1)
 
Bt0064 logic design2
Bt0064 logic design2Bt0064 logic design2
Bt0064 logic design2
 
Bt0066 database management system2
Bt0066 database management system2Bt0066 database management system2
Bt0066 database management system2
 
Bt0066 database management system1
Bt0066 database management system1Bt0066 database management system1
Bt0066 database management system1
 
Bt9002 Grid computing 2
Bt9002 Grid computing 2Bt9002 Grid computing 2
Bt9002 Grid computing 2
 
Bt9002 grid computing 1
Bt9002 grid computing 1Bt9002 grid computing 1
Bt9002 grid computing 1
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
 
Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)Bt0062 fundamentals of it(2)
Bt0062 fundamentals of it(2)
 
Elements analysis dfd_er_std
Elements analysis dfd_er_stdElements analysis dfd_er_std
Elements analysis dfd_er_std
 

Semelhante a Bt0074 oops with java2

Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questionsGradeup
 
MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionNarinder Kumar
 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1SURBHI SAROHA
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.netJanbask ItTraining
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
 
Unit of competency
Unit of competencyUnit of competency
Unit of competencyloidasacueza
 
Top 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfTop 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfUmesh Kumar
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 

Semelhante a Bt0074 oops with java2 (20)

Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall session
 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
Java notes
Java notesJava notes
Java notes
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
Top 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfTop 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdf
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 

Mais de Techglyphs

Bt0068 computer organization and architecture
Bt0068 computer organization and architecture Bt0068 computer organization and architecture
Bt0068 computer organization and architecture Techglyphs
 
Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2Techglyphs
 
Bt0070 operating systems 1
Bt0070 operating systems  1Bt0070 operating systems  1
Bt0070 operating systems 1Techglyphs
 
Bt0070 operating systems 2
Bt0070 operating systems  2Bt0070 operating systems  2
Bt0070 operating systems 2Techglyphs
 
Bt0072 computer networks 1
Bt0072 computer networks  1Bt0072 computer networks  1
Bt0072 computer networks 1Techglyphs
 
Bt0072 computer networks 2
Bt0072 computer networks  2Bt0072 computer networks  2
Bt0072 computer networks 2Techglyphs
 
Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Techglyphs
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Techglyphs
 
Bt0077 multimedia systems
Bt0077 multimedia systemsBt0077 multimedia systems
Bt0077 multimedia systemsTechglyphs
 
Bt0078 website design
Bt0078 website design Bt0078 website design
Bt0078 website design Techglyphs
 
Bt0077 multimedia systems2
Bt0077 multimedia systems2Bt0077 multimedia systems2
Bt0077 multimedia systems2Techglyphs
 
Bt0078 website design 2
Bt0078 website design 2Bt0078 website design 2
Bt0078 website design 2Techglyphs
 
Bt0080 fundamentals of algorithms1
Bt0080 fundamentals of algorithms1Bt0080 fundamentals of algorithms1
Bt0080 fundamentals of algorithms1Techglyphs
 
Bt0080 fundamentals of algorithms2
Bt0080 fundamentals of algorithms2Bt0080 fundamentals of algorithms2
Bt0080 fundamentals of algorithms2Techglyphs
 
Bt0081 software engineering
Bt0081 software engineeringBt0081 software engineering
Bt0081 software engineeringTechglyphs
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2Techglyphs
 
Bt0081 software engineering2
Bt0081 software engineering2Bt0081 software engineering2
Bt0081 software engineering2Techglyphs
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basicTechglyphs
 

Mais de Techglyphs (18)

Bt0068 computer organization and architecture
Bt0068 computer organization and architecture Bt0068 computer organization and architecture
Bt0068 computer organization and architecture
 
Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2Bt0068 computer organization and architecture 2
Bt0068 computer organization and architecture 2
 
Bt0070 operating systems 1
Bt0070 operating systems  1Bt0070 operating systems  1
Bt0070 operating systems 1
 
Bt0070 operating systems 2
Bt0070 operating systems  2Bt0070 operating systems  2
Bt0070 operating systems 2
 
Bt0072 computer networks 1
Bt0072 computer networks  1Bt0072 computer networks  1
Bt0072 computer networks 1
 
Bt0072 computer networks 2
Bt0072 computer networks  2Bt0072 computer networks  2
Bt0072 computer networks 2
 
Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1Bt0075 rdbms with mysql 1
Bt0075 rdbms with mysql 1
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
 
Bt0077 multimedia systems
Bt0077 multimedia systemsBt0077 multimedia systems
Bt0077 multimedia systems
 
Bt0078 website design
Bt0078 website design Bt0078 website design
Bt0078 website design
 
Bt0077 multimedia systems2
Bt0077 multimedia systems2Bt0077 multimedia systems2
Bt0077 multimedia systems2
 
Bt0078 website design 2
Bt0078 website design 2Bt0078 website design 2
Bt0078 website design 2
 
Bt0080 fundamentals of algorithms1
Bt0080 fundamentals of algorithms1Bt0080 fundamentals of algorithms1
Bt0080 fundamentals of algorithms1
 
Bt0080 fundamentals of algorithms2
Bt0080 fundamentals of algorithms2Bt0080 fundamentals of algorithms2
Bt0080 fundamentals of algorithms2
 
Bt0081 software engineering
Bt0081 software engineeringBt0081 software engineering
Bt0081 software engineering
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2
 
Bt0081 software engineering2
Bt0081 software engineering2Bt0081 software engineering2
Bt0081 software engineering2
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
 

Último

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Último (20)

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

Bt0074 oops with java2

  • 2. 2 1.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.
  • 3. 3 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. 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:
  • 4. 4 <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.
  • 5. 5 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.
  • 6. 6 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. 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:
  • 7. 7 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?
  • 8. 8 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 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>
  • 9. 9 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. 6. Explain different kinds of Exceptions in Java.
  • 10. 10 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 VirtualMachineError 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:
  • 11. 11 - 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. 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”);
  • 12. 12 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 (GUI). It will also facilitate receiving user input from the mouse and keyboard. The AWT classes are part of the
  • 13. 13 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)
  • 14. 14 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. 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.
  • 15. 15 10.Draw and explain the JDBC Application Architecture. Connection to a Database The java.sql package contains classes that help in connecting to a
  • 16. 16 database, sending SQL statements to the database, and processing query results. 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”;
  • 17. 17 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. 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
  • 18. 18 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();