Download 6.What is the difference between a public and a non

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1.Define class and object. Explain them with an example using java
Class: A class is a program construct which encapsulates data and operations on
data. In object oriented programming, the class can be viewed as a blue print of an
object.
Object: An object is a program construct that falls under a ‘classification’ (of a
class) which has state and behavior.
For Example: Employee is an example of a class
A specific employee with unique identification is an example of an object.
class Employee
{
// instance variables declaration
// Methods definition
}
An object of employee is a specific employee
Employee vismay =new Employee();
One of the objects of Employee is referred by ‘vismay’
2.Explain class vs. instance with example using java.
A class is a program construct which encapsulates data and operations on data. It is
a blue print of an object.
An object can be called as an ‘instance’ of a class.
The variables and methods (without static key word) that are declared in the class,
but not in the methods are called as instance variables which have one copy per
object. Once an object is created, it is said that, an instance of the class is created.
Class variables and methods occur once per class where as the instance variables
and methods occur once per instance of a class (per object).
3.What is a method? Provide several signatures of the methods
A java method is a set of statements to perform a task. A method is placed in a
class.
Signatures of methods: The name of the method, return type and the number of
parameters comprise the method signature.
A method can have the following elements in it signature:
Access specifier – public, private, protected etc. (Not mandatory)
Access modifier – static, synchronized etc. (Not mandatory)
Return type - void, int, String etc. (Mandatory)
Method name – show() (Mandatory)
With or without parameters – (int number, String name); (parenthesis are
mandatory)
Ex: void showResult () { }
public double getSalary(double basicSalary) { }
public static void finalValue() { }
public static void getStateName(String city ) { }
4.What is the difference between an Abstract class and Interface?
An abstract class can have both abstract and concrete methods whereas an interface
can have only method signatures.
A class is defined as singleton class, if and only if it can create only one object.
This class is useful when only one object is to be used in the application. The
following are some of the uses of singleton class.
5.What is a native method?
A native method is a method which is implemented in a non-java language that is
targeted for a single machine type. Native methods can pass or return Java objects.
6.What is the difference between a public and a non-public class?
A class with access specifier ‘public’ can be accessed across the packages. A
package is like a folder in GUI based operating systems. For example, the “public
class String” class is a public class which can be accessed across the packages.
7.What is the purpose of the Runtime class?
The java runtime system can be accessed by the Runtime class. The runtime
information – memory availability, invoking the garbage collector is possible by
using Runtime class.
8.What is the difference between a static and a non-static inner class?
Like static methods and static members are defined in a class, a class can also be
static. To specify the static class, prefix the keyword ‘static’ before the keyword
‘class’.
9.How
are this() and super() used with constructors?
this() constructor is invoked within a method of a class, if the execution of the
constructor is to be done before the functionality of that method..............
Read answer
10.What is the difference between the >> and >>> operators?
">>" is a signed right shift
">>>" is an unsigned right shift.
If >> is applied on a negative number, the result will still be negative.
>>> ignores the sign of the number.
If >>> is applied on a negative number,the result will be a positive number
The >> fills from the left with the sign bit (0 or 1).
The >>> zero-fills from the left.
11.What is the difference between the Boolean & operator and the && operator?
For Integers:
"&" is the "bit-wise AND" operator.
For boolean arguments:
"&" constitutes the (unconditional) "logical AND" operator
"&" always evaluates both arguments.
"&&" is defined for two boolean arguments.
It is the "conditional logical AND" operator.
"&&" ealuates the first argument. if it is true, it then evaluates the second.
12.What are primitive types in java?
Java primitive types are not reference types / objects. Java supports 8 primitive
data types. Each primitive type has a range of values. They are broadly classified
as
- Numeric – which are sub classified as - byte, short, int, long, float and double
- Character - char
- Boolean - boolean.
All numeric data types are signed and there are no unsigned numeric data types.
The size of each data type does not change from one architecture to that of another.
Due to this property, Java is so portable. The entire range of values of a specific
data type occupies same amount of memory space.
13. What are primitive types in java?
Data Type
Default Value (for fields)
Size
byte
0
8-bit signed
short
0
16-bit signed
int
0
32-bit signed
long
0L
64-bit signed
float
0.0f
single-precision 32-bits
double
0.0d
double-precision 64-bit
char
'\u0000'
String
null
boolean
false
16-bit Unicode character
not precisely defined
14.Explain the difference between Integer and int in java.
The following are the differences:
- Integer is a wrapper class, where as int is a primitive data type.
- Integer can be used as an argument to a method which requires an object, where
as int can be used as an argument to a method which requires an integer value, that
can be used for arithmetic expression.
- The variable of int type is mutable, unless it is marked as final. Integer class
contains one int value and are immutable.
Java variables interview questions
What is transient variable?
A variable declared as "transient" in a Serializable class cannot be serialized
although the class is declared as serializable..................
What is the difference between static and non-static variables?
A static variable is shared among all instances of a class..............
What is the difference between a field variable and a local variable?
Field variables: Variable that are declared as a member of a class. OR Variables
declared outside any method/constructor but inside the class block..................
What is inheritance?
Through inheritance, classes can inherit commonly used state and behavior from
their parent class. One class can have a single parent class and a class can have
unlimited number of subclasses.
Syntax:
class B extends class A
{
// new fields and methods
}
class C extends class A
{
// new fields and methods
}
class D extends class A
{
// new fields and methods
}
What is an overloaded method?
Overloaded methods are the methods which have the same name but different
signatures.
Eg:
void calculate(float x){
}
void calculate(double x){
}
void calculate(int x){
}
How do we allocate an array dynamically in java?
An array can be created dynamically with an initializer. For ex:
int numbers[] = {1, 2, 4, 8, 16, 32, 64, 128};
This syntax dynamically creates an array and initializes its elements to the
specified values.
Java - allocate an array dynamically in java - 19 Jan, 2009 at 15:00 PM by Amit
Satpute
How do we allocate an array dynamically in java?





