Upload
vijay
View
235
Download
0
Embed Size (px)
Citation preview
8/18/2019 2 Marks IT51
1/28
!"#$%&" &' &"(!"
1. What is object oriented programming? How does it differ from procedural concepts?
• Object Oriented Programming (OOP) is a new programming paradigm in which
programming problem is divided into a set of Objects. Objects are created by combining
the data and the related operations (methods).
• In procedural programming problem is divided into set of procedures and those are
focused rather than data. But in Object Oriented Programming data is focused rather than
algorithm.
2. What are the most striking features of Object oriented programming?
• Data hiding and data abstraction
• Inheritance
• Polymorphism
• Dynamic binding
3. Define objects in Object oriented programming.
• Objects are the basic dynamic entities in an Object oriented system.
• Objects should be matched closely with the real world Objects.
• Objects contain data and functions which handles data.
4. What is Data abstraction?
• The technique that reveals the essential features to the user without including the
background details is known as Data abstraction.
• Both the data and functions can be abstracted in Class data type.
5. What is encapsulation?
• The process of combining data and functions together into a single entity is called
as Encapsulation.
• Encapsulation plays a major role in Object oriented system.
• Because the data and functions are tied into an Object, outside world cannot access
the data. This is known 'as Data hiding.
8/18/2019 2 Marks IT51
2/28
6. What is the use of inheritance?
Inheritance increases the reusability of the code. Because the newly created Class by
deriving from the existing Class will have the combined features of both.
7. What is mean by polymorphism?
• The ability of an Object to respond differently to the different messages is known
as Polymorphism.
• Polymorphism provides a way to take elements in more than one from.
• In inheritance, when new Objects share common behavior and also contain
special behavior specific to that Object Polymorphism occurs to reduce the
complexity.
8. How is the message passed between objects?
• Objects in Object oriented system can communicate with each other using
messages.
• Messages’ passing between Objects is necessary to simulate the real world objects.
• Message is passed by calling the procedures of the Object with information
(arguments).
• Message passing consists of Object name, method name with arguments
9. List the advantages of Object oriented programming.
• Programs can be organized as a collection of Objects which can be managed
easily
• Data hiding provides security to the data, as unrelated functions cannot access its
data.
• Data abstraction enables the user to know only the essential details of an object.
Because each Object is independent, changes in one Object will not affect others.
• Object oriented systems can be easily extended by adding the additional features.
•
Inheritance avoids the redundancy of code.• Polymorphism reduces software complexity.
10. List any four applications of OOPs.
• Real time systems
• Simulation and modeling
• Object oriented databases
8/18/2019 2 Marks IT51
3/28
• Hypertext and Hypermedia
11. List the features of java.
• Object oriented programming
• Compiled and interpreted translation
• Platform independent and portable code
• High security
• Distributed network support
• Multi-thread support
• Dynamic linking
• Automatic garbage collection
• Direct database access
• Core XML support
12. What kind of programs can be developed in Java?
Java is an object oriented, general-purpose, portable programming language. It is
suitable for both internet programs and application programs. So, two kinds of java pro
can be developed. They are
• Stand-alone applications
• Web applets
13. What are tokens?
Tokens are the smallest individual units in a program. Tokens are constructed
from java support character set. Expressions and statements are constructed from tokens.
They are divided into 5 types. They are
• Keywords
• Identifiers
• Constants
• Operators
• Separators
14. What are keywords?
Keywords are the special reserved words having special meaning to the java compiler.
These are reserved for special purpose in the program coding. So keywords cannot be
8/18/2019 2 Marks IT51
4/28
used as Identifiers. All the keywords represented as lower case letters.
Example: int, double, abstract, try, catch
15. What are the rules to be followed to form identifiers?
• It can consist of alphabets, digits, underscore (_) and dollar sign.
• It must not start with digit
• It can be of any length.
• It is case sensitive. That is upper and lower case letters are distinct
16. How does character constant differ from string literal?
Character constant String literal
Single character is used Sequence of characters are used
Enclosed between single quotes Enclosed between double quotes
17. What is the difference between the statements a++ and ++a?
++a - preincrement(after the increment value of a is used)
a++ - postincrement(before the increment value of a is used)
Example
if a=10 means
a++ gives 10 and then a becomes 11.
++a becomes 11 and gives 11
18. List the characteristics of a class.
• It can have fields and methods.
• A class and members can be preceded with an access specifier.
• It can be normal or abstract
• It can have static and final members
• It can be derived from another class.
• It can be implemented from interfaces.
19. How will you define a class?
Defining a class consists of two steps. They are
• Fields declaration
• Methods declaration
20. What are the parts available in a method?
8/18/2019 2 Marks IT51
5/28
• Method name - the name that is used to invoke the method. It must be
a valid identifier.
• Arguments list - List of values with data types that are required to do the
process. This may be empty.
• Return type - The type of the data that is going to be returned after the
processing. void is specified when it does not return anything.
• Method body - The process that is going to be done by this method.
21. Differentiate mutators and accessors.
Mutators Accessors
Methods that change field values of an
object are called mutator methods.
Example:
public void change(int n1 ,int n2)
{
Numl=nl;
Num2=n2;
}
Methods that only access fields of an object
without modifying them are called accessor
methods.
Example:
public int Get_Num()
{
return Num;
}
22. What are the three key characteristics of objects?
• Identity - the name to identify the object uniquely among multiple objects
(Object name)
• Behavior - the processes that can be done on fields by the objects (Methods)
• State - the changes in the data after the processing or initialization (Fields)
23. How will you create objects?
Objects are instantiated using new Operator. The new operator creates an object
of the specified class and returns a reference to that Object. Memory space is allocated
only to the fields and not to the methods.
classname object_name = new classname(actual_arguments __ list); //arguments to the
constructor
24. List the access specifiers.
private, public, protected and default
8/18/2019 2 Marks IT51
6/28
25. What is meant by static field?
A field can be declared with static. Static fields are also known as class fields.
Because it is not related to any object. Normally each object has its own copy of all
instance fields. But, only one instance is created for each static field and that is shared by
all the objects. Static fields are common to all the objects. So class name is enough to
access the static fields. But it is legal to use an object to access a static field.
26. What are the characteristics of static methods?
• It can access only the static fields and the static methods.
• It can be accessed by the normal and static methods of its own class
• It can be accessed using the class name or object name from another class
• It cannot refer this and final
27. What are the functions of a constructor?
• It can be used to allocate memory to the fields.
• It can be used to initialize the fields.
28. What is a default constructor?
Default constructor is a constructor with no arguments. If no constructor is
defined in a class, then a default constructor is automatically provided by the compiler.
This default constructor assigns default values to all the fields in a class. That is, 0 is
assigned to all the numeric fields and false is assigned to all boolean fields and null is
assigned to all the objects. If at least one constructor is defined in a class, the compiler
will not include any default constructor and then it is illegal to construct objects
without construction parameters.
29. What are the steps followed when a constructor is called?
• Default values are assigned to all the fields.
• Field initializers and initialization blocks are executed one by one as they
are declared in the class.
• If the first line of the constructor invokes the second constructor, the second
constructor is executed.
30. What is the purpose of using this keyword?
this keyword is used to refer the object which invoked the method. this keyword
can be used inside any method to refer to the current object. That is, this always has
8/18/2019 2 Marks IT51
7/28
reference to the object on which the method was invoked. Normally a method is called
with two types of arguments implicit and explicit. Implicit argument is assigned to this.
Example:
void Change _ val(int N um I, int Num2)
{
This.Num1=Num1;
This.Num2=Num2;
}
31. What is the use of finalize method?
• Finalize method is similar to a destructor in C++. But manual memory
reclamation is not needed, because Java does automatic garbage collection.
• In some situations, objects utilize a resource other than memory, such as a file
or a handle to another object that uses system resources. Finalize method be
defined in these situations to free the resources, when it is no longer needed.
• The finalize method will be called before the garbage collector removes the
object.
• Only one finalize can be defined to a class.
32. What are the advantages of using packages?
• Classes can be easily reused.
• Two classes in different packages can have same name.
• It provides way to hide classes
33. How will you hide a class in packages?
Only the public classes in a package are accessible from outside. Non-public
classes are not accessible. Thus the classes are hidden in a package.
Example
package mypack;
class A //secured class
{
……
}
public class B //accessible from outside
8/18/2019 2 Marks IT51
8/28
{
A a;
……
}
34. List the types of comments.
• Class comments
• Method comments
• Field comments
• Packages and overview comments
35. What are tags that can be inserted in a class comment?
@ author name
This tag adds entry about the author. Multiple author tags can be put.
@ version text
This tag adds entry about the version. The text can be any description of the current
version.
@ since text
This tag adds entry about the version that introduced this feature.
@ deprecated text
This tag adds a description that the class, method, or variable should not be usedThe text should tell a replacement.
@ see reference
This tag adds a hyperlink in the see also section. It can be used with both classes
and methods.
36. What are package comments?
Package and overview comments
Class, method, and variable comments are placed directly into the Java source files
delimited by /** ... */ documentation comments. But, to generate package comments, a
separate file is to be added in each package directory. For this two methods are used
Method-l
An HTML file named package.html is created and supplied. All the text
between the tags ... are extracted.
8/18/2019 2 Marks IT51
9/28
Method-2
A Java file named package-info.java is created and supplied. The file must
contain an initial Javadoc comment with /** and */ followed by a package statement. It
should not contain other code or comments.
37. What is meant by array?
Array is a collection of similar data type values that share a common name. Each
element in an array can be accessed by using the index number or sub subscript. In java,
array is an object.
Example
To access the 3th
element in the array mark[ ], following statement can be used
mark[2]
38. How will you declare an array?
Array declaration
An array can be declared by specifying the data type followed by [] with array
name. Array declaration only declares the name of an array. No memory space is
allocated. So we cannot use it before instantiation. Size should not be given to an array at
the time of declaration.
General form of array declaration
data_type array_name[];
(or)
data_type [ ] array_name;
39. How an array length is is extracted?
Size of an array can be obtained by accessing the attribute length.
Size=arrayname.length;
40. What is meant by Anonymous Arrays?
An anonymous array is an array created without any name. It is used to
reinitialize an array without creating a new variable.
General form
array_name=new data_type[]{ values_list };
Example
mark=new int[ ]{ lO,20,30,40,50};
8/18/2019 2 Marks IT51
10/28
41. Explain about arraycopy() method.
It just copies the content of one array in another. But the destination must have
sufficient memory space to hold the source values.
General form
System.arraycopy( source, source _ index,destination,destination _ index,count);
42. What is meant by ragged arrays?
Ragged arrays are arrays in which different rows have different lengths. In Java,
multidimensional arrays are represented as array of arrays, that is, collection of one
dimensional array. There are no multidimensional arrays in Java.
Example
int a[][]=new int[2][];
a[0]=new int[5];
a[l]=new int[l0];
Now a contains 5 elements in first column and 10 elements in the second column.
43. What is the use of + operator on strings?
The + sign can be used to concatenate (join) two strings. During the concatenation non-string
operands are converted into string type.
44. How will you compare two strings?
Strings are compared by using 3 methods. equals() , equalsIgnoreCase() and
compareTo()·
Example
strl.equals(str2);// if strl and str2 are equal returns true, otherwise false.
strl.equalslgnoreCase (str2); // same as above, but ignores the case
strl.compareTo(str2); // strl=str2 - 0, strl>str2 - positive, strl
8/18/2019 2 Marks IT51
11/28
46. What is meant by inheritance?
Inheritance is the process by which new classes called derived classes are
created from existing classes called base classes
47. What are the advantages of inheritance?
• Reusability of code
• Effort and Time saving
• Increased reliability
48. How many classes can be extended by a class? Write the syntax
A class can extend only one class.
Syntax:
class derivedclassname extends baseclassname
{
…….
}
49. Write a short note on method overriding.
The method overriding is an example of runtime polymorphism. We can have a
method in subclass overrides the method in its super classes with the same name and
signature. Java virtual machine determines the proper method to call at the runtime, not at
the compile time.50. Why are the final methods used?
These are used to prevent a method from overriding by the subclasses.
51. Write short notes on final fields.
A final variable can only be assigned once. This assignment does not grant the
variable immutable status. If the variable is a field of a class, it must be assigned in the
constructor of its class. The value of a final variable is not necessarily known at compile
time, but value of constant is known at compile time.
Example:
public static final double PI = 3.141592653589793;
52. What is an abstract class?
An abstract class is class that cannot be instantiated. (i.e.) objects are created
for an abstract class. It can only be used as a super class for other classes that extend
8/18/2019 2 Marks IT51
12/28
the abstract class.
53. Explain the use of interface in event handling.
• an object that can generate an event maintains a list of objects that would like to
listen for that event (they will be notified when the event occurs by having one
of their methods called)
• the object that generates the event flres it by going through its list of objects that
want to handle the event, and calling a specified interface method for each
object
• a class may handle an event if it implements the interface that is expected for that
event - therefore it will have the specified method
54. What are the methods available in the object class?
• clone()• equals()
• copy(Object
• finalize()
• getClass()
• hashCode()
• notify()
• notifyAIl()
• toString()
• wait()
55.
Which programs use reflection?Reflection is commonly used by programs which require the ability to examine or
modify the runtime behavior of applications running in the Java virtual machine.
56. How can we get the class name using reflections?
From a Class object we can obtain its name in two versions. The fully qualified
class name (including package name) is obtained using the getName() method like this:
class aclass = ... //obtain class object.
String className = aClass.getName();
If we want the class name without the package name you can obtain it using the
getSimpleName() method, like this:
class aclass = ... //obtain class object.
String simpleClassName = aClass.getSimpleName();
57. What are the two major stream classes available in java.io package?
8/18/2019 2 Marks IT51
13/28
• Byte stream classes
• Character Stream classes
58. Write short notes on input stream class.
Input stream is an abstract class that defines a model of streaming byte input. All
of the methods in this class will throw an IOException on error conditions.
Methods Description
int available () Returns the number of bytes of input currently available for
reading
void close () Closes the input source. Further read attempts will generate an
IOException
void mark (int numBytes) Places a mark at the current point in the input stream that will
remain void until numBytes are used
int read () Returns an integer representation of the next available byte of
input -1 is returned when the end of the file is encountered
Long skip (long
numBytes)
Ignores numBytes bytes of input returning the number of bytes
actually ignored
59. Write short notes on output stream class
• Output Stream is an abstract class that defines streaming type output.
• All of the methods in this class return a void value and throw an IOException in the
case of errors.
Method Description
void close () Closes the output stream further write attempts will
generate an IOException
void flush () Finalizes the output state so that any buffers are cleared.
That is, it flushes the output buffers.
void write (int b) Writes a single byte to an output stream
void write(byte buffers []) Writes a complete array of bytes to an output stream
60. What is a character stream?
8/18/2019 2 Marks IT51
14/28
• Character stream are defined by using two hierarchies. At the top are two
abstract classes, Reader and Writer.
• These abstract classes handle unicode character streams.
61. What is a file input stream?
The FileInputStream class creates an InputStream that can be used to read bytes
from a file. Its common constructors are as follows:
FileInputStream (Stream filepath)
FileInputStream (File fileobj)
filepath – is a full path name of a file
fileobj – is a file object that describes the file
62. What is a file output stream?
FileOutputStream creates an outputStream can be used to write bytes to a file.
The form of constructors used
FileOutputStream (String filepath)
FileOutputStream (File fileobj)
FileOutputStream (String filepath, boolean append);
filepath – is the full path of the file
fileobj – is a file objec that describes the file
append – if it is true, thefile is opened in append mode63. What is meant by object cloning?
Object Cloning is the process of creating identical copy of an object. An identical
copy of an object is created by invoking clone() on that object.
64. What are the different types of cloning?
• Deep Cloning
• Shallow cloning
65. What will be the results when we invoke the clone() method?
• return an Object reference to a copy of the object upon which it is invoked,
or
• throw CloneNotSupportedException
66. What are inner classes?
An inner class is a class declared entirely within the body of another class or interface. It
8/18/2019 2 Marks IT51
15/28
is distinguished from a subclass.
67. Write about dynamic proxy class.
A dynamic proxy class is a class that implements a list of interfaces specified at
runtime when the class is created, with behavior.
68. What is the need of graphics programming?
To provide Graphical User Environment (GUI) to the Java applications, graphics
programming plays a vital role.
69. What is a frame?
A Frame is a top-level window. It consists of:
• A top part with a title, a little icon and buttons to minimize, maximize and
close the window.
• An optional menu area.
• A content area where we can place buttons, text, drawings etc.
70. How will you show a frame on the screen?
Calling setVisible(true) makes the frame appear onscreen. Sometimes we might
see the show method used instead. The two usages are equivalent, but we use
setVisible(true) for consistency's sake.
frame.setVisible(true);
71.
What are components?A component is an object having a graphical representation that can be displayed
on the screen and that can interact with the user. Examples of components are the
buttons, checkboxes, and scrollbars of a typical graphical user interface.
72. What is the use of setSize() method?
It resizes the component, it changes the size of width and height.
frame.setSize(1000,700);
73. List some graphics class line and shapes drawing methods.
void drawLine(int x1, int y1, int x2, int y2);
void drawOval(int x, int y, int h);
void drawRect(int x, int y, int w, int h);
void drawRoundRect(int x, int y, int w, int h, int aw, int ah);
void drawArc(int x, int y, int w, int h, int start, int angle);
8/18/2019 2 Marks IT51
16/28
74. What are the constructors available for Line2D class?
public Line2D.Float();
public Line2D.Float(float xl, float yI, float x2, float y2);
public Line2D.Float(Point2D pI, Point2D p2);
public Line2D.Double();
public Line2D.Double(f1oat xl, float yl, float x2, float y2);
public Line2D.Double(Point2D pI, Point2D p2)
75. What are the seven primary attributes of rendering engine?
• Paint• Stroke
• Font
• Transformation
• Clipping space
• Rendering hints
• Compositing rule
76. What are the logical font families defined by Java 2D?
• Dialog
• DialogInput
• Monospace
• Serif
• SansSerif
77. How can we extract all the font families installed in the system?
Java software provides access to other fonts that are installed on our system. The
names of all available font families can be found by calling the following:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontFamilies = ge.getAvailableFontFamilyNames();
78. How are the colors represented in java
Colors are represented by the java.awt.Color class. In Java 1.0 and Java 1.1, this
class represents colors in the RGB color space. It has constructors that allow you to
specify red, green, and blue color coordinates as integers or as floating-point values.
The class defines a static method that allows you to create a Color using coordinates
from the HSB (hue, saturation, brightness) color space. It also defines a number of
constants that represent colors by their common names, such as Color.black and
Color.white.
8/18/2019 2 Marks IT51
17/28
79. List the constants that represent colors.
Color.blackColor.blue
Color.cyan
Color.darkGrayColor.Gray
Color.green
Color.lightGray
Color.magenta
Color.orange
Color.pink
Color.red
Color.white
Color.yellow
80. Define event driven programming.
Event-driven programming can be defined as an application architecture
technique in which the application has a main loop which is clearly divided down to
two sections: the first is event selection (or event detection), and the second is event
handling. In embedded systems the same may be achieved using interrupts instead of a
constantly running main loop; in that case the former portion of the architecture resides
completely in hardware.
81. List the adapter classes for the different EventListener interfaces provided by the
AWT.
• ComponentAdapter
• ContainerAdapter
• FocusAdapter
• KeyAdapter
• MouseAdapter
• MouseMotionAdapter
• Window Adapter
82. What are the methods declared by MouseListener?
public abstract void mousePressed(MouseEvent evt)
public abstract void mouseReleased(MouseEvent evt)
8/18/2019 2 Marks IT51
18/28
public abstract void mouseEntered(MouseEvent evt)
public abstract void mouseExited(MouseEvent evt)
83. What is an Action object?
An Action object is an action listener that provides not only action-event
handling, but also centralized handling of the state of action-event-firing components
such as tool bar buttons, menu items, common buttons, and text fields. The state that an
action can handle includes text, icon, mnemonic, enabled, and selected status.
84. Write about mouse events.
Mouse events notify when the user uses the mouse (or similar input device) to
interact with a component. Mouse events occur when the cursor enters or exits a
component's onscreen area and when the user presses or releases one of the mouse
buttons.
85. List the features of swing.
• Pluggable look - and - feels
• Lightweight components
• Do not depend on native peers to render themselves.
• Simplified graphics to paint on screen
• Similar behaviour across all platforms
• Portable look - and - feel
• Only a few top level containers not lightweight.
• New components - tress tables, sliders progress bars, frames, text components
• Tooltips - textual popup to give additional help
• arbitrary keyboard event binding
• Debugging support
86. What are models?
Most Swing components have models. A button (JButton), for example, has amodel(a ButtonModel object) that stores the button's state - what its keyboard mnemonic
is, whether it's enabled, selected, or pressed, and so on. Some components have multiple
models. A list (JList), for example, uses a ListModel to hold the list's contents, and a
ListSelectionModel to track the list's current selection.
87. What is a view?
8/18/2019 2 Marks IT51
19/28
A very important part of the text package is the View class. As the name suggests
it represents a view of the text model, or a piece of the text model. It is this class that is
responsible for the look of the text component. The view is not intended to be some
completely new thing that one must learn, but rather is much like a lightweight
component. In fact, the original View implementation was a lightweight component.
There were several reasons why the Component implementation was abandoned in favor
of an alternative.
88. What are the methods available for layouts?
• etMinimumS an• getPreferred Span
• getMaximumSpan
• getAlignment
• preferenceChanged
• setSize
89. What is a controller?
The controller is the initial contact point for handling all requests in the system.
The controller may delegate to a helper to complete authentication and authorization of a
user or to initiate contact retrieval.
90. How will you set the default button?
We set the default button by invoking the setDefaultButton() method on a top
level container's root pane. Here is the code that sets up the default button for the
ListDialog
Example:
getRootPane().setDefaultButton(setButton);
91. What are check boxes?
Check boxes are similar to radio buttons but their selection model is different, by
convention. Any number of cheek boxes in a group - none, some, or all - can be selected.
92. What are Layout managers?
A layout manager is an object that implements the Layout Manager interface and
determines the size and position of the components within a container. Although
components can provide size and alignment hints, a container's layout manager has the
final say on the size and position of the components within the container.
8/18/2019 2 Marks IT51
20/28
92. What is meant by Generic programming?
Generic programming is a programming method that provides common code to
many different types of objects. Generic programming induces the reusability of code as
it can be used for different types of objects.
93. What are the advantages of using parameterized approach?
• Whenever a value is retrieved, type casting is not necessary.
• No error checking mechanism is needed. So ClassCastExceptions are avoided.
Compiler will report a syntax error and will refuse to compile the program, if it
detects any attempt to add an object of the wrong type. Compiler throws errors at
compile time itself, not at run time.
94. What are type variables?
Type variables are identifiers used in generic programming to specify the type of
the elements. These are generally declared in Uppercase to keep them short. The
following are the type variable names used by the Java library.
Type variable name for
E The element type of a collection
K Key type of a table
V Value type of a table
T(U and S – neighboring letters) Any type
95. What is generic class?
Generic class is a special type of class that provides common code for different
types of objects by defining common type fields and methods. It contains one or more
type variables defined between < > and separated by commas.
96. How are the type variables bound?
Type variables are restricted by extending the bounding type. That is, by giving
the bounding type to the type variables, restriction can be placed on type variables, even
bounding type is the interface, extends keyword is used to inherit. Because it expresses
that T should be a subtype of the bounding type.
97. How does the virtual machine handle the generic code?
All objects including generic objects belong to ordinary classes in the virtual
8/18/2019 2 Marks IT51
21/28
machine. The virtual machine does not have objects of generic types. Whenever a
generic type is defined, a corresponding raw type automatically provided. The name of
the raw type is simply the name of the generic type, with the type parameters removed.
The type variables are erased and replaced by their bounding types (or Object for
variables without bounds). The raw type replaces type variables with the first bound, or
Object if no bounds are given.
98. How are Generic Methods translated in a virtual machine?
Type erasure is also done for generic methods as virtual machine does not
contain generic types. Consider the following generic method.
public static T min(T[] a)
This is declared as the family of methods. But after erasure, only one method will
be there.
public static Comparable min(Comparable[] a)
Here the type parameter T has been erased, leaving only its bounding type Comparable.
99. What are the Restrictions and Limitations to be followed on generics?
• Type Parameters cannot be instantiated with Primitive Types
• Runtime Type inquiry only works with Raw Types
• We cannot Throw or Catch Instances of a Generic Class
• Arrays of Parameterized Types are not legal
• Type Variables cannot be instantiated.
• Type Variables are not valid in static contexts of generic classes
• We shave to aware of clashes after erasure
100. Why are wild cards needed?
For rigid type of systems, generic types are quite unpleasant to use. To
overcome this problem, wildcards were introduced by Java designers. Instead of
supplying a specific type as the type argument for a generic type,? Can be specified as
argument, in which case we have specified the type argument as a wildcard. A
wildcard type represents any class or interface type.
101. What is the need of supertype Bounds to Wildcards?
A wildcard with a supertype bound gives the opposite behavior of the
wildcards. Wildcards with supertype bounds let us write to a generic object,
8/18/2019 2 Marks IT51
22/28
wildcards with subtype bounds let us read from generic objects.
102. What are unbounded wildcards?
Wildcards can be used without bounds also. These are known as unbound It is
useful for very simple operations
Example:
Pair
Pair methods look like this
?getFirst()
Void setFirst(?)
103. Write about cast() method.
Syntax: T cast(Object obj)
returns object if it is null or can be converted to the type T, or throws a
BadCastException otherwise.
104. What are determined by Reflections?
• The generic method has a type parameter called T
• The type parameter has a subtype bound that is itself a generic type
• The bounding type has a wildcard parameter
• The wildcard parameter has a supertype bound
• The generic method has a generic array parameter.
105. What are the steps are necessary to get the reliable system?
• Error should be notified to the user.
• All works should be saved.
• Users should be able to gracefully exit the program.
106. What are device errors?
Hardware of a system always does not work properly. In some situations it may
get trouble or may be turned off. For example our system is trying to print a page using a
printer which is disconnected from the computer.
107. What is the function of default handler?
Any exception that is not caught and handled by any handler provided by the
programmer is caught by the default handler provided by the java run-time system. The
default handler displays the description of the exception.
8/18/2019 2 Marks IT51
23/28
108. What is meant by exception handling?
The process of catching and handling the exceptions that are occurred at the run-
time of a program is known as Exception handling.
109. What are the functions of try and catch block?
• The program statements that are to be monitored are given inside the try block.
• Catch block catches the exception thrown by the try block.
110. Write a short note on finally blocks.
Any program code that absolutely must be executed before a method returns is
written in a finally block. This block is used to handle an exception that is not caught by
any catch statements. It can be defined immediately after try or catch statements. Inside
statement's execution is compulsory, even no error is thrown by the try block.
111. What is the use of throw statement?
Normally exceptions are thrown to the catch block by java run-time system. It is
also possible to throw it explicitly by the programmer in the code by using throw
statement
112. What is the purpose of throws statement?
throws statement is used to make the methods to guard themselves against the
exceptions.
This is done by including throws statement in the method’s declaration. Example
static void Method() throws IllegalAccessException
113. How is the exception classes created?
Exception classes are created by deriving Exception class or its sub types. It is
customary to give both a default constructor and a constructor that contains a detailed
message.
114. What are stack trace elements?
A stack trace is a list of all remaining method calls at a particular point in the
execution of a program. Stack frame is an individual element of a stack trace when an
exception occurs.
115. What are assertions?
Assertions are the conditions given by the programmer during program
8/18/2019 2 Marks IT51
24/28
development that should be true during the execution of the program. It is used for
defensive programming.
116. What is the purpose of logging in Java?
Normally, System.out.println() is inserted in the troublesome code to get the
behavior of the program the method. They are removed after the problem has been
overcome and inserted in the place to overcome the next problem. The logging API is
designed to overcome this problem.
117. Write a short note on advanced logging?
In a professional application, all records are logged into a single global logger.
Instead, separate and own records are defined. Logger objects are of type Logger class.
Logger myLogger=Logger.getLogger(“com.mycompany.myapp”);
Logger names are hierarchical. Logger parents and children share certain
properties. For example, if you set the log level on the logger "com.mycompany", then
the child loggers inherit that level.
118. List all the logging levels
• SEVERE
• WARNING
• INFO
• CONFIG
• FINE
• FINER
• FINEST
119. How can unexpected exceptions be logged?
Logging can be used to log unexpected exceptions. The following two
convenience methods include a description of the exception in the log record.
• void throwing(String className, String methodName, Throwable t)
• void log(Level l, String message, Throwable t)
120. What are threads?
Threads are light-weight processes within a process. A thread of execution results
from a fork of a computer program into two or more concurrently running tasks. Threads
are analogous to programs that have single flow of control.
8/18/2019 2 Marks IT51
25/28
121. What are the methods available to create threads?
Threads in Java are implemented in the form of objects and created using two
methods. They are,
By extending Thread class
By implementing Runnable interface
122. How will you block a thread?
A thread can be blocked temporarily by using the following methods.
• sleep()
• suspend()
• wait()
123. What is meant by multithreading and concurrency?
Multithreading is the process of creating and using multiple threads for different
control flowing in a single Java program. The ability of Java to support multiple threads
is referred as concurrency.
124. What are the advantages of multithreading?
• If a thread gets a lot of cache misses, the other thread(s) can continue, taking
advantage of the unused computing resources, which thus can lead to faster
overall execution, as these resources would have been idle if only a single
thread was executed.
• If a thread cannot use all the computing resources of the CPU (because
instructions depend on each other's result), running another thread permits to
not leave these idle.
• If several threads work on the same set of data, they can actually share their cache,
leading to better cache usage or synchronization on its values.
125. List the type of multithreading
• Block multi-threading
• Interleaved multi-threading
• Simultaneous multi-threading
126. What are the ways available to interrupt a thread?
• Interrupting a thread using shared variable
• Interrupting a thread withThread.interrupt()
8/18/2019 2 Marks IT51
26/28
127. List the states of a thread.
• New
• Runnable
• Not runnable (blocked or waiting)
• Dead (terminated)
128. What are threads considered to be blocked state?
• It’s sleep() method is invoked
• It’s wait() method is invoked
• it is blocked on input/output( i.e.) waiting on system resources to perform an
input or output operation
129. Mention the thread priorities.
Thread.MIN_ PRIORITY The maximum priority of any thread (an int value of 10)
Thread.MAX_ PRIORITY The minimum priority of any thread (an int value of 1)
Thread. NORM_ PRIORITY The normal priority of any thread (an int value of 5)
130. Write a short note on thread shedular.
In the implementation of threading scheduler usually applies one of the two
following strategies:
• Preemptive scheduling - If the new thread has a higher priority then current
running thread leaves the runnable state and higher priority thread enter to the
runnable state.
• Time-Sliced (Round-Robin) Scheduling - A running thread is allowed to be
execute for the fixed time, after completion the time, current thread indicates
to the another thread to enter it in the runnable state.
131. What is meant by lock in thread synchronization?Lock refers to the access granted to a particular thread that can access the shared
resources. At any given time, only one thread can hold the lock and thereby have access
to the shared resource. Every object in Java has build-in lock that only comes in action
when the object has synchronized method code.
132. What are two ways to synchronized the execution of code?
8/18/2019 2 Marks IT51
27/28
• Synchronized Methuds
• Synchronized Blocks (Statements)
133. What is the purpose of synchronized keyword in methods?
If any method is specified with the keyword synchronized then this method of an
object is only executed by one thread at a time.
134. What are synchronized blocks?
A synchronized statement is another way to create synchronized code.
Synchronized statements must specify the object that provides the intrinsic lock. The
synchronized block allows execution of arbitrary code to be synchronized on the lock of
an arbitrary object.
135. Write a short note on conditional thread safety.
The synchronized collections wrappers, synchronizedMap and synchronizedList,
are sometimes called conditionally thread-safe - all individual operations are thread
safe, but sequences of operations where the control flow depends on the results of
previous operations may be subject to data races
136. What are executor classes?
The Executor Class is a new feature available for developing multithreaded
applications A java.util.concurrent.Executor is an object that executes Runnable tasks. It
is similar to callingnew Thread (aRunnableObject).start ();
Example
Executor executor = some Executor factory method;
exector.execute (aRunnable);
137. What is the use of callable interface?
The new java.util.conCurrent.Callable interface is much like Runnable but
overcomes two drawbacks with Runnable. The run() method is Runnable cannot return a
result (i.e. it returns void) and cannot throw a checked exception. If we try to throw an
exception in a run() method, the javac compiler insists that you use a throws clause in
the method signature. However, the super class run() method doesn't throw an exception,
so javac will not accept this.
138. List the parts of synchronizers.
8/18/2019 2 Marks IT51
28/28
• State
• Access Condition
• State Changes
• Notification Strategy
• Test and Set Method
• Set Method
139. What are the three categories of notification strategies?
• Notify all waiting threads.
• Notify 1 random of N waiting threads.
• Notify 1 specific of N waiting thread.
140. What are the advantages of event driving programming?
• It always leads to convoluted conditional logic.
• Each branching point requires evaluation of a complex expression.
• Switching between different modes requires modifying many variables, which all
can easily lead to inconsistencies.