Académique Documents
Professionnel Documents
Culture Documents
Sem1 - Java
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
TYBCS
Sem1 - Java
TYBCS
Sem1 - Java
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
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