Вы находитесь на странице: 1из 83

JAVA

1. What is java? Define five features of java?

Java is a general purpose, high-level programming language developed


by Sun Microsystems. A small team of engineers, known as the Green Team, initiated the
language in 1991. Java was originally called OAK, and was designed for handheld devices and
set-top boxes. Oak was unsuccessful, so in 1995 Sun changed the name to Java and modified
the language to take advantage of the burgeoning World Wide Web.

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.

 Architecture-neutral − Java compiler generates an architecture-neutral object file format, which


makes the compiled code executable on many processors, with the presence of Java runtime
system.

 Portable − Being architecture-neutral and having no implementation dependent aspects of the


specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability
boundary, which is a POSIX subset.

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

 Distributed − Java is designed for the distributed environment of the internet.

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

2. Describe the main method of java?


public static void main(string args[]) Explanation

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.

String args[] : is the parameter to the main Method.

3. Describe Basic Syntax of java?


About Java programs, it is very important to keep in mind the following points.

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

Example: class MyFirstJavaClass

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

Example: public void myMethodName()

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

2. An implementation Its implementation is known as JRE (Java Runtime Environment).

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

The JVM performs following operation:

o Loads code

o Verifies code

o Executes code

o Provides runtime environment

JVM provides definitions for the:

o Memory area

o Class file format

o Register set
o Garbage-collected heap

o Fatal error reporting etc.

Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.

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

It is the runtime data area in which objects are allocated.


4) Stack

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.

5) Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine instruction currently
being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1) A virtual processor

2) Interpreter: Read bytecode stream then execute the instructions.

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.

An object has three characteristics:

o state: represents data (value) of an object.

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.

A class in java can contain:

o data member

o method

o constructor

o block
o class and interface

Syntax to declare a class:

1. class <class_name>{

2. data member;

3. method;

4. }

Simple Example of Object and Class

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{

2. int id;//data member (also instance variable)

3. String name;//data member(also instance variable)

4.

5. public static void main(String args[]){

6. Student1 s1=new Student1();//creating an object of Student

7. System.out.println(s1.id);

8. System.out.println(s1.name);

9. }

10. }

8. Difference between Static and non-static method in Java?


In case of non-static method memory is allocated multiple time whenever method is calling. But
memory for static method is allocated only once at the time of class loading. Method of a class can be
declared in two different ways

 Non-static methods
 Static methods

Difference between non-static and static Method

Non-Static method Static method

These method never be preceded by static keyword These method always preceded by static keyword
Example: Example:

void fun1() static void fun2()

1 { {

...... ......

...... ......

} }

Memory is allocated multiple time whenever method is


2 Memory is allocated only once at the time of class loading.
calling.

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

10. Inter-thread communication in Java?


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its


critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:

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

public final void wait()throws InterruptedException

public final void wait(long timeout)throws InterruptedException

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:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

11. What is Bytecode?

Bytecode: The intermediate code produced by certain semi-compiled programming languages, in


particular SMALLTALK and JAVA, So called because each instruction is one byte long. Source programs
are com piled into bytecode, which is then executed by a bytecode INTERPRETER or VIRTUAL
MACHINE that forms part of the language RUN-TIME SYSTEM. In such languages, programs may be
distributed either in SOURCE CODE or in bytecode form.

Write down the use of Final Keyword in java?


A java variable can be declared using the keyword final. Then the final variable can be assigned only
once.

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

 Java classes declared as final cannot be extended. Restricting inheritance!

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

12. Java Tokens - What is Java Tokens?


Java Tokens:- A java Program is made up of Classes and Methods and in the Methods are the Container
of the various Statements And a Statement is made up of Variables, Constants, operators etc .

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

13. What is Identifiers in Java?


Identifier is is a simple variable name which is defined as the value container. The type of value stored
by identifier is defined by the special java keyword is termed as primitive data type.

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

14. New Keyword - What is New Keyword?


