Vous êtes sur la page 1sur 12

TYBCS

Sem1 - Java

This Document contains all important one mark questions of Java

1. What is a java compilation unit?


A compilation unit is a java source file.
2. What are the differences between == and equals() ?
The == operator compares two objects to determine if they are the same object in memory i.e.
present in the same memory location. It is possible for two String objects to have the same value,
but located in different areas of memory. == compares references while equals compares contents.
The method public Boolean equals(Object obj) is provided by the Object class and can be
overridden. The default implementation returns true only if the object is compared with itself,
which is equivalent to the equality operator == being used to compare aliases to the object.
String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println("== comparison : " + (s1 == s5));
// == comparison : true
System.out.println("== comparison : " + (s1 == s2));
// == comparison : true
System.out.println("Using equals method : " + s1.equals(s2)); // Using equals method : true
System.out.println("== comparison : " + s3 == s4);
// == comparison : false
System.out.println("Using equals method : " + s3.equals(s4)); // Using equals method : true
3. Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it
has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the
class, so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an
array for string given during command line.
4. How to convert String to -umber in java program?
The valueOf() function of Integer class is is used to convert string to Number.
String numString = "1000";
int id=Integer.valueOf(numString).intValue();
5. What is JVM?
JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs
are running inside this JVM only. It converts java byte code to OS specific commands. In addition
to governing the execution of an application's byte codes, the virtual machine handles related
tasks such as managing the system's memory, providing security against malicious code, and
managing multiple threads of program execution.
6. What is a JVM heap?
The heap is the runtime data area from which memory for all class instances and arrays is
allocated. The heap may be of a fixed size or may be expanded. The heap is created on virtual
machine start-up.
7. How many JVM's we can run in a system?
Any number of JVMs can run in a system. Whenever we issue the command 'java' a new JVM
will start.
8. What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful
capabilities such as GUI components, event handling, I/O, file handling etc. The Java API is
grouped into libraries of related classes and interface
9. Why Java is not fully objective oriented?
Due to the use of primitives in java, which are not objects.
10. What if the main method is declared as private?
net2net

TYBCS

Sem1 - Java

The program compiles properly but at runtime it will give "Main method not public." message.
11. Can we compile a java program without main?
Yes, we can. In order to compile a java program, we don't require any main method. But to
execute a java program we must have a main in it (unless it is an applet or servlet) because main
is the starting point of a java program.
12. What is the use of bin and lib in JDK?
bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all
packages.
13. What is classpath?
Classpath is the path where Java looks for loading class at run time and compile time.
14. What is path?
It is the location where the OS will look for finding out the executable files and commands.
15. Can an application have multiple classes having main method?
Yes. While starting the application we mention the class name to be run. The JVM will look for
the main method only in the class whose name you have mentioned. Hence there is not conflict
amongst the multiple classes having main method.
16. Can we have multiple main methods in the same class?
We can have multiple overloaded main methods but there can be only one main method with the
following signature:
public static void main(String[] args) {}
Otherwise the program fails to compile. The compiler says that the main method is already
defined in the class.
17. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
18. What is the difference between public, private, protected and default access specifiers?
Access specifiers are keywords that determine the type of access to the member of a class. These
keywords are for allowing privileges to parts of a program such as functions and variables.
public : accessible to all classes
protected : accessible to the classes within the same package and any subclasses.
private : accessible only to the class to which they belong
default : accessible to the class to which they belong and to subclasses withinthe same package
19. What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects.
20. What are the different primitive data types in java?
There are 8 primitive types in java: boolean, char, byte, short, int long, float, double.
21. What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so
that integral and floating-point operations may take place. In the numerical promotion process the
byte, char, and short values are converted to int values. The int values are also converted to long
values, if necessary. The long and float values are converted to double values, as required.
22. How can one prove that the array is not null but empty?
print array.length. It will print 0. That means it is empty. But if it would have been null then it
would have thrown a NullPointerException on attempting to print array.length.
23. What are the restrictions placed on the values of each case of a switch statement?
At compile time, each case values of switch statement must evaluate to a an int value (not even
long).
24. What is the difference between a continue statement and a break statement?
break statement results in the immediate termination of the statement to which it applies (switch,
for, do, or while).
continue statement is used to end the current loop iteration and return control to the loop
statement.
25. What is the difference between a switch statement and an if statement?
if statement is used to select from two alternatives. It uses a boolean expression to decide which
alternative should be executed. The expression in if must be a boolean value. The switch