Arrays in java are static lists that can store a certain kind of variables.
Therefore these arrays need to be initialized at the compile time.
Though arrays offer efficient performance, they are not space efficient when
the data grows to thousands of entries. In this case, it is always a better idea
to allocate the memory dynamically. This is where a vector comes into
picture.
The key difference between Arrays and Vectors in Java is that Vectors are
dynamically-allocated.
Each Vector can contain a dynamic list of references to other objects.
Therefore, they need not contain a single type of variable.
The Vector class is found in the java.util package, and extends
java.util.Abstractlist
Explain with example how to initialize an array of objects.
Create an array with new key word as follows:
Film films[] = new Film[4];
Use individual element of array films[] with index for creating individual objects
of the class. Select the appropriate constructor for sending parameters. The
following example depicts this
films[0] = new Film("Shrek",133);
films[1] = new Film("Road to Perdition",117);
films[2] = new Film("The Truth about Cats and Dogs",93);
films[3] = new Film("Enigma",114);
Java - how to initialize an array of objects - 19 Jan, 2009 at 15:00 PM by Amit
Satpute
Explain with example how to initialize an array of objects.
An array can be instantiatd in various ways as follows:
int[] arr = new int[5];
int arr[] = new int[5];
int[] arr = Array.newInstance[int, 5];
int[] arr = {0,1,2,3,4};
int[][] arr2 = new int[length1][length2];
list1 = new Object[5];
//2D array
//An array of objects
Java - Difference between a Vector and an Array - Feb 28, 2010 at 16:16 PM by
Vidya Sagar
What is the difference between a Vector and an Array. Discuss the advantages and
disadvantages of both?
Differences between a Vector and an Array
- A vector is a dynamic array, whose size can be increased, where as an array size
can not be changed.
- Reserve space can be given for vector, where as for arrays can not.
- A vector is a class where as an array is not.
- Vectors can store any type of objects, where as an array can store only
homogeneous values.
Advantages and disadvantages of Vector and Array:
Advantages of Arrays:
- Arrays supports efficient random access to the members.
- It is easy to sort an array.
- They are more appropriate for storing fixed number of elements
Disadvantages of Arrays:
- Elements can not be deleted
- Dynamic creation of arrays is not possible
- Multiple data types can not be stored
Advantages of Vector:
- Size of the vector can be changed
- Multiple objects can be stored
- Elements can be deleted from a vector
Disadvantages of Vector:
- A vector is an object , memory consumption is more.
What is an Exception? Explain by giving an example.
Exceptions are errors that occur at runtime and disrupt the normal flow of
execution of instructions in a program.
An exception object is created by the method in which an error occurs which is
then handed over to the runtime system. This process is called throwing an
exception. The object contains the details of the error, its type, etc.
An exception handler is the code that executes after an exception is encountered.
The runtime method searches the call stack to find an appropriate method
containing the code for handling the exception. The runtime system after receiving
the exception tries to find a suitable way to handle it.
When the type of exception thrown matches the type of exception that can be
handled, the exception is passed on to the handler so as to catch the exception. The
three types of exceptions are:
checked exceptions, errors and runtime exceptions.
An event that occurs during the execution of a program that disrupts the normal
flow of instructions is called an exception.
Eg:
public static void Main ()
{
int numerator, denominator;
try
{
int quotient = numerator/denominator;
}
catch (DivideByZeroException e)
{
System.out.println("Divide By Zero Exception Occurred!");
}
}
Checked Exceptions vs. Unchecked Exceptions
Checked Exceptions