New is a Keyword Which is used when we are Creating an object of class For Storing all the data like
variables and member functions of class there is some memory Space that is to be needed So that With
the help of new Keyword and Object is Instantiated or Simply an object Reserves

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 .

15. Difference Between Type Conversion and Type Casting


Type Conversion

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

16. Write Structure of a Java Program?


A Java program consists of different sections. Some of them are mandatory but some are optional. The
optional section can be excluded from the program depending upon the requirements of the
programmer.

Documentation Section

It includes the comments to tell the program's purpose. It improves the readability of the program.

Package Statement

It includes statement that provides a package declaration.

Import statements

It includes statements used for referring classes and interfaces that are declared in other packages.

Interface Section

It is similar to a class but only includes constants, method declaration.


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

Java programming language supports three types of comments.

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:

// Calculate sum of two numbers

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.

/*calculate sum of two numbers */

Comments cannot be nested. In other words, you cannot comment a line that already includes
traditional comment. For example,

/* x = y /* initial value */ + z; */ is wrong.

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.

/**The text enclosed here will be part of program documentation */

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:

Import java.util.Date; /* imports only the Date class in java.util package */

import java.applet.*; // imports all the classes in java applet

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

void push(int item); // Insert item into stack

int pop(); // Delete an item from 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.

The class section is mandatory.

After discussing the structure of programs in Java, we shall now discuss a program that displays a string
Hello Java on the screen.

// Program to display message on the screen

class HelloJava

public static void main(String args[])

System.out.println("Hello Java");

17. What is a Wrapper Class in java?


Wrapper Classes:- We know that Vectors can’t handle Primitives data types like int, float ,char, long So
that Primitives data type may be Converted into object data types by using wrapper classes those are
contained in java.lang packages The Various Wrapper Classes are :-

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

18. What is the super keyword in java?


The super keyword in java is a reference variable that is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.

Usage of java super Keyword

1. super is used to refer immediate parent class instance variable.

2. super() is used to invoke immediate parent class constructor.

3. super is used to invoke immediate parent class method.

//example of super keyword