net2net

TYBCS

26.

27.

28.

29.

30.

31.

32.

33.

34.

35.

36.

37.
38.
39.

Sem1 - Java

statement is used to select from multiple alternatives. The case values must be promoted to an int
value.
What is casting?
Casting means converting one type to another. There are mainly two types of casting: Casting
between primitive types and casting between object references. Casting between primitive
numeric types is used to convert larger data types to smaller data types. Casting between object
references is used to refer to an object by a compatible class, interface, or array type reference.
What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any
transformation guidance to the compiler. This type of casting is not permitted in all kinds of
transformations and may not work for all scenarios.
int i = 1000;
long j = i; //Implicit casting
What is explicit casting?
Explicit casting is the process in which the complier are specifically informed to about
transforming the object.
long i = 700.20;
int j = (int) i; //Explicit casting
What are the restrictions placed on overriding a method?
The overridden methods have the exact signature of the super class method, including the return
type. The access specified cannot be less restrictive than the super class method. We cannot throw
any new exceptions in overridden method.
What is static initializer block? What is its use?
A static initializer block is a block of code that declares with the static keyword. It normally
contains the block of code that must execute at the time of class loading. The static initializer
block will execute only once at the time of loading the class only.
What is the difference between throw and throws clause?
throw is used to throw an exception manually, where as throws is used in the case of checked
exceptions, to tell the compiler that we haven't handled the exception, so that the exception will be
handled by the calling function.
What is a package?
A package is a collection of classes and interfaces that provides a high-level layer of access
protection and name space management.
What is the difference between this() and super()?
this() is used to invoke a constructor of the same class whereas super() is used to invoke a super
class constructor.
What is an interface?
Interface is similar to a class which may contain methods signature only but not bodies and
constant declarations. The methods must be defined by the class that implements it.
What are uses of interface?
a) Declaring methods that one or more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class relationship.
c) Determining an objects programming interface without revealing the actual body of the class.
What is difference between an abstract class and an interface?
1. An abstract class can have concrete method, which is not allowed in an interface.
2. Abstract class can have private or protected methods and variables and only public methods
and variables are allowed in interface.
3. We can implement more than one interface, but we can extend only one abstract class.
4. Interfaces provides loose coupling where as abstract class provides tight coupling.
What is an abstract method?
An abstract method is a method that doesnt have a body. It is declared with modifier abstract.
What is the difference between System.err and System.out?
We can redirect System.out to another file but we cannot redirect System.err stream
How can you force garbage collection in java?

net2net

TYBCS

40.

41.
42.
43.

44.

45.

46.

47.
48.
49.

50.

51.
52.

53.

54.

55.

56.

57.

Sem1 - Java