A checked exception is a subclass of Exception excluding class
RuntimeException and its subclasses.
Compiler checks to see if these exceptions have been properly caught or not.
Else the code doesnt compile. Thus, a program is forced to deal with the
situations where an exception can be thrown.
Checked exceptions must be either declared or caught at compile time.
Unchecked Exceptions

Unchecked exceptions are RuntimeException and all of its subclasses along
with class java.lang.Error and its subclasses also are unchecked.

A program does compile without these exceptions being handled during
compile time.
What is a user defined exception?
At times, depending on the need of a program, a programmer might need to create
his own set of exceptions. These exceptions are called as the User defined
Exceptions.
The user defined exception class should extend from Exception class.
You may override the toString() method in order to display a user friendly
message.
Eg:
BloodGroupException.java
public class BloodGroupException extends Exception {
private String gp;
public BloodGroupException (String gp){
this.gp = gp;
}
public String toString(){
return "This is an incorrect Blood Group” ;
}
}
What are the different ways to generate an Exception?
There are 3 ways in which the exceptions are generated:



The JVM can generate exceptions which are beyond the control of the User.
A few standard exceptions that can be generated due to an error in the
program and which need to be handled manually.
The third way is to directly throw an exception. However, it is handled in the
similar fashion.
How are try, catch and finally block organized?
The try block is the region of code where exceptions can get produced. So most of
the code of execution lies in this region.
The catch block is where an Exception is caught. Then, the action to be performed
upon catching the exception is stated in this block. Usually a user friendly message
is displayed.
The finally block is the region where the code that needs to be executed under any
circumstance is written. This is usually the performing a clean up. Eg: freeing the
resources, etc. If the finally clause executes a return statement, it overrides a
thrown exception (so the exception will not be thrown; instead the return will
occur).
What is a throw in an Exception block?
The different ways to use a throw are:
if (condition) {
throw new xxxException();
}
method_name() throws xxxException
What are Chained Exceptions?
Example of a chained exception:
try {
} catch (IOException e) {
throw new xxxException("Other IOException", e);
}
When an application responds to an exception by throwing another exception, it is
very useful to know when an exception caused another. Chained Exceptions help
the programmer do this.
The following are the methods and constructors in Throwable that support chained
exceptions.



Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)