class Vehicle{

int speed=50;

class Bike4 extends Vehicle{

int speed=100;

void display(){

System.out.println(super.speed);//will print speed of Vehicle now

}
public static void main(String args[]){

Bike4 b=new Bike4();

b.display();

19. What is the use of this keyword in java?


There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the
current object. his is a keyword in Java. It can be used inside the Method or constructor of Class.
It(this)works as a reference to the current Object whose Method or constructor is being invoked.
The this keyword can be used to refer to any member of the current object from within an instance
Method or a constructor.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this keyword can be used to refer current class instance variable.

2. this() can be used to invoke current class constructor.

3. this keyword can be used to invoke current class method (implicitly)

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

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

20. What is the Difference between Checked vs Unchecked Exception in Java?


What is Checked Exception in Java?

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.

3) Checked Exception is a reminder by compiler to programmer to handle failure scenario.

Example of checked Exception in Java API


Following are some Examples of Checked Exception in Java library:

IOException
SQLException

DataAccessException

ClassNotFoundException

InvocationTargetException

What is Unchecked Exception in Java?

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.

When to use UnCheckedException in Java

A good strategy of Exception handling in Java is wrapping a checked Exception


into UnCheckedException. Since most of Database operation throws SQLException but it’s not good to
let SQLException propagate from your DAO layer to up higher on business layer and client code provide
exception handling you can handle SQLException in DAO layer and you can wrap the cause in a
RuntimeException to propagate through client code. Also as I said earlier unchecked exceptions are
mostly programming errors and to catch them is real hard until you do a load test with all possible input
and scenario.

21. What is Garbage collection in java?

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.

Simple example of command-line argument in java

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{

public static void main(String args[]){

System.out.println("Your first argument is: "+args[0]);

1. compile by > javac CommandLineExample.java

2. run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

23. What is Java applet?


An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including
the following −

 An applet is a Java class that extends the java.applet.Applet class.

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

24. What is Java Database Connectivity (JDBC)?


Java Database Connectivity (JDBC) is an application program interface (API) specification for connecting
programs written in Java to the data in popular databases. The application program interface lets you
encode access request statements in Structured Query Language (SQL) that are then passed to the
program that manages the database. It returns the results through a similar interface. JDBC is very
similar to the SQL Access Group's Open Database Connectivity (ODBC) and, with a small "bridge"
program, you can use the JDBC interface to access databases through the ODBC interface. For example,
you could write a program designed to access many popular database products on a number
of operating system platforms. When accessing a database on a PC running Microsoft's Windows 2000
and, for example, a Microsoft Access database, your program with JDBC statements would be able to
access the Microsoft Access database.
25. What is the Difference Between Error Vs Exception In Java?

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.

Below is the list of differences between Error and Exception in java.

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

Below is the quick recap of above points.

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.

Checked exceptions are known to compiler where as


unchecked exceptions are not known to compiler because
Errors happen at run time. They will not be known to compiler. they occur at run time.

You can recover from exceptions by handling them through


It is impossible to recover from errors. try-catch blocks.

Errors are mostly caused by the environment in which


application is running. Exceptions are mainly caused by the application itself.

Examples :
Checked Exceptions : SQLException, IOException
Examples : Unchecked Exceptions : ArrayIndexOutOfBoundException,
java.lang.StackOverflowError, java.lang.OutOfMemoryError ClassCastException, NullPointerException

26. What is Event Handling?


Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism have the code which is known as event handler that is executed when an event
occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.Let's have a brief introduction to this model.

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.

 Listener - It is also known as event handler.Listener is responsible for generating response to an


event. From java implementation point of view the listener is also an object. Listener waits until
it receives an event. Once the event is received , the listener process the event an then returns.

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.

27. Define Type casting in java?

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.

There are two types of casting,

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.

Consider primitive data types in java which represent the numbers.

These are data types with no decimal places.

1) byte 2) short 3) int 4) long

and these are data types with decimal places.

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.

Processes and threads can be diagrammatically represented as below,


Multitasking :

Multitasking is an operation in which multiple tasks are performed simultaneously. Multitasking


is used to utilize CPU’s idle time. Multitasking can be of two types. One is process-based and
another one is thread-based.

1) Process-based multitasking Or Multiprocessing :

In process-based multitasking or multiprocessing, Multiple processes are executed


simultaneously. You are all familiar with process-based multitasking. Because of this feature
only, your computer runs two or more programs simultaneously. For example, You can play a
video file and print a text file simultaneously in your computer.

2)Thread-based Multitasking Or Multithreading:

In thread-based multitasking or multithreading, multiple threads in a process are executed


simultaneously. For example, MS word can print a document using background thread, at the
same another thread can accept the user input so that user can create a new document.

29. Write all the Operators in Java?

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

 Ternary or Conditional 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<=10 True

> A>B True

>= A<=B False

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

&& (A<B) && (B>C) False

|| (B!=-C) || (A==B) True

! !(B<=-A) True
Truth table of Logical Operator

C1 C2 C1 && C2 C1 || C2 !C1 !C2

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

=a=b Value of b will be assigned to a

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.

Eg: AvgTemp, count, $calculate, s5, value_display

An identifier must not begin with a number because it leads to invalid indentifier.

Eg: 5s, yes/no

Literals:

A constant value in Java is created by using a literal representation. A literal is allowed to use
anywhere in the program.

Eg: Integer literal : 100

Floating-point literal : 98.6

Character literal : ‘s’

String literal : “sample”

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

// This comment extends to the end of the line.

Multi-line comment: To add a comment of more than one line, we can precede our comment
using /* and end with delimiter */.

/*..............the multi-line comments

are given with in this comment

.......................................................

.......................................................

.....................................................*/

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