You cannot force Garbage Collection, but you can request for it by calling the method
System.gc(). But it doesn't mean that Garbage Collection will start immediately. The garbage
collection is a low priority thread of JVM.
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. It is also
possible for programs to create objects that are not subject to garbage collection. And there is no
guarantee that Garbage Collection thread will be executed.
How can you call a constructor from another constructor ?
By using this([...]) reference.
How can you call the constructor of super class?
By using super([...]) syntax.
What's the difference between normal methods and constructors?
Constructors must have the same name of the class and cannot have a return type. They are called
only once, while regular methods can be called whenever required. We cannot explicitly call a
constructor.
What is the use of packages in java?
Packages are a way to organize files in java when a project consists of more than one module. It
helps in resolving name conflicts when different modules have classes with the same names.
What is an abstract class?
An abstract class is a class designed with implementation gaps for subclasses to fill in and is
deliberately incomplete. It is declared with the modifier abstract. We cannot create objects of the
abstract class. It is used to specify a common behavioral protocol for all its child classes.
What is a marker interface?
An interface that contains no methods. eg: Serializable, Cloneable, SingleThreadModel etc. It is
used to just mark java classes that support certain capability.
What are tag interfaces?
Tag interface is an alternate name for marker interface.
What are the different inner classes types?
Member classes, Nested top-level classes, Local classes and Anonymous classes
What is constructor chaining?
When a constructor of a class is executed it will automatically call the default constructor of the
super class (if no explicit call to any of the super class constructor) till the root of the hierarchy.
What is garbage collection?
Garbage collection is the process of releasing memory used by unreferenced objects. It relieves
the programmer from the process of manually releasing the memory used by objects.
What is reflection?
Reflection is the process of finding out the different features of a class dynamically.
What is the disadvantage of garbage collection?
It adds an overhead that can affect performance. Additionally there is no guarantee that the object
will be garbage collected.
What is object cloning?
It is the process of duplicating an object so that two identical objects will exist in the memory at
the same time.
What is object pooling?
Creating a large number of identical short lived objects is called object pooling. This helps to
minimize the need of garbage collection and makes the memory use more effective.
What is final?
A final is a keyword in java. If final keyword is applied to a variable, then the variable will
become a constant. If it applied to method, sub classes cannot override the method. If final
keyword is applied to a class we cannot extend from that class.
What is finalize()?
Finalize is a protected method in java. When the garbage collector is executes, it will first call
finalize( ), and on the next garbage-collection it reclaim the objects memory. So finalize( ), gives
you the chance to perform some cleanup operation at the time of garbage collection.
What is -ested top-level class?

net2net

TYBCS

Sem1 - Java

A class declared within a class with static modifier is called nested top level class. Any class
outside the declaring class can access the nested top level class with the declaring class dot nested
top level class. Top-level inner classes have access to static variables only .
58. What is Member class?
A class declared inside a class without static modifier is called member class. Member classes are
just like any other member methods or member variables.
59. What is Local inner class?
Local inner classes are class declared inside a block of code. They are visible only within the
block of their declaration.
60. Can a top level class be private or protected?
No. A top level class cannot be private or protected. It can have either "public" or no modifier.
61. Can we declare an anonymous class as both extending a class and implementing an
interface?
No. An anonymous class can extend a class or implement an interface, but it cannot be declared to
do both
62. What is the use of assert keyword
assert keyword validates certain expressions. It replaces the if block effectively and throws an
AssertionError on failure. The assert keyword should be used only for critical arguments (means
without that the method does nothing).
63. What is AWT?
AWT stands for Abstract Window Toolkit. AWT enables programmers to develop Java
applications with GUI components, such as windows, and buttons. The Java Virtual Machine
(JVM) is responsible for translating the AWT calls into the appropriate calls to the host operating
system.
64. What is adapter class?
An adapter class provides a default implementation of all methods in an event listener interface.
Adapter classes are useful when you want to process only some of the events that are handled by a
particular event listener interface. You can define a new class by extending one of the adapter
classes and implementing only those events relevant to us.
65. What is the difference between exception and error?
The exception class defines mild error conditions that your program encounters. Exceptions can
occur when trying to open the file, which does not exist, the network connection is disrupted,
operands being manipulated are out of prescribed ranges, the class file you are interested in
loading is missing. The error class defines serious error conditions that you should not attempt to
recover from. In most cases it is advisable to let the program terminate when such an error is
encountered.
66. What are different types of exceptions in Java?
There are two types of exceptions in java: Checked exceptions and Unchecked exceptions.
Any exception that is is derived from Throwable and Exception is called checked exception
except RuntimeException and its sub classes. The compiler will check whether the exception is
caught or not at compile time. We need to catch the checked exception or declare in the throws
clause. Any exception that is derived from Error and RuntimeException is called unchecked
exception. We don't need to explicitly catch an unchecked exception.
67. Can we catch an error in our java program?
Yes. We can. We can catch anything that is derived from Throwable. Since Error is a sub class of
Throwable we can catch an error also.
68. What is the use of the finally block?
Finally is the block of code that executes always. The code in finally block will execute even if an
exception is occurred or not. finally will not execute when the user calls System.exit().
69. What is the difference between String and String Buffer?
a. String objects are constants and immutable whereas StringBuffer objects are not.
b. String class supports constant strings whereas StringBuffer class supports growable and
modifiable strings.
70. Which is the base class for all classes?
java.lang.Object.
net2net