Throwable(Throwable)
What is the purpose of the finally clause of a try-catch-finally statement?
The finally block is the region where the code that needs to be executed under any
circumstance is written. The purpose of this block is usually performing the clean
up activities.
Eg: freeing the resources, etc. If the finally clause executes a return statement, it
overrides a thrown exception (so the exception will not be thrown; instead the
return will occur).
Java input & output interview questions
Explain how to read a line of input at a time.
Reading a line of input at a time is done by using console’s input stream , the
System.in. This object is wrapped by an InputStreamReader. InputStreamReader
reads the data in binary stream one character at a time and converts it to character
stream. To read the data at a time, BufferedReader is wrapped around the
InputStreamReader. The method readLine() of BufferedStream reads the line of
characters.
EX :
String str;
BufferedReader br = new BufferedReader(InputStreamReader(System.in));
str = br.readLine();.
Input from the console is read from the System.in object and is then wrapped by an
InputStreamReader which reads one character at a time.
To read this data a line at a time, a BufferedReader is wrapped around the
InputStreamReader.
class MyReader
{
public static void main(String[] args) throws IOException
{
String s = "";
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
// type 00 to exit from the program
while (!(s.equals("00")))
{
s = in.readLine();
if (!(s.equals("00")))
{
System.out.println(s);
}
}
}
}
When do we need to flush an output stream?
If any bytes that are previously written and have been buffered by the
implementation of the output stream then such bytes need to be immediatel written
to their intended destination. This is where flush needs to be used. It flushes this
output stream and forces any buffered output bytes to be written out.
The use of flush() comes when any bytes previously written have been buffered by
the implementation of the output stream. Such bytes should be immediately written
to their expected destination.
Explain the purpose of Event object.
EventObjects represent events. Applications subclass this class to add event
specific information.
public EventObject(Object source)
public Object getSource() returns the object on which the Event initially occurred.
public String toString() returns a String representation of this EventObject.
Explain how to force garbage collection.
Garbage collection can't be forced, it can explicitly be called using System.gc(),
but there is not guarantee that GC will be started immediately.
Java - garbage collection - Jan 15, 2009 at 8:10 am by Rajmeet Ghai
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory.
The garbage collection is dependant on the JVM. Hence it is possible for the
resources to be used faster than they are garbage collected. Garbage collection
cannot be predicted if it will happen or not.
Java - garbage collection - Jan 15, 2009 at 7:10 am by Amit Satpute
Does garbage collection guarantee that a program will not run out of memory?
Programs can in general create objects (that are not subject to garbage collection)
and use memory resources faster than they can be garbage collected. Hence,
Garbage collection does not guarantee that a program will not run out of memory.
What is an applet? How does applet differ from applications?
A program that a Java enabled browser can download and run is an Applet.
An applet is embedded in a web-page and runs in the browser context.
The java.applet.Applet class provides a standard interface between the applet and
the browser environment.
Applets cannot perform actions such as reading/writing to the file system. Java
applications run standalone, outside the browser.
Explain how to implement an applet into a web page using applet tag
To view an applet in the browser, following steps need to be followed:
Compile the applet you have written … the .java file so as to get the .class file.
Then, include the following code in your .html file:
<APPLET CODE="XZY.class" WIDTH=100 HEIGHT=100>
</APPLET>
What are the attributes of Applet tags?
height: Defines height of applet
width: Defines width of applet
align: Defines the text alignment around the applet
alt: An alternate text to be displayed if the browser support applets but cannot run
this applet
archive: A URL to the applet when it is stored in a Java Archive or ZIP file
code: A URL that points to the class of the applet
codebase: Indicates the base URL of the applet if the code attribute is relative
hspace: Defines the horizontal spacing around the applet
vspace: Defines the vertical spacing around the applet
name: Defines a name for an applet
object: Defines the resource name that contains a serialized representation of the
applet
title: Display information in tool tip
Explain how to set the background color within the applet area
You can set the background color of an applet in the following manner:
<applet code="MyApplet.class" width="100" height="100">
<param name="background-color" value="#ffffff">
<param name="foreground-color" value="#000000">
</applet>
What are methods that controls an applet’s life cycle, i.e. init, start, stop and
destroy?
Life Cycle of an Applet: Basically, there are four methods in the Applet class on
which any applet is built.
init: This method is intended for the initialization of your applet and is called after
the param attributes of the applet tag.
start: This method is automatically called after init.
stop: This method is automatically called whenever the user moves away from the
page containing applets.
destroy: This method is only called when the browser shuts down normally.
What are the methods that control an applet’s on-screen appearance? I.e. update
and paint.
The paint() method is called in situations the applet window being overwritten by
another window or uncovered or the applet window being resized.
The paint() is also called when the applet begins execution. The paint() method has
one parameter of type Graphics which is needed to know the location wher the
applet is supposed to paint its output.
The update() is called when a portion of its window be redrawn. It is defined by the
AWT.
However, the update() first fills an applet with the default background colour and
then calls paint() due to which an instance of the default color appears each time
update is called.
Thus update() method should be overridden to avoid this situation.
What is the purpose of “this” keyword?
"this" refers to current object instance.
"super" refers to the member of superclass of the current object instance.
It invokes the constructor of the parent class.
“this” keyword is used to refer current instance of object.
xplain how to play sound in an applet
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Audio1Applet extends Applet implements ActionListener{
Button play,stop;
AudioClip audioClip;
public void init(){
play = new Button(" Play ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "abc.wav");
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play "){
audioClip.play();
}
else if(source.getLabel() == " Stop "){
audioClip.stop();
}
}
}
<APPLET CODE="Audio1Applet" WIDTH="100" HEIGHT=
"100"></APPLET>< H5><<Previous Next >>
What is the difference between an Applet and an Application?
An applet runs with the control of a browser, where as an application runs
standalone. The application runs with the support of a virtual machine.
An applet has restrictions with respect to network access, whereas the application
does not. Interactive and dynamic applications can be used with applet. A java
application can have full access to network and local file system.
Java abstract window toolkit interview questions
What are the component and container classes?
A component is a graphical object. A few examples of components are:


Button
Canvas







Checkbox
Choice
Container
Label
List
Scrollbar
TextComponent
public class Container extends Component and is a component that can contain
other AWT components.
A few examples of are:








BasicSplitPaneDivider
Box
CellRendererPane
DefaultTreeCellEditor.EditorContainer
JComponent
Panel
ScrollPane
Window
Explain the purpose of invalidate and validate methods
The invalidate method is called as a side efftect of an addition or deleting some
component. calling invalidate() is however the first step of processing a
COMPONENT_RESIZED event.
validate() checks if a container is valid or not.
It calls layout or validateTree to calculate the exact positions and sizes of all the
contained components.
validate() also decides the new size and location of a component in the container.
What are AWT peers? When are peers created and destroyed?
A Component is associated with a standard AWT button object, a peer object
(hidden button object internal to the native GUI) and an interfacing button object
constructed per the native GUI.
The behaviour of the particular Component can depends the peer. The peer object
for a Button contains platform-dependent code whereas the AWT button object
would be identical for all platforms.
Explain how to create a borderless window
public static void main(String[]args)
{
JButton button1=new JButton("MY BUTTON");
JWindow window=new JWindow();
window.getContentPane();
window.setSize(100,100);
window.setVisible(true);
}
What is Remote Procedure Calls, RPC?
In distributed systems, a client calls a procedure stored on a server. This is called
calling a remote procedure stored on a server. Though, the call is made as if the
procedure was stored on the local machine.
The steps in which a RPC is made are:











The client calls the procedure
The client stub builds the message.
The message is sent over the network.
The Server OS gives the message to the server stub.
The server stub unpacks the message.
The stub makes a local call to the procedure.
The server does the work and returns the result to the server stub.
The stub packs the message and traps to the kernel.
The remote kernel sends the message the client kernel.
The client kernel gives the message to the client stub.
The client stub unpacks the result and gives to the client.
Explain the advantages and disadvantages of RPC.
Advantages of RPC:


Server independent
Process-oriented and thread oriented models supported by RPC





The development of distributed systems is simple because it uses
straightforward semantics and easier.
Like the common communications between the portions of an application,
the development of the procedures for the remote calls is quite general.
The procedure calls preserves the business logics which is apt for the
application.
The code re-writing / re-developing effort is minimized.
Enables the usage of the applications used in the distributed environment,
not only in the local environment.
Disadvantages of RPC:




Context switching increases scheduling costs
RPC is not a standard – it is an idea that can be implemented in many ways
RPC does not solve the most of the distribution creation problems
RPC is only interaction based. This does not offer any flexibility in terms of
hardware architecture.
Explain the difference between RPC and RMI.
RMI:


The remote objects are accessed by the references
Implements object to object implementation among different java objects to
implement distributed communication model.
- RMI passes the objects as parameters to remote methods.
- RMI invokes the remote methods from the objects
RPC:




The process is through methods / functions
Proxy server is involved in processing the procedure calls
Calls a procedure remotely like invoking the methods
The remoteness is not exactly transparent to the client
Explain the architecture of RMI.
RMI is based on client-server architecture model. The stub plays the role of a
proxy server for the remote objects. The skeleton lives in the same JVM as the
remote object and communication will be handled with the stub. The remote
references are managed by the registry. The binding of server with reference to
itself will be on the registry. The clients communicate with a registry which in turn
obtains a remote reference to the server. This could be a remote host. The remote
reference could be obtained by the client from the registry in order to invoke the
methods from the remote object.
Describe how to open a database connection using JDBC.
Opening a database connection:
The database connection should be established after registering the drivers. The
getConnection is used to open a database connection. The following code snippet
illustrates this:
Connection con;
con = DriverManager.getConnection(url,"scott","tiger");// returns the connection
object
where url specifies the database server port, ip address,domain name etc. For ex:
jdbc:oracle:thin:@192.137.63.230:1521:MyCompany
the ip address is an imaginary one and not intended to specify any specific system.
The “scott” and “tiger” are the user name and passwords respectively.