/**....... Documentation comments..........*/

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.

31. Discuss various Data Type in Java?

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

 Fundamental or primitive data types

 Derived data types

 User defined data types.


Primitive data types

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

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

int a[] = {10,20,30}; // valid


int b[] = {100, 'A', "ABC"}; // invalid

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

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

Student s = new Student();

In java we have eight data type which are organized in four groups. They are

 Integer category data types

 Character category data types

 Float category data types

 Boolean category data types

Integer category data types

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

Data Type Size Range

1 Byte 1 + 127 to -128


2 Short 2 + 32767 to -32768

3 Int 4 + x to - (x+1)

4 Long 8 + y to - (y+1)

Character category data types

A character is an identifier which is enclosed within single quotes. In java to represent


character data, we use a data type called char. This data type takes two byte since it follows
Unicode character set.

Data Type Size(Byte) Range

Char 2 232767 to -32768

Why Java take 2 byte of memory for store character ?

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 types

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

Float 4 +2147483647 to -2147483648 8

Double 8 + 9.223*1018 16

Boolean category data types

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.

Why Boolean data types take zero byte of memory ?

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

boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

short 0 2 byte

Int 0 4 byte
Long 0L 8 byte

Float 0.0f 4 byte

double 0.0d 8 byte

32. Introduction to the Java Environment?

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

Bytecodes and the Java Virtual Machine (JVM)


When Java source code is compiled, it is translated into bytecodes. The bytecodes represent
the tasks that are performed during the program execution. The bytecodes are instructions for
a simulated computer, the Java Virtual Machine (JVM). The Java Virtual Machine (JVM), is part
of the Java Development Kit (JDK).

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.

Command: java HelloWorld

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.

Sr.No. Method & Description

public String getMessage()


1
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
public Throwable getCause()
2
Returns the cause of the exception as represented by a Throwable object.

public String toString()


3
Returns the name of the class concatenated with the result of getMessage().

public void printStackTrace()


4
Prints the result of toString() along with the stack trace to System.err, the error
output stream.

public StackTraceElement [] getStackTrace()

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.

public Throwable fillInStackTrace()


6
Fills the stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.

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.

// File Name : ExcepTest.java


import java.io.*;

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

This will produce the following result −


Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following −

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;
}

Catching Multiple Type of Exceptions


Since Java 7, you can handle more than one exception using a single catch block, this feature
simplifies the code. Here is how you would do it −