TYBCS

Sem1 - Java

71. When does a compiler supplies a default constructor for a class?


If there is no other constructor exist in a class, the compiler will supply a default constructor.
72. What is JFC?
A JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java
class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building
graphics user interface (GUI) and graphics functionality for client applications that will run on
popular platforms such as Microsoft Windows, Linux, and Mac OSX.
73. What are the differences between Swing and AWT?
AWT
Swing
AWT is heavy-weight components
Swing is light-weight components
AWT is OS dependent because it uses native Swing components are OS independent.
components
Cannot change the look and feel in Swing
Can change the look and feel in Swing
Swing takes less more memory compared to Swing takes less memory compared to AWT
AWT
For drawing AWT uses screen rendering
Swing uses double buffering.
74. What are heavyweight components?
A heavyweight component is one that is associated with its own native screen resource
(commonly known as a peer).
75. What is lightweight component?
A lightweight component is one that "borrows" the screen resource of an ancestor (which means it
has no native resource of its own -- so it's "lighter").
76. What is an event?
Changing the state of an object is called an event.
77. What is an event handler?
An event handler is a part of a computer program created to tell the program how to act in
response to a specific event.
78. What is a layout manager?
A layout manager is an object that is used to organize components in a container i.e. responsible
for placement or lying of components within container.
79. Which containers use a BorderLayout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
80. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component
to display normally.
81. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
82. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
83. Which method of the Component class is used to set the position and size of a component?
void setBounds(int x, int y, int width, int height)
84. What is an applet?
Applet is a java program that runs inside a web browser.
85. What is the difference between applications and applets?
Application
Applet
Application must be run explicitly within Java Applet loads and runs itself automatically in a
Virtual Machine
java-enabled browser.
Application starts execution with its main Applet starts execution with its init method.
method
Application can run with or without graphical Applet must run within a graphical user
user interface
interface.
To run an application we dont need a java To run an applet we need a java enabled web
enabled web browser or an appletviewer.
browser or an appletviewer.
86. Which method is used by the applet to recognize the height and width?
Dimension getDimension().
net2net

TYBCS

Sem1 - Java

87. When we should go for codebase in applet?


If the applet class is not in the same directory, codebase is used.
88. What is the lifecycle of an applet?
init( ) method - called when an applet is first loaded
start( ) method - called each time an applet is started
paint( ) method - called when the applet is minimized or maximized
stop( ) method - called when the browser moves off the applet's page
destroy( ) method - called when the browser is finished with the applet
89. What is an event object and what are the models available for event handling?
An event object describes a state of change. In other words, event occurs when an action is
generated, like pressing a key on keyboard, clicking mouse, etc.
There different types of models for handling events are event-inheritance model and eventdelegation model
90. What are the advantages of the event-delegation model over the event inheritance model?
1. Event delegation model enables event handling by objects other than the ones that generate
the events. This allows a clean separation between a component's design and its use.
2. It performs much better in applications where many events are generated. This performance
improvement is due to event-delegation model does not have to be repeatedly process
unhandled events as is the case of the event inheritance.
91. What is source and listener?
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way.
A listener is an object that is notified when an event occurs. It has two major requirements. First,
it must have been registered with a source to receive notifications about specific event. Second, it
must implement necessary methods to receive and process these notifications.
92. What is a control and what are different types of controls in AWT?
A Control is a component that allows a user to interact with your application.
AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars and Text Components.
These controls are subclasses of Component.
93. What is the difference between choice and list?
A Choice is displayed in a compact form that requires you to pull it down to see the list of
available choices and only one item may be selected from a choice.
A List may be displayed in such a way that several list items are visible and it supports the
selection of one or more list items.
94. What is the difference between scrollbar and scrollpane?
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles
its own events and perform its own scrolling.
95. What are different types of layout managers available?
The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout ,
GridBagLayout, BoxLayout and SpringLayout
96. How are the elements of different layouts organized?
- The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
- The elements of a BorderLayout are organized at the borders (North, South, East and West)
and the center of a container.
- The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
- The elements of a GridLayout are of equal size and are laid out using the square of a grid.
- The elements of a GridBagLayout are organized according to a grid. However, the elements
are of different size and may occupy more than one row or column of the grid. In addition, the
rows and columns may have different sizes. It is the most flexible layout.
97. What are types of applets?
There are two different types of applets: Trusted Applets and Untrusted applets. Trusted Applets
are applets with predefined security and Untrusted Applets are applets without any security.
98. What are the restrictions imposed by a Security Manager on Applets?
1. A Applets cannot read or write files on the client machine that's executing it.
net2net

TYBCS

Sem1 - Java

2. They cannot load libraries or access native libraries.


3. They cannot make network connections except to the host that it came from.
4. They cannot start any program on the client machine.
5. They cannot read certain system properties.
99. What is the relationship between an event-listener interface and an event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for
a particular kind of event.
An event adapter provides a default implementation of an event-listener interface.
100.
How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and
adding itself as its own event listener.
101.
What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause
paint() to be invoked by the AWT painting thread.
102.
Which interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.
103.
What is Canvas?
A Canvas is a Component subclass which is used for drawing and painting. Canvas is a
rectangular area where the application can draw or trap input events.
104.
What is default Look-and-Feel of a Swing Component?
A Java Look-and-Feel
105.
What are the features of JFC?
A Pluggable Look-and-Feel, Accessibility API, Java 2D API, Drag and Drop Support
106.
What does x mean in javax.swing?
Extension of java.
107.
What is the default layout for a ContentPane in JFC?
BorderLayout.
108.
What is the difference between a Canvas and a Scroll Pane?
A Canvas is a component. ScrollPane is a container. Canvas is a rectangular area where the
application can draw or trap input events. ScrollPane implements horizontal and vertical scrolling.
109.
What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be
checked or unchecked.
110.
Which is the super class of all event classes?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
111.
How the Canvas class and the Graphics class are related?
A Canvas object provides access to a Graphics object via its paint() method.
112.
What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
A window can be modal.
113.
How will you define an interface?
An interface is defined with the keyword interface.
public interface MyInterface {...}
114.
How will you define an abstract class?
An abstract class is defined with the keyword abstract.
public abstract class MyClass { }
115.
What are the methods in Object?
clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
116.
What do you mean by immutable ? How to create an immutable object?
Immutability means an object cannot be modified after it has been initialized. There will not be
any setter methods in an immutable class. And normally these classes will be final.
117.
What is a stream and what are the types of Streams?
A Stream is an abstraction that either produces or consumes information.
There are two types of Streams
i. Byte Streams: Provide a convenient means for handling input and output of bytes.
net2net

TYBCS

Sem1 - Java

ii.Character Streams: Provide a convenient means for handling input & output of characters.
118.
Enlist main classes of Streams?
Byte Stream classes: Two main abstract classes: InputStream and OutputStream.
Character Stream classes: Two main abstract classes: Reader and Writer.
119.
What is the difference between Reader/Writer and InputStream/OutputStream?
The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byteoriented.
120.
What is filtered I/O?
An I/O filter is an object that reads from one stream and writes to another, usually altering the
data in some way as it is passed from one stream to another.
121.
What is the difference between readers and streams?
Readers are character oriented where streams are byte oriented. The readers are having full
support for Unicode data.
122.
What is the difference between RandomAccessFile and File?
The File class contains information of the files and directories of the local file system.
The RandomAccessFile class contains the methods needed to directly access data contained in
any part of a file.
123.
What is a native method?
A native method is a method that is implemented in a language other than Java.
124.
Is sizeof a keyword in java?
The sizeof operator is not a keyword.
125.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded
method in the out object.
126.
What are different forms of polymorphism in Java?
a. Method overloading
b. Method overriding through inheritance
c. Method overriding through the Java interface
127.
What if I write static public void instead of public static void?
Program compiles and runs properly.
128.
What is difference between String and StringTokenizer?
StringTokenizer as its name suggests tokenizes a String supplied to it as an argument to its
constructor and the character based on which tokens of that string are to be made. The default
tokenizing character is space " ".
StringTokenizer st = new StringTokenizer("Hello World");
while (st.hasMoreTokens())
System.out.println(st.nextToken());
Output:
Hello
World
129.
What if the static modifier is removed from the signature of the main method or What if
I do not provide the String array as the argument to the method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
130.
What modifiers may be used with top-level class?
public, abstract and final can be used for top-level class.
131.
Can you have an inner class inside a method and what variables can you access?
Yes, we can have an inner class inside a method and final variables can be accessed.
132.
What is the difference between Integer and int?
a) Integer is a class defined in the java. lang package, whereas int is a primitive data type
defined in the Java language itself. Java does not automatically convert from one to the other.
b) Integer can be used as an argument for a method that requires an object, whereas int can be
used for calculations.
133.
How can we call a method or variable of the super class from child class?
We can use super.method() or super.variable syntax for this purpose.
134.
How can you create your own exception?
net2net

