Java23
Java23
2 Marks Questions
1. What is Java API?
Ans: The full form of API is Application Programming Interface. It is a document which gives you the
list of all the packages, classes, and interfaces, along with their fields and methods.
Using these API’s, the programmer can know how to use the methods, fields, classes, interfaces
provided by Java libraries.
Ans: Java bytecode are a special set of machine instruction that are not specified to any
One processor or computer system .A platform specific byte code interpreter executes the java byte code
interpreter is also called as java virtual machine.
Ans: java program doesnot rely on particular os .it can run any os which has JVM.
The string literal is a sequence of characters which has to be double coded and occur on a single line.
Eg “vadivel”
Ans: These are declared in a class ,but outside a method, they are also called member or field variable,
an instance variable is created when an object is created and destroyed when the object is destroyed,
visible in all methods and constructors of defining class.
7. What are the default values of float and character primitive datatypes in java
Ans: Eight primitive data types can be put in four groups : Integer types : includes byte,short,int, and
long
Floating point types: includes float and doubles Character types: includes char
Boolean type: includes Boolean representing true or false
Ans:Syntax:
Switch(expression)
{
Case value1:
Value1 Break;
Case value2:
Value2 Break;
}
Ex:
Default:
Class switchdemo
{
Public static void main(String args[])
{
int a=10,b=20,c=30; int status=-1;
If(a>b && a>c)
{
Status=1;
}
Elseif(b>c)
{
}
Else
{
}
Status=2;
Status=3;
Switch(status)
{
Case1:
System.out.println(“a is greatest”); Break;
Case2:
System.out.println(“b is greatest”); Break;
Case3:
System.out.println(“c is greatest”); Break;
Default:
}
System.out.println(“can not be determined”);
}
}
Ans: break statement is used to break the loops and transfer control to the line immediate outside of the
loop while continue is used to escape current execution and transfers control back to start of the loop.
Ans:
Constructer Method
Is used to initialize the instancevariables of a Is used for any general purposetasks like
class. calculations
Constructor name and class nameshould be The method name and class namecan be same
always same. or different.
Constructor is called at the time ofcreating an Method can be called aftercreating
object. the object.
Method can be called any numberof times on
Constructor is called only onceper object.
the object.
Constructor is called and executed
Method is executed only when wewant it.
automatically.
13. Differentiate between ‘String class’ and ‘String Buffer’ class?
Ans: it represent the values of passed to main() method to receive and it store the values, main()
method provides argument called as String args[].
Example: java Sumclass 10 20
1. Java is simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java
2. Java is object-oriented
Java is an object-oriented programming language. Everything in Java is an object Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.
What is oop??
O0P stands for Object-Oriented Programming,
It Focus on objects that contain both data and functions.
Classes and objects are the two main aspects of object- oriented programming
3. Java is distributed
Distributed computing involves several computers on a network working together
Writing network programs in java is like sending and receiving data to and from a file in
network environment.
7. Java is secured
->Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
8. Java is robust
Robust simply means strong. Java is robust because:
It uses strong memory management
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make
Java robust.
9. Java is multithreaded
A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each thread.
It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
For example, downloading an mp3 file while playing the file would be considered as
multithreading.
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this section,
we declare the package name in which the class is placed. Note that there can be only one package
statement in a Java program. It must be defined before any class and interface declaration. It is
necessary because a Java class can be placed in different packages and directories based on the module
they are used. For all these classes package belongs to a single parent directory. We use the keyword
package to declare the package name. For example:
1. package javatpoint; //where javatpoint is the package name
2. package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory
Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class of a
particular package, we need to import that class. The import statement represents the class stored in the
other package. We use
the import keyword to import the class. It is written before the class declaration and after the package
statement. We use the import statement in two ways, either import a specific class or import all classes
of a particular package. In a Java program, we can use multiple import statements. For example:
1. import java.util.Scanner; //it imports the Scanner class only
2. import java.util.*; //it imports all the class of the java.util package
Interface Section
It is an optional section. We can create an interface in this section if required. We use the interface
keyword to create an interface. An interface is a slightly different from the class. It contains only
constants and method declarations. Another difference is that it cannot be instantiated. We can use
interface in classes by using the implements keyword. An interface can also be used with other
interfaces by using the extends keyword. For example:
1. interface car 2. {
3. void start();
4. void stop(); 5. }
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we cannot
create any Java program. A Java program may conation more than one class definition. We use the
class keyword to define the class. The class is a blueprint of a Java program. It contains information
about user- defined methods, variables, and constants. Every Java program has at least one class that
contains the main() method. For example:
1. class Student //class definition
2. {
3. }
For example:
1. public class Student //class definition
2. {
3. public static void main(String args[])
4. {
5. //statements
6. }
7. }
You can read more about the Java main() method here. Methods and behaviour
In this section, we define the functionality of the program by using the methods. The methods are the
set of instructions that we want to perform. These instructions execute at runtime and perform the
specified task. For example:
Static methods:
The methods can also be declared as static. A static method is associated with a class rather than the
instatnce.
The static methods are also called as class members.
Ans: Constructor Overloading: Writing two or more constructor with the same name but with different
number and types of arguments.
Example:
Class ConsDemo
{
Int i,j; ConsDemo()
{
i = 10;
j = 20;
}
ConsDemo (int a)
{
i = a;
j = 20;
}
ConsDemo (int a, int b)
{
i = a; j = b;
}
Void display()
{
System.out.println (“ i = “ +i); System.out.println (“ j = “ +j);
}
Public static void main (String args[])
{
ConsDemo a1 = new ConsDemo(); ConsDemo a2 = new ConsDemo(11); ConsDemo a3 = new
ConsDemo(111,222); a1.display();
a2.display();
a3.display();
}
}
2 Marks Questions
1. What is the use of Super keyword and This keyword?
This keyword:
This keyword refers to current object.
This keyword used to solve the program of name conflict, and differentiate the instant and local
variables.
It points to the object that is executing the block in which this keyword is present.
A java package is a group of similar types of classes, interfaces and sub- packages.
Package in java can be categorized in two form, built-in package and user- defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantages of package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Ans. Java provides four types of access modifiers or visibility specifiers i.e., default, public, private,
and protected. The default modifier does not have any keyword associated with it. When a class or
method or variable does not have an access specifier associated with it, we assume it ishaving default
access.
Types of Inheritance
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only then
we call it a single inheritance.
2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base
class. The problem with “multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often
leads to problems in the hierarchy. This results in unwanted complexity when further extending the
class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived
class, thereby making this derived class the base class for the new class.
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A.
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination
of Single and Multiple inheritance. A hybrid inheritance can be achieved in the java in a same way
as multiple inheritance can be!! Using interfaces.
2. Explain with an example: (i) Method Overloading. (ii)Method overriding. (iii) Abstract
method. (iv) Abstract class.
Ans: (i) Method overloading: It deals with multiple methods in the same class with the same name but
different method signature.
It can be static or non-static.
Example: import java.lang.*; class methodOverload Demo
{
Void add(int x,int y)
System.out.println(+(x+y);
}
int add (int x, int y,int z)
{
return;
}
Void add (double x, double y)
{
System.out.println (+(x+y));
}
}
Class methodOverloadmain
{
Public static void main (String a[])\
{
methodOverloaddemo ob = new methodoverloaddemo(); ob.add (10,20);
System.out.println (“Sum =” + ob.add (10,20,30)); Ob.add (5.5, 2.5);
}
}
(ii) Method Overriding: Overriding deals with two methods, one in the parent class other one in the
child class.
Method with super class and subclass.
class Baseclass
{
Public void getAmount (int rate)
{
............
}
}
class Myclass extends Baseclass
{
Public void getAmount (int rate)
{
............
}
}
(iii) Abstract method: The method which does not have body.
It just contains only method signature.
Compiler does not allow abstract method tp be private or final.
Example: abstract void method();
(iv) Abstract class: Abstract class is a class which contain 0 or more abstract method.
It cannot be instantiated.
An abstract class does not define a complete implementation.
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in
Java.In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just
like the abstract class.
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
// by default.
Interface fields are public, static and final by default, and the methods are public and abstract.
In this example, the Printable interface has only one method, and its implementation is provided in the
A6 class.
interface printable{
void print();
}
obj.print();
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
• Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
• Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
• Providing controlled access: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member (without
any access specifier) is accessible by classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding). All we need to do is put related
Types of packages:
package package_one;
public static void main(String[] args){ ClassTwo a = new ClassTwo(); ClassOne b = new ClassOne();
a.methodClassTwo(); b.methodClassOne();
Important points:
2. If no package is specified, the classes in the file goes into a special unnamed package (the same
unnamed
4. If package name is specified, the file must be in a subdirectory called name (i.e., the directory name
must match the package name).
5. We can access public classes in another (named) package using: package-name, class-name
UNIT III – EVENT AND GUI PROGRAMMING AND I/O PROGRAMMING
For example, java.awt.Button is a heavy weight component, when it is running on the Java platform
for Unix platform, it maps to a real Motif button.
A component is associated with a standard AWT button object, a peer object and an interfacing button
object constructed per the native GUI.
Labels, Pushbuttons, Checkboxes, Choice lists, Lists, Scroll bars, Text components
The window class can be used to create a plain, bare bones window that does not have a border or
menu.
The window class can also be used to display introduction or welcome screens.
5. What is an applet?
Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable
browser.
Application must be run explicitly within a java compatible virtual machine where as applet loads and
runs itself automatically in a java enabled browser.
Application starts execution with its main method whereas applet starts execution with its init method.
Application can run with or without graphical user interface whereas applet must run within a
graphical user interface.
Whenever we minimize, maximize, restart the applet and explicitly calling the repaint() method in the
code.
9. Why does it take so much time to access an Applet having Swing components the first
time?
Because behind every swing component are many Java objects and resources.
This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead
to faster execution of Swing applications.
We can have a pluggable look and feel feature which shows us how they appear in other platforms.
We can add images to Swing components. We have toolbars and tooltips in Swing.
Canvas
Checkbox
Choice etc.
12. What is the difference between the paint() and repaint() method?
The repaint() method is used o cause paint() to be invoked by the AWT painting thread.
A Container contains and arranges other components through the use of layout managers, which use
specific layout policies to determine where components should go as a function of the size of the
container.
The default layout manager for an Applet is FlowLayout, and the FlowLayout manager attempts to
honor the preferred size of any components.
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be
checked or unchecked.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
Border Layout: The elements of a BorderLayout are organized at the borders and the centre of a
container.
CardLayout: The elements of a CardLayout are stacked, on the top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are equal size and are laid out using the square of a grid.
The default layout manager for an Applet is FlowLayout, and the FlowLayout manager attempts to
honor the preferred size of any components.
In Grid layout the size of each grid is constant where as in GridbagLayout grid size can varied.
The Frame class extends Window to define a main application window that can have a menu bar.
22. What are the default layouts for a applet, a frame and a panel?
For an applet and a panel, Flow layout, and The FlowLayout manager attempts to honor the preferred
size of any components.
Java I/O (Input and Output) is used to process the input and produce the output. Java makes use of the
stream concepts to make I/O operation fast. The java.io package contains all the classes required for
input and output operations.
24. What is difference between Scanner and BufferedReader?
Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the
stream and does not do any special parsing. Usually we pass a BufferedReader to a scanner as the
source of characters to parse.
The window class can be used to create a plain, bare bones window that does not have a border or
menu.
The window class can also be used to display introduction or welcome screens.
java.io.FileInputStream and java.io.FileOutputStream were introduced in JDK 1.0. These APIs are
used to read and write stream input and output. They can also be used to read and write images.
PrintStream is used to write data on Console, for example, System.out.println(), here out is an object of
PrintStream class and we are calling println() method from that class.
You can also use both BufferedReader and Scanner to read a text file line by line in Java.
try {
System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
numberOfCharsRead = textFileReader.read(buffer);
textFileReader.close();
} catch (IOException e) {
e.printStackTrace();
The DataInputStream class read primitive Java data types from an underlying input stream in a
machine-independent way. While the DataOutputStream class write primitive Java data types to an
output stream in a portable way.
DataInputOutputStreamExample.java
package com.boraji.tutorial.io;
/**
* @author imssbora
* DataInputOutputStreamExample.java
* Nov 5, 2016
*/
fileOutputStream=new FileOutputStream(file);
dataOutputStream=new DataOutputStream(fileOutputStream);
dataOutputStream.writeInt(50); dataOutputStream.writeDouble(400.25);
dataOutputStream.writeChar('A'); dataOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileOutputStream!=null){ fileOutputStream.close();
if(dataOutputStream!=null){ dataOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
/*Read primitive data type from file*/ FileInputStream fileInputStream = null; DataInputStream
dataInputStream = null; try {
dataInputStream = new
DataInputStream(fileInputStream);
System.out.println(dataInputStream.readInt()); System.out.println(dataInputStream.readDouble());
System.out.println(dataInputStream.readChar());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileInputStream!=null){
fileInputStream.close();
if(dataInputStream!=null){ dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
init(): The init() method is the first method to execute when the applet is executed. Variable
declaration and initialization operations are performed in thismethod.
start(): The start() method contains the actual code of the applet that should run. The start() method
executes immediately after the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab toanother tab in the browser.
stop(): The stop() method stops the execution of the applet. The stop() method executes when the
applet is minimized or when moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is closed orwhen the tab containing
the webpage is closed. stop() method executes just before when destroy() method is invoked. The
destroy() method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet displayarea. The paint() method
executes after the execution of start() method and whenever the applet or browser is resized.
init()
start()
paint()
32. Explain the methods of Graphics class methodsCommonly used methods of Graphics
class:
1. public abstract void drawString(String str, int x, int y): is used todraw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws arectangle with the specified width
and height.
3. public abstract void fillRect(int x, int y, int width, int height): is usedto fill rectangle with the
default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): isused to draw oval with the
specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is usedto fill oval with the default
color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used todraw line between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw
the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to
fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics
current color to the specified color.
11.public abstract void setFont(Font font): is used to set the graphicscurrent font to the specified font.
import java.applet.Applet;
import java.awt.*;
}
}
33. Explain the use of FileInputStream class and FileOutputStream class.
Java provides I/O Streams to read and write data where, a Stream represents an input source or an
output destination which could be a file, i/o devise, other program etc.
FileInputStream
This class reads the data from a specific file (byte by byte). It is usually used to read the contents of a
file with raw bytes, such as images.
•First of all, you need to instantiate this class by passing a String variable or a File object, representing
the path of the file to be read.
or,
Then read the contents of the specified file using either of the variants of read() method −
oint read() − This simply reads data from the current InputStream and returns the read data byte by
byte (in integer format).
oint read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the
current InputStream, to the given array
This method returns an integer representing the total number of bytes or, -1 if the end of the file is
reached.
oint read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length
(int) as parameters and reads the contents of the current InputStream, to the given array.
oThis method returns an integer representing the total number of bytes or, -1 if the end of the file is
reached.
UNIT IV – MULTITHREADING, COLLECTIONS IN JAVA AND JAVABEANS
AND NETWORK PROGRAMMING
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one
of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
2. Runnable State: A thread that is ready to run is moved to runnable state. In this state, a
thread might actually be running or it might be ready run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run. A multi-threaded program
allocates a fixed amount of time to each individual thread. Each and every thread runs for a short
while and then pauses and relinquishes the CPU to another thread, so that other threads can get a
chance to run. When this happens, all such threads that are ready to run, waiting for the CPU and the
currently running thread lies in runnable state.
3. Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the following
states:
Blocked
Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s the
responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread. A thread in
this state cannot continue its execution any further until it is moved to runnable state. Any thread in
these states does not consume any CPU cycle.
1. A thread is in the blocked state when it tries to access a protected section of code that is
currently locked by some other thread. When the protected section is unlocked, the schedule picks
one of the thread which is blocked for that section and moves it to the runnable state. Whereas, a
thread is in the waiting state when it waits for another thread on a condition. When this condition is
fulfilled, the scheduler is notified and the waiting thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting state, another thread in the runnable state is
scheduled by the thread scheduler to run. It is the responsibility of thread scheduler to determine
which thread to run.
2. Timed Waiting: A thread lies in timed waiting state when it calls a method with a time out
parameter. A thread lies in this state until the timeout is completed or until a notification is received.
For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
Because it exists normally. This happens when the code of thread hasentirely executed by the
program.
Because there occurred some unusual erroneous event, likesegmentation fault or an unhandled
exception.
A thread that lies in a terminated state does no longer consumes any cyclesof CPU.
2. How will you create thread in java?There are two ways to create a thread:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
intended to be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performsfollowing tasks:
o When the thread gets a chance to execute, its target run() method will run.
t1.start();
Output:thread is running...
The code sleep(1000); puts thread aside for exactly one second. The code
wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the
notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is
defined in the class Thread.
4. Define deadlock.
This occurs when two threads have a circular dependency on a pair of synchronized objects. For
example, suppose one thread enters the monitor on object X and another thread enters the monitor on
object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected.
However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits
forever, because to access X, it would have to release its own lock on Y so that the first thread could
complete.
5. Define multithreading.
A thread is a line of execution. It is the smallest unit of code that is dispatchedby the scheduler. Thus, a
process can contain multiple threads to execute its different sections. This is called multithread.
A thread is a line of execution. It is the smallest unit of code that is dispatched by the scheduler. Thus,
a process can contain multiple threads toexecute its different sections. This is called multithread.
Two or more threa.ds accessing the same data simultaneously may lead to loss of data integrity. For
example, when two people access a savings account, it is possible that one person may overdraw and
the cheque
may bounce. The importance of updating of the pass book can be wellunderstood in this case.
An exception is an abnormal condition, which occurs during the execution of a program Exceptions
are erroneous events like division by zero, opening of a file that does not exist, etc. A java execution is
an object, which describes the error condition that has materialized in the program.
The try and catch clause is used to handle an exception explicitly. The advantages of using the try and
catch clause are that, it fixes the error andprevents the program from terminating abruptly.
12. What is use of ‘throw statement’ give an example? (or) state the purpose of the throw
statement.
Whenever a program does not want to handle exception using the try block, it can use the throws
clause. The throws clause is responsible to handle the different types of exceptions generated by the
program. This clause usually contains a list of the various types of exception that are likely to occur in
the program.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero
A. User Defined Exception or custom exception is creating your own exceptionclass and throws that
exception using 'throw' keyword. This can be done by extending the class Exception. There is no need
to override any of the above methods available in the Exception class, in your derived class.
A. Error: An Error “indicates serious problems that a reasonable application should not try to catch.”
Both Errors and Exceptions are the subclasses of Throwable class. Errors are the conditions which
cannot get recovered by anyhandling techniques. Errors mostly occur at runtime that's they belong to
an unchecked type.
Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code
written by the developers. Exceptions are divided into two categories such as checked exceptions and
uncheckedexceptions.
A framework is a popular and readymade architecture that contains a set of classes and interfaces.
Collection Framework is a grouping of classes and interfaces that is used to store and manage the
objects. It provides various classes like Vector, ArrayList, HashSet, Stack, etc. Java Collection
framework can also be used for interfaces like Queue, Set, List, etc.
Equals() verifies whether the number object is equal to the object, which is passed as an argument or
not.
This method takes two parameters 1) any object, 2) return value. It returns true if the passed argument
is not null and is an object of a similar type having the same numeric value.
Example:
import java.lang.Integer;
Integer p = 5;
Integer q = 20;
Integer r =5;
Short s = 5;
System.out.println(p.equals(q));
System.out.println(p.equals(r));
System.out.println(p.equals(s));
Java collection framework is a root of the collection hierarchy. It represents a group of objects as its
elements. The Java programming language does not provide a direct implementation of such interface.
Set: Set is a collection having no duplicate elements. It uses hashtable for storing elements.
List: List is an ordered collection that can contain duplicate elements. It enables developers to access
any elements from its inbox. The list is like an array having a dynamic length.
MAP: It is an object which maps keys to values. It cannot contain duplicate keys. Each key can be
mapped to at least one value.
22. Distinguish between ArrayList and Vector in the Java collection framework.
ArrayList Vector
ArrayList is cannot be synchronized. Vector can be is synchronized.
It is not a legacy class. It is a legacy class.
It can increase its size by 50% of the size of the It can increase its size by doubling the size of the
array. array.
ArrayList is not thread-safe. Vector is a thread-safe.
A server-side component, which manages the architecture for constricting enterprise applications and
managed is called Enterprise JavaBeans(EJB).
Entity Beans were presented in the earlier versions of EJB consisting of persistent data in distributed
objects.
28. Define network programming.
It refers to writing programs that executes across multiple devices (computers), in which the
devices are all connected to each other using a network.
This is often required when clients have certain restrictions on which servers they can connect to.
And when several users are hitting a popular website, a proxy server can get the contents of the web
server's popular pages once, saving expensive internetwork transfers while providing faster access to
those pages to the clients.
These two protocols differ in the way they carry out the action of communicating.
A TCP protocol establishes a two way connection between a pair of computers, while the UDP
protocol is a one way message sender.
The common analogy is that TCP is like making a phone call and carrying on a two way
communication while UDP is like mailing a letter.
Sockets provide the communication mechanism between two computers using TCP.
A client program creates a socket on its end of the communication and attempts to connect that socket
to a server.
Simple Mail Transmission Protocol, the TCP/IP Standard for Internet mails.
SMTP exchanges mail between servers; contract this with POP, which transmits mail between a server
and a client.
getInputStream() and getOutputStream() are the two methods available in Socket class.
Application
Presentation
Session
Transport
Network
DataLink
Physical Layer
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code intry block that will not throw an exception.
try{
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent classexception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiplecatch block with a single
try block.
try
{
catch(ArithmeticException e)
{
System.out.println(e);
}
36. Explain nested try statementWhy use nested try block
Sometimes a situation may arise where a part of a block may cause one errorand the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
}
}
catch(Exception e)
}
Example
class Excep6{
try{ try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");