What Is Java? Define Five Features of Java?
What Is Java? Define Five Features of Java?
Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of two key
Sun software assets: Java and Solaris.
Java Today
Today Java is a commonly used foundation for developing and delivering content on the Web.
According to Oracle, there are more than 9 million Java developers worldwide and more than 3
billion mobile phones run Java.
In 2014 one of the most significant changes to the Java language was launched with Java SE 8.
Changes included additional functional programming features, parallel processing using
streams and improved integration with JavaScript. The 20th anniversary of commercial Java
was celebrated in 2015.
Java programming language was originally developed by Sun Microsystems which was initiated by James
Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its
widespread popularity, multiple configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to
be Write Once, Run Anywhere.
Java is −
Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based
on the Object model.
Platform Independent − Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
Multithreaded − With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
Interpreted − Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high performance.
Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to
an evolving environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.
In the above application example we are using public static void main. Each word has a different
meaning and purpose.
Public : is an Access Modifier, which defines who can access this Method. Public means that this
Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or variable is
not instance related but Class related. It can be accessed without creating the instance of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return. Void
means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for an
application with a particular signature only.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several words are
used to form a name of the class, each inner word's first letter should be in Upper Case.
Method Names − All method names should start with a Lower Case letter. If several words are
used to form the name of the method, then each inner word's first letter should be in Upper
Case.
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and
append '.java' to the end of the name (if the file name and the class name do not match, your program
will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main() method
which is a mandatory part of every Java program.
4. What is JVM?
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation provider
is independent to choose the algorithm. Its implementation has been provided by Sun and other
companies.
3. Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What it does
o Loads code
o Verifies code
o Executes code
o Memory area
o Register set
o Garbage-collected heap
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.
1) Classloader
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.
3) Heap
Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation
and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
PC (program counter) register. It contains the address of the Java virtual machine instruction currently
being executed.
7) Execution Engine
It contains:
1) A virtual processor
3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
5. What is JRE?
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at
runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
6. What is JDK?
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
7. Define Object and Class in Java?
In this page, we will learn about java objects and classes. In object-oriented programming technique, we
design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It
can be physical or logical (tengible and intengible). The example of integible object is banking system.
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to
write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
o data member
o method
o constructor
o block
o class and interface
1. class <class_name>{
2. data member;
3. method;
4. }
In this example, we have created a Student class that have two data members id and name. We are
creating the object of the Student class by new keyword and printing the objects value.
1. class Student1{
4.
7. System.out.println(s1.id);
8. System.out.println(s1.name);
9. }
10. }
Non-static methods
Static methods
These method never be preceded by static keyword These method always preceded by static keyword
Example: Example:
1 { {
...... ......
...... ......
} }
It is specific to an object so that these are also known as These are common to every object so that it is also known as
3
instance method. member method or class method.
These methods always access with object reference These property always access with class reference
4 Syntax: Syntax:
Objref.methodname(); className.methodname();
If any method wants to be execute multiple time that can If any method wants to be execute only once in the program that
5
be declare as non static. can be declare as static .
Note: In some cases static methods not only can access with class reference but also can access with
object reference
o wait()
o notify()
o notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
Method
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
A variable that is declared as final and not initialized is called a blank final variable. A blank final
variable forces the constructors to initialise it.
Methods declared as final cannot be overridden. In methods private is equal to final, but in
variables it is not.
final parameters – values of the parameters cannot be changed after initialization. Do a small
java exercise to find out the implications of final parameters in method overriding.
Java local classes can only reference local variables and parameters that are declared as final.
A visible advantage of declaring a java variable as static final is, the compiled java class results in
faster performance.
‘final’ should not be called as constants. Because when an array is declared as final, the state of the
object stored in the array can be modified. You need to make it immutable in order not to allow
modifcations. In general context constants will not allow to modify. In C++, an array declared as const
will not allow the above scenario but java allows. So java’s final is not the general constant used across
in computer languages.
A variable that is declared static final is closer to constants in general software terminology. You must
instantiate the variable when you declare it static final.
Tokens are the various Java program elements which are identified by the compiler. A token is the
smallest element of a program that is meaningful to the compiler. Tokens supported in Java include
keywords, variables, constants, special characters, operations etc.
When you compile a program, the compiler scans the text in your source code and extracts individual
tokens. While tokenizing the source file, the compiler recognizes and subsequently removes
whitespaces (spaces, tabs, newline and form feeds) and the text enclosed within comments
In the given example there are some identifiers have been used like byteident, shortident, intident,
longident, charident, stringident, floatident, doubleident. And there are some primitive data types of
used identifiers have been also used in the program like byte, short, int, long, float, double,
char and String.
In addition to the rules that governs identifiers, Java programmers follow certain style conventions to
make up names for classes, methods, constants, variables, interfaces and packages.
1. Class names in Java begins with a capital letter. Class names should be descriptive names or noun
phrases but not very long. If class name contains multiple words then each subsequent word in the class
name begins with a capital letter. For example: Employee, GradeBook, CommissionEmployee,
ProcessExamResult etc.
2. Names of the fields that are not final and method's name should begin with a lowercase letter.
Method names should be verbs or verb phrases. However, if they contain multiple words then each
subsequent word in the name begins with a capital letter. For example: firstName, salary, getName,
getMaximum etc.
3. Names of the packages intended only for local use should have a first identifier that begins with a
lowercase letters.
4. Constant represent fixed values that cannot be altered. For example, PI is constant with a fixed value
3.14159. Such constants should be written in uppercase
Some Memory or Some New Memory is Allocated to Class Object For Storing data and member
functions of Class So Every Object Must be Created With the Help of New Keyword So For Allocating
New Memory Area .
Type Conversion is that which converts the one data type into another for example converting a int into
float converting a float into double The Type Conversion is that which automatically converts the one
data type into another but remember we can store a large data type into the other for ex we can t store
a float into int because a float is greater than int Type Conversion is Also Called as Promotion of data
Because we are Converting one Lower data type into higher data type So this is Performed
Automatically by java compiler
Type Casting
When a user can convert the one higher data type into lower data type then it is called as the type
casting Remember the type Conversion is performed by the compiler but a casting is done by the user
for ex converting a float into int Always Remember that when we use the Type Conversion then it is
called the promotion when we use the type casting means when we convert a large data tote into
another then it is called as the demotion when we use the type casting then we can loss some data. Like
We are converting float into int then it will Truncate the Fractional part from the data Like (int) 123.78
Will gives use only 123 this will Truncate the Fractional Part and Returns only Int value
Documentation Section
It includes the comments to tell the program's purpose. It improves the readability of the program.
Package Statement
Import statements
It includes statements used for referring classes and interfaces that are declared in other packages.
Interface Section
It describes information about user defines classes present in the program. Every Java program consists
of at least one class definition. This class definition declares the main method. It is from where the
execution of program actually starts.
1. DOCUMENTATION Section: It includes the comments that improve the readability of the program. A
comment is a non-executable statement that helps to read and understand a program especially when
your programs get more complex. It is simply a message that exists only for the programmer and is
ignored by the compiler. A good program should include comments that describe the purpose of the
program, author name, date and time of program creation. This section is optional and comments may
appear anywhere in the program.
Single line (or end-of line) comment: It starts with a double slash symbol (//) and terminates at the end
of the current line. The compiler ignores everything from // to the end of the line. For example:
Multiline Comment: Java programmer can use C/C++ comment style that begins with delimiter /* and
ends with */. All the text written between the delimiter is ignored by the compiler. This style of
comments can be used on part of a line, a whole line or more commonly to define multi-line comment.
For example.
Comments cannot be nested. In other words, you cannot comment a line that already includes
traditional comment. For example,
Documentation comments: This comment style is new in Java. Such comments begin with
delimiter /** and end with */. The compiler also ignores this type of comments just like it ignores
comments that use / * and */. The main purpose of this type of comment is to automatically generate
program documentation. The java doc tool reads these comments and uses them to prepare your
program's documentation in HTML format. For example.
PACKAGE STATEMENT: Java allows you to group classes in a collection known as package. A package
statement includes a statement that provides a package declaration. It must appear as the first
statement in the source code file before any class or interface declaration. This statement is optional.
For example: Suppose you write the following package declaration as the first statement in the source
code file.
package employee;
This statement declares that all classes and interfaces defined in this source file are part of the
employee package. Only one package declaration can appear in the source file.
IMPORT STATEMENT: Java contains many predefined classes that are stored into packages. In order to
refer these standard predefined classes in your program, you need to use fully qualified name (i.e.
Packagename.className). But this is a very tedious task as one need to retype the package path name
along with the classname. So a better alternative is to use an import statement.
An import statement is used for referring classes that are declared in other packages. The import
statement is written after a package statement but before any class definition. You can import a specific
class or all the classes of the package. For example : If you want to import Date class of java.util package
using import statement then write
import java.util.Date;
This statement allows the programmer to use the simple classname Date rather than fully qualified
classname java.util.Date in the code.
Unlike package statement, you can specify more than one import statement in your program.
For example:
// package
INTERFACE SECTION: In the interface section, we specify the interfaces. An interface is similar to a class
but contains only constants and method declarations. Interfaces cannot be instantiated. They can only
be implemented by classes or extended by other interfaces. It is an optional section and is used when
we wish to implement multiple inheritance feature in the program.
interface stack
CLASS SECTION: The Class section describes the information about user-defined classes present in the
program. A class is a collection of fields (data variables) and methods that operate on the fields. Every
program in Java consists of at least one class, the one that contains the main method. The main ()
method which is from where the execution of program actually starts and follow the statements in the
order specified.
The main method can create objects, evaluate expressions, and invoke other methods and much more.
On reaching the end of main, the program terminates and control passes back to the operating system.
After discussing the structure of programs in Java, we shall now discuss a program that displays a string
Hello Java on the screen.
class HelloJava
System.out.println("Hello Java");
1) Integer
2) Float
3) Character
These are used When a List Contains Elements those are String in nature and we wants to convert them
into primitives data type then we have to use Wrapper Class Wrapper Classes will First Convert the
String into the object data type eithet it may beint, float ,char etc and after that we will be able to
convert the object data type into primitives date type Many Times we were using Wrapper Class Like
Integer.parseInt(“123”) This is also a Wrapper Class (Integer) For Converting a String into int data type
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
class Vehicle{
int speed=50;
int speed=100;
void display(){
}
public static void main(String args[]){
b.display();
6. this keyword can also be used to return the current class instance.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
\
Checked Exception in Java is all those Exception which requires being catches and handled
during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws
Compilation error. Now Which Exception is checked Exception and Why Checked Exception are
introduced in first place? All the Exception which are direct sub Class of Exception but not
inherit RuntimeException are Checked Exception.
While doing File Programming in C++ I found that most of the time programmer forgets to close file
descriptors , which often result in locking of file on OS level. Since Java is introduced after C++, designers
of Java thought to ensure such mistakes are not allowed and resources opened are closed properly. To
ensure this they introduced Checked Exception. If you see most of File IO related operation comes under
IOException which is checked one. Though is a special scenario related to Checked Exception but you
can generalize this as, where Java sees an opportunity of failure more, they ensure that programmer
provide recovery strategy or at least handle those scenario gracefully.
Since a picture is worth 1000 words I have put together Exception hierarchy in mind map which clearly
says which Exceptions are checked and which Exceptions are unchecked.
When to use Checked Exception in Java
Knowing Checked Exception is not that useful until you know how to use Checked Exception in Java.
Java has often been criticized for its Checked Exception strategy, arguments given are that checked
Exception adds lot of boiler plate code and makes whole class or function unreadable. Somewhat I agree
with this and java also recognize this by introducing improved Exception handling mechanism in
Java7 but Checked Exception does have its real purpose. Following are some scenarios where I would
prefer to use Checked Exception to ensure that Code is Robust and stable:
1) All Operation where chances of failure is more e.g. IO Operation, Database Access or Networking
operation can be handled with Checked Exception.
2) When you know what to do (i.e. you have alternative) when an Exception occurs, may be as part of
Business Process.
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException
Unchecked Exception in Java is those Exceptions whose handling is not verified during Compile time.
Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object,
accessing element outside an array bonding or invoking method with illegal arguments. In Java,
Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked
Exception is that it doesn't reduce code readability and keeps the client code clean.
Java Memory Management, with its built-in garbage collection, is one of the language’s finest
achievements. It allows developers to create new objects without worrying explicitly about memory
allocation and deallocation, because the garbage collector automatically reclaims memory for reuse.
This enables faster development with less boilerplate code, while eliminating memory leaks and other
memory-related problems. At least in theory.
Ironically, Java garbage collection seems to work too well, creating and removing too many objects.
Most memory-management issues are solved, but often at the cost of creating serious performance
problems. Making garbage collection adaptable to all kinds of situations has led to a complex and hard-
to-optimize system. In order to wrap your head around garbage collection, you need first to understand
how memory management works in a Java Virtual Machine (JVM).
Many people think garbage collection collects and discards dead objects. In reality, Java garbage
collection is doing the opposite! Live objects are tracked and everything else designated garbage. As
you’ll see, this fundamental misunderstanding can lead to many performance problems.
Let’s start with the heap, which is the area of memory used for dynamic allocation. In most
configurations the operating system allocates the heap in advance to be managed by the JVM while the
program is running. This has a couple of important ramifications:
Object creation is faster because global synchronization with the operating system is not needed
for every single object. An allocation simply claims some portion of a memory array and moves
the offset pointer forward (see Figure 2.1). The next allocation starts at this offset and claims
the next portion of the array.
When an object is no longer used, the garbage collector reclaims the underlying memory and
reuses it for future object allocation. This means there is no explicit deletion and no memory is
given back to the operating system.
Figure 2.1: New objects are simply allocated at the end of the used heap.
All objects are allocated on the heap area managed by the JVM. Every item that the developer uses is
treated this way, including class objects, static variables, and even the code itself. As long as an object is
being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not
reachable by the application code, the garbage collector removes it and reclaims the unused memory.
22. What is Java Command Line Arguments?
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.
So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
In this example, we are receiving only one argument and printing it. To run this java program, you must
pass at least one argument from the command prompt.
class CommandLineExample{
There are some important differences between an applet and a standalone Java application, including
the following −
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a
separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Both java.lang.Error and java.lang.Exception classes are sub classes of java.lang.Throwable class, but
there exist some significant differences between them. java.lang.Error class represents the errors which
are mainly caused by the environment in which application is running. For
example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs
when stack overflows.
Where as java.lang.Exception class represents the exceptions which are mainly caused by the
application itself. For example, NullPointerException occurs when an application tries to access null
object or ClassCastExceptionoccurs when an application tries to cast incompatible class types. In this
article, we will discuss the differences between Error and Exception in java.
1) Recovering from Error is not possible. The only solution to errors is to terminate the execution.
Where as you can recover from Exception by using either try-catch blocks or throwing exception back to
caller.
2) You will not be able to handle the Errors using try-catch blocks. Even if you handle them using try-
catch blocks, your application will not recover if they happen. On the other hand, Exceptions can be
handled using try-catch blocks and can make program flow normal if they happen.
3) Exceptions in java are divided into two categories – checked and unchecked. Where as
all Errors belongs to only one category i.e unchecked.
4) Compiler will not have any knowledge about unchecked exceptions which include Errors and sub
classes of RunTimeException because they happen at run time. Where as compiler will have knowledge
about checked Exceptions. Compiler will force you to keep try-catch blocks if it sees any statements
which may throw checked exceptions.
5) Exceptions are related to application where as Errors are related to environment in which application
is running.
Errors Exceptions
Errors in java are of type java.lang.Error. Exceptions in java are of type java.lang.Exception.
All errors in java are unchecked type. Exceptions include both checked as well as unchecked type.
Examples :
Checked Exceptions : SQLException, IOException
Examples : Unchecked Exceptions : ArrayIndexOutOfBoundException,
java.lang.StackOverflowError, java.lang.OutOfMemoryError ClassCastException, NullPointerException
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event. The user interface element is able to delegate the processing of an event to the
separate piece of code. In this model ,Listener needs to be registered with the source object so that the
listener can receive the event notification. This is an efficient way of handling the event because the
event notifications are sent only to those listener that want to receive them.
Type casting in java or simply casting is used to convert data from one data type to another data type.
Please note that by using casting, data can not be modified but only type of data can be modified.
1) Primitive Casting.
2) Derived Casting
1) Primitive Casting.
Primirive Casting is used to convert data from one primitive data type to another primitive data type.
5) float 6) double
When you put them in the increasing order of their memory size, you get
byte < short < int < long < float < double.
Please remember this order we will be using this order in below examples. byte is the smallest data type
and double is the biggest data type in terms of memory size.
There are two types in primitive casting. 1) Auto Widening 2) Explicit Narrowing
2) Derived Casting
Derived casting is used to change the type of object from one user defined data type to another
user defined data type in the class hierarchy.
There are two types in derived casting. 1) Auto-up Casting 2) Explicit Down Casting.
28 .Describe Thread in java?
Application :
Application is a program which is designed to perform a specific task. For example, MS Word,
Google Chrome, a video or audio player etc.
Process :
Process is an executing instance of an application. For example, when you double click MS
Word icon in your computer, you start a process that will run this MS word application.
Processes are heavy weight operations that they require their own separate memory address in
operating system. Because of the processes are stored in separate memory, communication
between processes (Inter Process Communication) takes time. Context switching from one
process to another process is also expensive.
Thread :
Thread is a smallest executable unit of a process. Thread has it’s own path of execution in a
process. For example, when you start MS word, operating system creates a process and start
the execution of a primary thread of that process. A process can have multiple threads. Threads
of the same process share the memory address of that process. i.e threads are stored inside the
memory of a process. As the threads are stored in the same memory space, communication
between threads (Inter Thread Communication) is fast. Context switching from one thread to
another thread is also less expensive.
Operator is a special symbol that tells the compiler to perform specific mathematical or
logical Operation. Java supports following lists of operators.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Arithmetic Operators
Given table shows all the Arithmetic operator supported by Java Language. Lets suppose
variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always return true or false. Lets suppose
variable A hold 8 and B hold 3.
Operators Example (int A=8, B=3) Result
== A== B False
!= A!=(-4) True
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to combined
two conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C).
Here &&is Logical Operator.
Operator Example (int A=8, B=3, C=-10) Result
! !(B<=-A) True
Truth table of Logical Operator
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold
3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
Ternary operator
If any operator is used on three operands or variable is known as ternary operator. It can be
represented with " ?: "
30. Write note on Lexical Issues in java?
There are many atomic elements of Java. Java programs are a collection of whitespace,
identifiers, comments, literals, operators, separators and keywords.
Whitespace:
Java is a free-form language. It means we do not need to follow any special indentation rules. In
java whitespace is a space, tab, or newline.
Identifiers:
Identifiers are used for class names, method names and variable names.
An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or
the underscore and dollor-sign characters.
An identifier must not begin with a number because it leads to invalid indentifier.
Literals:
A constant value in Java is created by using a literal representation. A literal is allowed to use
anywhere in the program.
Comments:
The contents of a comment are ignored by the compiler. A comment describes or explains the
operation of the program to anyone who is reading its source code. The comment describes the
program. In java there are three types of comments. They are single-line, multi-line and
documentation comment.
Single-line comment: Two slashes characters are the single-line comment i.e. //. This type of
comment is called a "slash-slash" comment
Multi-line comment: To add a comment of more than one line, we can precede our comment
using /* and end with delimiter */.
.......................................................
.......................................................
.....................................................*/
Documentation comment:
This is a special type of comment that indicates documentation comment. This type of
comment is readable to both, computer and human. To start the comment, use /** and end
with */.
Separators:
Separators are used to terminate statements. In java there are few characters are used as
separators . They are, parentheses(), braces{}, brackets[], semicolon;, period., and comma,.
Keywords:
In java, a keyword has a predefined meaning in the language, because of this, programmers
cannot use keywords as names for variables, methods, classes, or as any other identifier.
Datatype is a spacial keyword used to allocate sufficient memory space for the data, in
other words Data type is used for representing the data in main memory (RAM) of the
computer.
In general every programming language is containing three categories of data types. They
are
Primitive data types are those whose variables allows us to store only one value but they
never allows us to store multiple values of same type. This is a data type whose variable can
hold maximum one value at a time.
Example
int a; // valid
a=10; // valid
a=10, 20, 30; // invalid
Here "a" store only one value at a time because it is primitive type variable.
Derived data types are those whose variables allow us to store multiple values of same type.
But they never allows to store multiple values of different types. These are the data type
whose variable can hold more than one value of similar type. In general derived data type
can be achieve using array.
Example
Here derived data type store only same type of data at a time not store integer, character
and string at same time.
User defined data types are those which are developed by programmers by making use of
appropriate features of the language.
User defined data types related variables allows us to store multiple values either of same
type or different type or both. This is a data type whose variable can hold more than one
value of dissimilar type, in java it is achieved using class concept.
Note: In java both derived and user defined data type combined name as reference data
type.
In C language, user defined data types can be developed by using struct, union, enum etc. In
java programming user defined datatype can be developed by using the features of classes
and interfaces.
Example
In java we have eight data type which are organized in four groups. They are
These category data types are used for storing integer data in the main memory of
computer by allocating sufficient amount of memory space.
Integer category data types are divided into four types which are given in following table
3 Int 4 + x to - (x+1)
4 Long 8 + y to - (y+1)
Java support more than 18 international languages so java take 2 byte for characters,
because for 18 international language 1 byte of memory is not sufficient for storing all
characters and symbols present in 18 languages. Java supports Unicode but c support ascii
code. In ascii code only English language are present, so for storing all English latter and
symbols 1 byte is sufficient. Unicode character set is one which contains all the characters
which are available in 18 international languages and it contains 65536 characters
Float category data type are used for representing float values. This category contains two
data types, they are in the given table
Data Type Size Range Number of decimal places
Double 8 + 9.223*1018 16
Boolean category data type is used for representing or storing logical values is true or false.
In java programming to represent Boolean values or logical values, we use a data type called
Boolean.
Boolean data type takes zero bytes of main memory space because Boolean data type of
java implemented by Sun Micro System with a concept of flip - flop. A flip - flop is a general
purpose register which stores one bit of information (one true and zero false).
Note: In C, C++ (Turbo) Boolean data type is not available for representing true false values
but a true value can be treated as non-zero value and false values can be represented by
zero
Data Type Default Value Default size
Byte 0 1 byte
short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Computers can only understand machine language instructions; therefore each instruction in a
high-level language must be translated into machine language before it can be executed. In
other languages such as C, C++, when programs are compiled using a compiler, the code is
translated into machine language one time, and the resulting object program can be run as
many times as needed. This machine language code is dependent on the specific computer
hardware platform being used. Therefore for applications written using C, separate source
code needs to be generated for all possible hardware platforms, or the software developer
decides which machines to support, and guarantees the object program works on those
machines.
With the rise of the Internet, application programs need to run correctly regardless of the
platform being used. Java source code is said to be much more portable, meaning it can easily
be transferred between different platforms. This is done using bytecodes and the Java Virtual
Machine (JVM).
The Java Virtual Machine is an interpreter program that translates each bytecode instruction
into the machine language for a particular computer, and then executes it. Unlike machine
language, which is dependent on a specific platform, bytecodes are platform independent
instructions; they are not dependent on a specific computer platform. Therefore Java’s
bytecodes are portable, meaning the same bytecodes can execute on any platform containing a
JVM that understands the version of Java in which the bytecodes were compiled. The
developer can compile Java source code once, and know that it will run on a variety of
computers.
Phases of Program Creation and Execution
During the creation and execution of a Java program, programs normally go through 5
phases. These are:
1. Edit – creating a Java program consists of using an editor program. You type the Java
source code using the editor, make corrections and save the program on a secondary
storage device. Java source code files are saved with the file extension “.java”. These files
can be created using a simple text editor, or an IDE (Integrated Development Environment),
such as JCreator, Eclipse, JBuilder, etc. IDEs provide tools to support the development
process, including editors for writing programs and debugging for locating logic errors in
programs.
2. Compile – during this phase, the programmer compiles the program using a command at
the command line, or tools from the IDE. At this step, the Java source code is translated
into bytecodes. If you are running the Java compiler from the command prompt, the
command to enter is:
Command: javac HelloWorld.java*
*Below we will see common errors using the compiler.
Running the command above would compile the Java source file, HelloWorld.java, and
generate a bytecode class file named, HelloWorld.class.
3. Load – The program must be placed in memory before it can execute. In loading, the class
loader takes the “.class” files, created in the previous step, and transfers them to primary
memory. The class loader also loads the .class files provided by Java, that your program
uses.
4. Verify – as the classes are loaded, a bytecode verifier examines the bytecodes to ensure
they are valid and don’t violate any security restrictions.
5. Execute - during the last phase, the JVM executes a programs bytecodes, performing the
actions specified by the program. In earlier versions of Java, the JVM was simply an
interpreter for Java bytecodes. This meant that the Java programs would execute slowly,
because the JVM would interpret and execute, one bytecode at a time. The newer versions
of JVMs execute bytecodes using a combination of interpretation and what is called “just-in-
time” compilation. Using JIT compilation the JVM analyzes the bytecodes as they are
interpreted, and searches for parts of the bytecode that execute frequently. For these
parts, a JIT compiler translates the bytecodes into the underlying computer’s machine
language. When the JVM encounters the compiled parts again, the faster machine language
code executes. This means that Java programs actually go through two compilation phases,
on in which source code is translated to bytecodes (for portability across JVMs) and second,
during execution, the bytecodes are translated into machine language for the actual
computer on which the program executes.
Example: HelloWorld.java
Java Virtual Machine Model
Common problems
As you are compiling and executing your Java programs, there are some common errors that
you may see. Two common problems that will result in errors occur when the JDK has not been
installed correctly, or parameters have changed.
Setting the Classpath – when executing a Java program, the JVM uses a class loader to locate
the classes it needs. The compiler starts by searching the standard Java classes bundled with
the JDK (i.e. String class, BufferedReader class, etc). If the class is not found in the standard
classes (i.e. you’ve created the class yourself) then the class loader searches the classpath,
which is a list of location in which classes are stored (remember the .class files). By default, the
classpath contains only the current directory (i.e. the class loader will only search the current
directory) but if you are executing a program from a directory other than where the class is
stored, you can add that location to the CLASSPATH environment variable, in order for the class
loader to locate the class.
Eg. CLASSPATH C:\myfiles
Setting the Path – generally, when the JDK is installed, it should automatically set the path
variable, which tells the OS where to find the executable files (compiler, JVM, etc) regardless of
the directory where the files are being compiled and executed. Occasionally this may not be
set correctly. When you try to execute a program with the command: java myProgram, you
may see the error message, Bad command or filename at the command prompt. If this is the
case, you need to set the PATH variable in the Autoexec.bat file and include the path of the
directory, which contains the exe files. (Such as: C:\JDK1.5.1_01\bin)
33. Write detailed note on Exception Hierarchy?
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled
by the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from
errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Following is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods
Following is the list of important methods available in the Throwable class.
5 Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.
Catching Exceptions
A method catches an exception using a combination of the try and catchkeywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch
block is referred to as protected code, and the syntax for using try/catch looks like the
following −
Syntax
try {
// Protected code
}catch(ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
Syntax
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown to
the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i) {
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
Example
import java.io.*;
public class className {
Example
import java.io.*;
public class className {
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −
Syntax
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following −
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
34. Write Note on Java applet life cycle
Various states, an applet, undergoes between its object creation and object removal (when the
job is over) is known as Applet Life Cycle. Each state is represented by a method. There exists 5
states represented by 5 methods. That is, in its life of execution, the applet exists (lives) in one
of these 5 states.
These methods are known as "callback methods" as they are called automatically by the
browser whenever required for the smooth execution of the applet. Programmer just write the
methods with some code but never calls.
Following are the methods.
1. init() method
2. start() method
3. paint() method
4. stop() method
5. destroy() method
These methods are known as Applet Life Cycle methods. These methods are defined
in java.applet.Applet class except paint() method. The paint() method is defined
in java.awt.Component class, an indirect super class of Applet.
Browser Responsibilities
The Applet Life Cycle methods are called as callback methods as they are called implicitly by the
browser for the smooth execution of the applet. Browser should provide an environment
known as container for the execution of the applet. Following are the responsibilities of the
browser.
1. It should call the callback methods at appropriate times for the smooth execution of the
applet.
2. It is responsible to maintain the Applet Life Cycle.
3. It should have the capability to communicate between applets, applet to JavaScript and
HTML, applet to browser etc.
Description of Applet Life Cycle methods
Even though, the methods are called automatically by the browser, the programmer should
know well when they are called and what he can do with the methods. Following is the
schematic representation of the methods.
Brief Description of Life Cycle Methods
Following is the brief description of the above methods.
1. init(): The applet's voyage starts here. In this method, the applet object is created by the
browser. Because this method is called before all the other methods, programmer can
utilize this method to instantiate objects, initialize variables, setting background and
foreground colors in GUI etc.; the place of a constructor in an application. It is equivalent
to born state of a thread.
2. start(): In init() method, even through applet object is created, it is in inactive state. An
inactive applet is not eligible for microprocessor time even though the microprocessor is
idle. To make the applet active, the init() method calls start() method. In start() method,
applet becomes active and thereby eligible for processor time.
3. paint(): This method takes a java.awt.Graphics object as parameter. This class includes
many methods of drawing necessary to draw on the applet window. This is the place
where the programmer can write his code of what he expects from applet like animation
etc. This is equivalent to runnable state of thread.
4. stop(): In this method the applet becomes temporarily inactive. An applet can come any
number of times into this method in its life cycle and can go back to the active state
(paint() method) whenever would like. It is the best place to have cleanup code. It is
equivalent to the blocked state of the thread.
5. destroy(): This method is called just before an applet object is garbage collected. This is
the end of the life cycle of applet. It is the best place to have cleanup code. It is equivalent
to the dead state of the thread.
After knowing the methods, let us know when they are called by the browser.
init() method is called at the time of starting the execution. This is called only once in the
life cycle.
start() method is called by the init() method. This method is called a number of times in
the life cycle; whenever the applet is deiconifed , to make the applet active.
paint() method is called by the start() method. This is called number of times in the
execution.
stop() method is called whenever the applet window is iconified to inactivate the applet.
This method is called number of times in the execution.
destroy() method is called when the applet is closed. This method is called only once in the
life cycle.
Observe, the init() and destroy() methods are called only once in the life cycle. But, start(),
paint() and stop() methods are called a number of times.
For example, using JDBC drivers enable you to open database connections and to interact with
it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
The basic aim of String Handling concept is storing the string data in the main memory
(RAM), manipulating the data of the String, retrieving the part of the String etc. String
Handlingprovides a lot of concepts that can be performed on a string such as concatenation
of string, comparison of string, find sub string etc.
Character
String:
String is a sequence of characters enclosed within double quotes (" ") is known as String.
Example: "Java Programming".
In java programming to store the character data we have a fundamental datatype
called char. Similarly to store the string data and to perform various operation on String
data, we have three predefined classes they are:
String
StringBuffer
StringBuilder
By == operator
By compreTo() method
equals() method always used to comparing contents of both source and destination String. It
return true if both string are same in meaning and case otherwise it returns false. It is case
sensitive method.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3));
}
}
Output
== Operator is always used for comparing references of both source and destination objects
but not their contents.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1=new String("java");
String s2=new String("java");
if(s1==s2)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
comapreTo() method can be used to compare two string by taking Unicode values. It returns
0 if the string are same otherwise returns either +ve or -ve integer.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
equals() method always used to comparing contents of both source and destination String.
== Operator is always used for comparing references of both source and destination objects
but not their contents.
38 . What is StringBuffer?
It is a predefined class in java.lang package can be used to handle the String, whose object is
mutable that means content can be modify.
StringBuffer class is working with thread safe mechanism that means multiple thread are not
allowed simultaneously to perform operation of StringBuffer.
StringBuffer class object is mutable that means when we create an object of StringBulder
class it can be change.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java");
sb.append("software");
System.out.println(sb);
}
}
Output
javasoftware
Explanation: Here we can changes in the existing object of StringBuffer class so output is
javasoftware.
String StringBuffer
The data which enclosed within double The data which enclosed within double quote
1 quote (" ") is by default treated as String (" ") is not by default treated as StringBuffer
class. class
When we create an object of String class by When we create an object of StringBuffer class
3 default no additional character memory by default we get 16 additional character
space is created. memory space.
Similarities between String and StringBuffer
Both of them are belongs to public final. so that they never participates in inheritance
that is is-A relationship is not possible but they can always participates in As-A and Uses-
A relationship.
The static keyword is used in java mainly for memory management. It is used with variables,
methods, blocks and nested class. It is a keyword that are used for share the same variable
or method of a given class. This is used for a constant variable or a method that is the same
for every instance of a class. The main method of a class is generally labeled static.
No object needs to be created to use static variable or call static methods, just put the class
name before the static variable or method to use them. Static method can not call non-static
method.
block
nested class
By concat() method
By + operator
Using Java string concatenation operator (+) you can combined two or more strings.
Example
class StringHandling
{
public static void main(String arg[])
{
String s= "Java" + "Code";
System.out.println(s);
}
}
Output
JavaCode
By concat() method
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Java";
String s2="Code";
String s3=s1.concat(s2);
System.out.println(s3);
}
}
Output
JavaCode
1 Converting numeric string type data into numerical / fundamental type values
In order to convert numerical string into numerical or fundamental values we use the
following generalized predefined method which is present in wrapper classes.
Example
String s1="100";
int x=Integer.parseInt(s1);
Example
String s2="100.75f";
Float y=Float.parseFloat(s2);
In order to convert numeric / fundamental type values into string values, we use the
following predefined static overloaded method.
Example
int a=10;
3 Converting fundamental type values into object type values:
In order to convert the fundamental data into equivalent wrapper class object type data we
use the following generalized predefined parameterized constructor by taking fundamental
data type as a parameter.
Example:
in JDK 1.4 converting fundamental data type values into wrapper class object is known as
boxing. In the case of JDK 1.5 and in higher version it is optional to the java programmer to
convert fundamental data type value into equivalent wrapper class object. That is implicitly
taken care by JVM and it is known as auto boxing.
The process of implicitly converting fundamental type value into equivalent wrapper class
object is known as auto boxing.
In order to convert wrapper class object data into fundamental type data, we use the
following predefined instance method present in each and every wrapper class.
In case of JDK 1.5 and in higher version it is optional to the java programmer to convert
object data into fundamental type data and this process is known as auto un-boxing and its
takes care by JVM.
In process of implicitly conversion objects type data into fundamental type data is known as
auto un-boxing.
In order to convert String type numeric data into equivalent wrapper class object, we use
the following predefined parameterized constructor by each and every wrapper class except
character class.
6 Converting wrapper class object type data into String type data
To convert wrapper class object type data into string type data we use the following
generalized predefined instant method which is present each and every wrapper class.
Example
int a=10;
String is=String.valueOf(a);
int x=io.intValue();
String so=io.toString();
int x=Integer.parseInt(so);
43. What is Interface in Java?
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java.
properties of Interface
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
All the data members of interface are implicitly public static final.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
Understanding the simple example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a
type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing
stored procedures.
ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its
data.
SQLException: This class handles any errors that occur in a database application.
Balraj Gill