TYBCS

Sem1 - Java

Our class must extend either Exception or its sub class


135.
If a class doesn't have any constructors, what will happen?
If a class doesn't have a constructor, the JVM will provide a default constructor for the class.
136.
What are the differences between boolean & operator && operator
When an expression containing the & operator is evaluated, both operands are evaluated. And the
& operator is applied to the operand. When an expression containing && operator is evaluated,
the first operand is evaluated. If the first operand returns a value of true then only the second
operand is evaluated otherwise the second part will not get executed.&& is also called short cut
and.
137.
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e.
casting down the hierarchy
138.
Can we call finalize() method ?
Yes. Nobody will stop us to call any method, if it is accessible in our class. But a garbage
collector cannot call an object's finalize method if that object is reachable.
139.
When is static variable loaded? Is it at compile time or runtime? When exactly a static
block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an
object has to be created. Static variables will be allocated memory space when they have been
loaded. The code in a static block is loaded/executed only once i.e. when the class is first
initialized. A class can have any number of static blocks. Static block is not member of a class,
they do not have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.
140.
What must a class do to implement an interface?
It must identify the interface in its implements clause. Also it must provide definition for all the
methods in the interface otherwise it must be declared abstract.
141.
What is an Object and how do you allocate memory to it?
Object is an instance of a class and it is a software unit that combines a structured set of data with
a set of operations for inspecting and manipulating that data. When an object is created using new
operator, memory is allocated to it.
142.
What is dynamic typing?
Dynamic typing means type errors are detected at run time by checking the actual data types of
the values against the required data types.
143.
What is static typing?
Static typing means type errors are detected at compile time by checking the inferred data type is
a subtype of the required type.
144.
If aaaa is an array then why aaaa.length why not aaaa.length()?
Because length is a property not a method.
145.
Does the code in finally block get executed if there is an exception and a return
statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still
executed. The finally block will not be executed when the System.exit(1) statement is executed
earlier or the system shut down earlier or the memory is used up earlier before the thread goes to
finally block.
146.
What must be the order of catch blocks when catching more than one exception?
The sub classes must come first. Otherwise it will give a compile time error.
147.
How many times may an object's finalize() method be invoked by the garbage collector?
Only once
148.
What is static?
static means one per class. static variables are created when the class loads. They are associated
with the class. In order to access a static we don't need objects. We can directly access static
methods and variable by calling classname.variablename.
149.
What is class loader in java?
A class loader is a class that is responsible for loading the class. All JVM contains one class
loader called primordial class loader.
net2net