catch (IOException|FileNotFoundException ex) {


logger.log(ex);
throw ex;

The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.

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.

The following method declares that it throws a RemoteException −

Example
import java.io.*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions
are declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException −

Example
import java.io.*;
public class className {

public void withdraw(double amount) throws RemoteException,


InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.

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 {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}

This will produce the following result −

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following −

 A catch clause cannot exist without a try statement.

 It is not compulsory to have finally clauses whenever a try/catch block is present.

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

35. What is JDBC Driver?


JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

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.

JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBC Bridge Driver


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

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.

Type 2: JDBC-Native API


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to
the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.

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.

Type 3: JDBC-Net pure Java


In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS, and forwarded to the database server.

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.

Type 4: 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself.

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.

Which Driver should be Used?


If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.

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.

36. Write a note on String Handling in Java?

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

It is an identifier enclosed within single quotes (' ').


Example: 'A', '$', 'p'

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

37. Write String Compare in Java?

There are three way to compare string object in java:


 By equals() method

 By == operator

 By compreTo() method

equals() Method in Java

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

Compare String: false

Compare String: true

== or Double Equals to Operator in Java

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

Strings are not same

compareTo() Method in Java

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

Strings are not same

Difference between equals() method and == operator

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.

Difference between String and StringBuffer

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

2 String class object is immutable StringBuffer class object is mutable

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.

 We can not override the method of String and StringBuffer.

39. Write Difference between Applet and Application?


Applet is a Java program executed by a browser. The position of applets in software world is
they occupy the client-side position in Web communication. On the server-side, you guess,
another Java program comes, Servlets. Applets on client-side and servlets on server-side makes
Java a truly "Internet-based language". To execute applets, the browsers come with JRE (Java
Runtime Environment). The browsers with Java Runtime Environment (or to say, JVM) loaded
are known as Java enabled browsers.
Note: Browser do not have a Java compiler as a compiled applet file (.class file) is given to
browser to execute.
Advantages of Applets of Applets Vs Applications
1. Execution of applets is easy in a Web browser and does not require any installation or
deployment procedure in realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not required
(but are required in applications).
Restrictions of Applets of Applets Vs Applications
1. Applets are required separate compilation before opening in a browser.
2. In realtime environment, the bytecode of applet is to be downloaded from the server to
the client machine.
3. Applets are treated as untrusted (as they were developed by unknown people and placed
on unknown servers whose trustworthiness is not guaranteed) and for this reason they are
not allowed, as a security measure, to access any system resources like file system etc.
available on the client system.
4. Extra Code is required to communicate between applets using AppletContext.
40. Static keyword in java?

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.

In java language static keyword can be used for following

 variable (also known as class variable)

 method (also known as class method)

 block

 nested class

41. Write a note on String Concatenation

There are two way to concat string object in java:

 By + (string concatenation) operator

 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

concat() method is used to combined two strings.

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

42. Write note on Data Conversion in String

In java programming we have six data conversion technique they are:.

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.

Here xxx represent any fundamental data type.

Example

String s1="100";
int x=Integer.parseInt(s1);

Example

String s2="100.75f";
Float y=Float.parseFloat(s2);

2 Converting numeric / fundamental type values into string type values

In order to convert numeric / fundamental type values into string values, we use the
following predefined static overloaded method.

Here XXX represent any fundamental data type values

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.

Definition of auto boxing

The process of implicitly converting fundamental type value into equivalent wrapper class
object is known as auto boxing.

4 Converting object type value into fundamental type value:

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.

Definition of auto un-boxing

In process of implicitly conversion objects type data into fundamental type data is known as
auto un-boxing.

5 Converting String type data into object type data

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

 Integer io=new Integer(is);

 int x=io.intValue();

 Integer io=new Integer(n);

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

Why we use Interface ?

 It is used to achieve fully abstraction.

 By using Interface, you can achieve multiple inheritance in java.

 It can be used to achieve loose coupling.

properties of Interface

 It is implicitly abstract. So we no need to use the abstract keyword when declaring an


interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.

 Methods in an interface are implicitly public.

 All the data members of interface are implicitly public static final.

44. Write the important difference between constructors and methods ?


1. Constructors create and initialize objects that don't exist yet, while methods perform
operations on objects that already exist.
2. Constructors can't be called directly; they are called implicitly when the new keyword creates
an object. Methods can be called directly on an object that has already been created with new.
3. The definitions of constructors and methods look similar in code. They can take parameters,
they can have modifiers (e.g. public), and they have method bodies in braces.
4. Constructors must be named with the same name as the class name. They can't return
anything, even void (the object itself is the implicit return).
5. Methods must be declared to return something, although it can be void.

45. Write note on Method Overriding in Java with example?

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.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method is same and
there is IS-A relationship between the classes, so there is 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

Output:Bike is running safely

46. Write a detailed note on Inheritance in Java

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.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

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

Programmer salary is:40000.0


Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

Note: Multiple inheritance is not supported in java through class.


47. Write detailed note on JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −

 JDBC API: This provides the application-to-JDBC Manager connection.

 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

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 −

Common JDBC Components


The JDBC API provides the following interfaces and classes −

 DriverManager: This class manages a list of database drivers. Matches connection


requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
 Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated with
working with Driver objects.

 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

Вам также может понравиться