10

TYBCS

Sem1 - Java

150.
What type of parameter passing does Java support?
In Java the arguments primitives are always passed by value whereas object references are passed
by reference so both the original reference and parameter copy both refer to the same object.
151.
What is Garbage Collection and how to call it explicitly?
When an object is no longer referred to by any variable, java automatically reclaims memory used
by that object. This is known as garbage collection. System.gc() method may be used to call it
explicitly.
152.
What is the difference between static and non static variables?
A static variable is associated with the class as a whole rather than with specific instances of a
class. There will be only one value for static variable for all instances of that class. Non-static
variables take on unique values with each object instance.
153.
What are the restrictions placed on static method?
We cannot override static methods. We cannot access any object variables inside static method.
Also the this reference also not available in static methods.
154.
What is diamond problem?
The diamond problem is an ambiguity that can occur when a class multiply inherits from two
classes that both descend from a common super class
155.
Why java does not support multiple inheritance?
Because the multiple inheritance causes the redundancy. Also we cannot solve diamond problem.
156.
What is the first argument of the String array in main method?
If we do not provide any arguments on the command line, then the String array of main method
will be empty but not null. This is unlike C/C++ where the first element by default is the program
name.
157.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
158.
Why we cannot override static methods?
Static means they are associated with a class. In static methods, the binding mechanism is static
binding. So it must be available at the compile time.
159.
What is a weak reference?
A weak reference is the one that does not prevent the referenced object from being garbage
collected. The weak reference will not keep the object that it refers to alive. A weak reference is
not counted as a reference in garbage collection. This will make the memory use more effective.
160.
Strings are immutable. But String s="Hello"; String s1=s+"World" returns HelloWorld
how?
Here actually a new object is created with the value of HelloWorld
161.
Why Java is not 100% pure object oriented language?
Because java uses primitives.
162.
What is JIT?
JIT (just in time) compiler, which compiles each method to native code upon first execution, then
executes the native code. Thereafter, whenever the method is called, the native code is executed.
163.
What is a cloneable interface and how many methods does it contain?
It is not having any method because it is a TAGGED or MARKER interface. It indicates that the
class which implements Cloneable interface is having ability to get cloned.
164.
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and
dynamically manipulate at run time. This is supported using Reflection API with built-in classes
like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the
class name, by using the getName method.
165.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the
OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to
those objects are on the STACK.
166.
What is the difference between static and non-static?
A static variable is associated with the class as a whole rather than with specific instances of a
class. Each object will share a common copy of the static variables i.e. there is only one copy per
net2net

11

TYBCS

Sem1 - Java

class, no matter how many objects are created from it. Class variables or static variables are
declared with the static keyword in a class. These are declared outside a class and stored in static
memory. Class variables are mostly used for constants. Static variables are always called by the
class name. This variable is created when the program starts and gets destroyed when the
programs stops. The scope of the class variable is same an instance variable. Its initial value is
same as instance variable and gets a default value when its not initialized corresponding to the
data type. Similarly, a static method is a method that belongs to the class rather than any object of
the class and doesn't apply to an object or even require that any objects of the class have been
instantiated. Static methods are implicitly final, because overriding is done based on the type of
the object, and static methods are attached to a class, not an object. A static method in a
superclass can be shadowed by another static method in a subclass, as long as the original method
was not declared final. However, you can't override a static method with a non-static method. In
other words, you can't change a static method into an instance method in a subclass. Non-static
variables take on unique values with each object instance.
167.
What is a classloader?
A class loader is an object that is responsible for loading classes.
168.
What is composition?
Holding the reference of the other class within some other class is known as composition.
169.
What is aggregation?
It is a special type of composition. If you expose all the methods of a composite class and route
the method call to the composite method through its reference, then it is called aggregation
170.
What is anonymous class?
An anonymous class is a type of inner class that don't have any name.
171.
How does a try statement determine which catch clause should be used to handle an
exception?
When an exception is thrown, the catch block of the try statements are examined in the order in
which they appear. The first catch block that is capable of handling the exception is executed. The
remaining catch blocks are ignored
172.
What is the security mechnaism used in java?
Java uses sand box security model.
173.
What is sandbox?
A sandbox is a security mechanism for safely running programs. The sandbox typically provides a
tightly-controlled set of resources for guest programs to run in, such as scratch space on disk and
memory.

net2net

12

Vous aimerez peut-être aussi