How do you play audio clips without using applet class? (Applets) Discuss in Detail (QID: 672)
Answer You can do this using Java Media Framework. I dont have much context on this API.
Question If you need to display a String on the applet, what would you do? (Applets) Discuss in Detail (QID: 641)
Answer drawString() is used to output a String to an applet. This method is included in the paint() of the Applet
Question What are the methods to retrive information about an applet? (Applets) Discuss in Detail (QID: 640)
Answer getAppletInfo() : Returns a string describing the applet, its author, copyright information, etc.
getParameterInfo( ) method: Returns an array of string describing the applet?s parameters
Question What tags are mandatory when creating HTML to display an applet? (Applets) Discuss in Detail (QID: 639)
Answer code, height, width
Question What is AppletStub Interface? (Applets) Discuss in Detail (QID: 638)
Answer The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface
Question Which classes and interfaces does Applet class consist? (Applets) Discuss in Detail (QID: 637)
Answer Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub, and AudioClip
Question How do I determine the width and height of my application? (Applets) Discuss in Detail (QID: 636)
Answer Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of
the applet as a Dimension object, from which you extract separate width, height fields. The following code snippet explains this:
Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
Question How do I go from my applet to another JSP or HTML page? (Applets) Discuss in Detail (QID: 635)
Answer Use AppletContext and invoke showDocument() on that context object. Below is sample code
URL targetURL;
String URLString = "http://localhost:8080/mypage.jsp";
AppletContext context = getAppletContext();
try
{
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
context.showDocument(targetURL);
Question How can I arrange for different applets on a web page to communicate with each other? (Applets) Discuss in Detail (QID: 634)
Answer Name your applets inside the Applet tag and invoke AppletContext?s getApplet() method in your applet code to obtain references to the other applets
on the page
Question When an user wants to send an int from HTML what does he needs to do? (Applets) Discuss in Detail (QID: 633)
Answer Either the user wants to send an int or a String, it will be the same. Here are steps he might do to get an int
[html]
[applet code="Launch.class" archive="bak.jar" width=740 height=460]
[param name="mynum" value="098765"]
[/applet]
[/html]
And within the init() of your applet, Use the following line to get the value.
String mynum = getParameter("mynum");
int x = Integer.parseInt(mynum);
Question How do we pass a parameter from HTML page to Applet? (Applets) Discuss in Detail (QID: 632)
Answer [html]
[applet code="Launch.class" archive="bak.jar" width=740 height=460]
[param name="lang" value="English"]
[/applet]
[/html]
And within the init() of your applet, Use the following line to get the value.
String langs = getParameter("lang");
Question How are the differences between Applets and Applications? (Applets) Discuss in Detail (QID: 631)
Answer Application:
-Applications are Stand Alone and the doesn?t need web-browser.
-Execution starts with main().
-May or may not be a GUI.
Applets
-Needs no explicit installation on local machine. Can be transferred through Internet on to the local machine and may run as part of web-browser.
-Execution starts with init() method. Must run within a GUI (Using AWT / Swing)
Question What is the sequence for calling the methods by AWT for applets? (Applets) Discuss in Detail (QID: 630)
Answer When an applet begins, the AWT calls the following methods, in this sequence:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes place
stop()
destroy()
Question What are the Applet's Life Cycle methods? Explain them? (Applets) Discuss in Detail (QID: 629)
Answer Following are methods in the life cycle of an Applet:
init() method - called when an applet is first loaded. This method is called only once in the entire cycle of an applet. This method usually intialize
the variables to be used in the applet
start() method - called each time an applet is started
paint() method - called when the applet is minimized or refreshed. This method is used for drawing different strings, figures, and images on the applet
window
stop() method - called when the browser moves off the applet?s page
destroy() method - called when the browser is finished with the applet
Question What is the difference between an Applet and an Application? (Applets) Discuss in Detail (QID: 548)
Answer The differences between an applet and an application are as follows:
1. Applets can be embedded in HTML pages and downloaded over the Internet whereas
Applications have no special support in HTML for embedding or downloading.
2. Applets can only be executed inside a java compatible container, such as a browser
or appletviewer whereas Applications are executed at command line by java.exe or jview.exe.
3. Applets execute under strict security limitations that disallow certain operations
(sandbox model security) whereas Applications have no inherent security restrictions.
4. Applets don't have the main() method as in applications. Instead they operate on an
entirely different mechanism where they are initialized by init(),started by start(),stopped
by stop() or destroyed by destroy().
Question What are the problems faced by Java programmers who dont use layout managers? (AWT) Discuss in Detail (QID: 232)
Answer Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system
Question Which Component subclass is used for drawing and painting? (AWT) Discuss in Detail (QID: 231)
Answer Canvas
Question What is a layout manager? (AWT) Discuss in Detail (QID: 230)
Answer A layout manager is an object that is used to organize components in a container
Question What interface is extended by AWT event listeners? (AWT) Discuss in Detail (QID: 229)
Answer All AWT event listeners extend the java.util.EventListener interface.
Question What is the difference between a Choice and a List? (AWT) Discuss in Detail (QID: 228)
Answer A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items
Question How can the Checkbox class be used to create a radio button? (AWT) Discuss in Detail (QID: 227)
Answer By associating Checkbox objects with a CheckboxGroup
Question What is the difference between the paint() and repaint() methods? (AWT) Discuss in Detail (QID: 226)
Answer 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.
Question What advantage do Java's layout managers provide over traditional windowing systems? (AWT) Discuss in Detail (QID: 225)
Answer Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
Question How are the elements of a GridBagLayout organized? (AWT) Discuss in Detail (QID: 224)
Answer The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
Question How can a GUI component handle its own events? (AWT) Discuss in Detail (QID: 223)
Answer A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
Question What is the relationship between an event-listener interface and an event-adapter class? (AWT) Discuss in Detail (QID: 222)
Answer 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.
Question What is the relationship between clipping and repainting? (AWT) Discuss in Detail (QID: 221)
Answer When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
Question How are the elements of a CardLayout organized? (AWT) Discuss in Detail (QID: 220)
Answer The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
Question What is the difference between the Font and FontMetrics classes? (AWT) Discuss in Detail (QID: 219)
Answer The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
Question What is the difference between a Window and a Frame? (AWT) Discuss in Detail (QID: 218)
Answer The Frame class extends Window to define a main application window that can have a menu bar.
Question How are the elements of a BorderLayout organized? (AWT) Discuss in Detail (QID: 217)
Answer The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
Question What is the relationship between the Canvas class and the Graphics class? (AWT) Discuss in Detail (QID: 216)
Answer A Canvas object provides access to a Graphics object via its paint() method.
Question Which containers may have a MenuBar? (AWT) Discuss in Detail (QID: 215)
Answer Frame
Question Which class is the immediate superclass of the MenuComponent class (AWT) Discuss in Detail (QID: 214)
Answer Object
Question In which package are most of the AWT events that support the event-delegation model defined? (AWT) Discuss in Detail (QID: 213)
Answer Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.
Question What class is the top of the AWT event hierarchy? (AWT) Discuss in Detail (QID: 212)
Answer The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy
Question What is the difference between a MenuItem and a CheckboxMenuItem? (AWT) Discuss in Detail (QID: 211)
Answer The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked
Question What is clipping? (AWT) Discuss in Detail (QID: 210)
Answer Clipping is the process of confining paint operations to a limited area or shape
Question What is the immediate superclass of the Dialog class? (AWT) Discuss in Detail (QID: 209)
Answer Window
Question Name three Component subclasses that support painting (AWT) Discuss in Detail (QID: 208)
Answer The Canvas, Frame, Panel, and Applet classes support painting
Question What is the immediate superclass of the Applet class? (AWT) Discuss in Detail (QID: 207)
Answer Panel
Question Which containers use a FlowLayout as their default layout? (AWT) Discuss in Detail (QID: 206)
Answer The Panel and Applet classes use the FlowLayout as their default layout
Question What is the preferred size of a component? (AWT) Discuss in Detail (QID: 205)
Answer The preferred size of a component is the minimum component size that will allow the component to display normally
Question which containers use a border Layout as their default layout? (AWT) Discuss in Detail (QID: 204)
Answer The window, Frame and Dialog classes use a border layout as their default layout
Question Why variables/objects in java bean classes are declared as private? Question by Rajesh (Beans) Discuss in Detail (QID: 692)
Answer Since you do not want users to access these objects directly and wanted users to get access to these objects
using getter and setter methods.
Question Can we write abstract methods in a final class and vice versa? (CoreJava) Discuss in Detail (QID: 919)
Answer A class can be declared as either abstract or final and not both. abstract methods are not allowed in final class.
If a class has abstract method then the class needs to be declared as abstract and not final.
An abstract class can have final methods in it.
Question How to increase stack size in Java? (CoreJava) Discuss in Detail (QID: 918)
Answer The following commands can be used to increase stack size
-Xss Stacksize to increase the native stack size
-Xoss Stacksize to increase the Java stack size
Where Stacksize is expressed as an integer followed by "k" or "m" for kbytes or mbytes.
E.g.
$java -Xss156k MyTest - for native
$java -Xoss600k MyTest - for Java
The default native stack size is 128k, with a minimum value of 1000 bytes.
The default java stack size is 400k, with a minimum value of 1000 bytes.
Question What is the difference between local variable and temporary variable? Can you give example? (CoreJava) Discuss in Detail (QID: 917)
Answer There is nothing like temp variable concept in Java. You can call any
variable or object as temp if you feel that it would be used just for
temporary purpose.
public void myMethod() {
Map tempMap = new HashMap();
Map myMap = new HashMap();
}
In the above code both the Map objects are local to the method but one
of them is named as tempMap but it doesn't mean it looses any
functionality or gains any functionality. Its the same as other
objects that are defined in the Method or class.
Question Why all classes in Java extend Object class implicitly? (CoreJava) Discuss in Detail (QID: 916)
Answer Before we actually answer this question, lets ask a question to ourself, why should a class
extend another class? - Dont you think this is done to inherit the methods defined in
super class be used in sub class?
In the same way every class that is defined by the user has access to methods defined in
Object class.
A few advantages of doing this
A. Object class has a special privilages set in JVM (Any one who is an expert in JVM can comment on this)
B. All the methods defined in Object class have some functionality that is common if extended
by any class. User is given permission to override these defaults with the logic he/she intends with.
For e.g.
public class A {
public boolean equals(Object obj) {
//perform user logic here
}
}
C. Initiation of garbage collection happens through Object class
Any one has more points to add. Please feel free to add them.
Question What do you mean by Legacy class? (CoreJava) Discuss in Detail (QID: 912)
Answer Legacy classes are those that were built using Java 1.1 or Java 1.2 API. In general we cannot use this term for
java classes. Say for example when Java 1.0 was available Vector was used instead of dynamic array and since
there was no ArrayList class people were forced to use Vector for this purpose.
When Java 1.2 was released ArrayList was much more advanced to Vector but has all the features of Vector too.
So people started using ArrayList instead of Vector (this again depends on the project requirement, both Vector
and ArrayList have their own advantages). And in this case Vector became legacy class
But this is not constant since in future Sun may introduce a new class that is much more advanced to ArrayList and
Vector. And then we call both ArrayList and Vector as legacy classes.
But in general a "legacy" is a term used to define a software created using older version of software.
Question What is PermGen space? (CoreJava) Discuss in Detail (QID: 909)
Answer The memory in the Virtual Machine is divided into a number of regions. One of these regions is PermGen. It's an area
of memory that is used to (among other things) load class files. The size of this memory region is fixed, i.e. it
does not change when the VM is running. You can specify the size of this region with a commandline switch: -XX:MaxPermSize .
The default is 64 Mb on the Sun VMs.
If there's a problem with garbage collecting classes and if you keep loading new classes, the VM will run out of space
in that memory region, even if there's plenty of memory available on the heap. Setting the -Xmx parameter will not help:
this parameter only specifies the size of the total heap and does not affect the size of the PermGen region.
Question Why can't I declare a static method in an interface? (CoreJava) Discuss in Detail (QID: 902)
Answer Because all methods declared in an interface are (implicitly) also "abstract" methods, by definition, they do not define the (implementation of) the method.
This would cause problems with multiple inheritance.
Lets have a look at an example, If object C implemented interfaces A and B,
and both A and B defined a static method F(), then some method invoked C.F(), then which F() would get invoked?
The one from A() or the one from B()? We don't know which, and can't know, so Java doesn't let us complicate matters thus.
Question Why does array index always begin from zero? (CoreJava) Discuss in Detail (QID: 900)
Answer Any one wants to answer this question?
Question What is marker interface and What is the use of marker interface? (CoreJava) Discuss in Detail (QID: 899)
Answer An interface without any methods is known as marker interface. Examples of marker interfaces are
1. Serializable
2. EventListener
3. Remote
4. Cloneable
Assume a class X implements Cloneable interface. Now you can call X.clone() inorder to clone this object. If this
class doesn't implement this interface then you will not be able to clone this class.
The same is for Serializable interface, a class that implements this interface will be serialized and
de-serialized.
Classes that require special handling during the serialization and deserialization process must implement
special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
Question What is the difference between inheritance and aggregation? When would you use one over the other? (CoreJava) Discuss in Detail (QID: 898)
Answer Anyone wants to answer this question?
Question What is the difference between ArrayList and LinkedList? (CoreJava) Discuss in Detail (QID: 897)
Answer The difference between ArrayList and LinkedList vary in the way both these objects implement List interface.
ArrayList used arrays to store its elements and LinkedList used node objects to store its elements.
ArrayList is faster than LinkedList. Assume a scenario where in both ArrayList and LinkedList have 5 objects and you are trying to
remove 2nd object from these objects, since ArrayList uses arrays its much faster to find the object, delete it and re-arrange the
order in the object. But in LinkedList each object will be linked to its previous and next object, removing the object at an index
will be slower as the object needs to re-arrange the object by linking to previous and next object in the list (if any)
Question In case of inner class methods the scope of variable is only for local,but if we make it final then it can be accessed on outside method,why it is so (CoreJava) Discuss in Detail (QID: 698)
Answer Can someone answer this question?
Question How do you uniquely identify one instance of a class among 10 instances of the same class? (CoreJava) Discuss in Detail (QID: 689)
Answer One way would be to check an objects hashCode.
Question Since Object class is the super class of every class in java and suppose if I write class x extends y and this class x also extending Object,
Is this multiple Inheritance ? (CoreJava) Discuss in Detail (QID: 687)
Answer When you write "public class x" which doesn't extend any other class by default x is extending Object.
When you write "public class x extends y" x is extending y and y is extending Object class
Your class can extend only one class.
Question Why java is called as PLATFORM independent? (CoreJava) Discuss in Detail (QID: 684)
Answer Java applications consist of byte-code which may be interpreted by a virtual engine. Thus, the
applications are able to run on any hardware for which a virtual engine exists. Interpretation by a
virtual engine means a lower processing speed, compared to compiled software. To counter this
disadvantage, improvements have been developed, like just-in-time compilation (JIT), which
translates program instructions of the virtual engine into instructions for the physical machine.
The result in this case is an aligned program in memory, which can be executed rapidly without
interpretation. Aditional analysis of the runtime behavior with Hotspot-technology results in
additional improvements.
Question Why does main() in java taking String[] as argument? (CoreJava) Discuss in Detail (QID: 683)
Answer Since main(String[]) is the starting point for an application if you need to pass any arguments to
application at the startup time, we can send the parameters as Strings
Question What is meant by Virtual function in Java? Does Java supports Virtual function?
Question by Joji Mathew (CoreJava) Discuss in Detail (QID: 679)
Answer Java supports Virtual functions, all functions in Java are virtual by default. Virtual functions or virtual methods are functions or methods that will be redefined in derived classes.
Pure Virtual functions from C++ could be abstract functions without body.
Make your class abstract, define the pure virtual methods you want subclasseses to provide implementation for
(using the abstract keyword in their definition) and you should be good.
public abstract class MyClass {
public void concreteInitThing() {
// your code here
}
public abstract void specificImplementation(); //Virtual method
}
public class ConcreteImplementationOfMyClass extends MyClass {
public void specificImplementation() {
// Your code here
}
}
Question What is the difference between local inner class and non-local inner class? (CoreJava) Discuss in Detail (QID: 677)
Answer Local inner classes may only access the local variables or method parameters of the code block in which
they are defined. Local inner classes may only access final variables which have been assigned a value.
A non-local inner class has access to all variables declared within the encapsulating class
Question What are dynamic class loaders? (CoreJava) Discuss in Detail (QID: 674)
Answer This is a mechanism of loading classes at runtime. They have following characteristics,
a. lazyloading - load classes only when they are required. This helps in memory management.
b. type safety linkate - Dynamic loading of a class should not require additional run-time checks in order to
guarantee type safety. Adds link-time checks by replacing run-time checks. They are performed only once.
c. User defined class loaders - Programmers have the control to load classes in their applications. A user can
define a class loader to load classes from remote location.
d. Multiple namespaces - Class loaders provide separate namespaces for different software components. For
example an applet running in a browser loads classes from different jar files. Assume that the classes loaded
from different jar files have same name but they are treated as distinct types by JVM
E.g.
Class cla = Class.forName( "com.javagalaxy.util.MyClass" );
MyClass tCla = (MyClass)cla.newInstance( );
tCla.doSomething();
Question What is the difference between break, continue and return statements? (CoreJava) Discuss in Detail (QID: 673)
Answer
break: breaks the current loop and moves the cursor to next line after the loop
e.g.
for(int i=0; i <>
{
System.out.println("i"+i);
if(i == 5) break;
}
continue: Use continue when you have to skip few lines of code in a loop when a condition is satisfied
e.g.
for(int i=0; i <>
{
System.out.println("i:"+i);
if(i == 5) continue;
System.out.println("ii:"+i);
}
return: When a condition is satisfied you may want to return from the method itself.
e.g.
public int getValue() {
int retValue = 0;
for(int i=0; i <>
{
retValue = i;
System.out.println("i:"+i);
if(i == 5) return retValue;
System.out.println("ii:"+i);
}
return retValue;
}
Question Question by Madhavi
Last week when I attended an interview, they asked me to write a program in java to get in output as follows.
1
1 2
1 2 3
1 2 3 4.
Second question was to write the program in java to get in output as follows.
1
2 3
4 5 6
7 8 9 10
Can you provide a solution please? (CoreJava) Discuss in Detail (QID: 668)
Answer Below is the a sample programme that gives you this output.
public class A
{
public static void main(String args[]) throws Exception
{
/**
* outputs the following format
* 1
* 2 3
* 3 4 5
* 4 5 6 7
*/
for (int i = 1; i <= 4; i++) {
for (int j = 0; j <>
System.out.print(i + j +" ");
}
System.out.println("");
}
System.out.println("*****************");
/**
* outputs the following format
* 1
* 1 2
* 1 2 3
* 1 2 3 4
*/
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j +" ");
}
System.out.println("");
}
System.out.println("*****************");
/**
* outputs the following format
* 1
* 2 3
* 4 5 6
* 7 8 9 10
*/
int k=1;
int y = 1;
for (int i = 1; i <= 4; i++) {
for (int j = 0; j <>
System.out.print(y++ +" ");
}
k++;
System.out.println("");
}
}
}
Question Why Java is not complete Object Oriented Programming language? (CoreJava) Discuss in Detail (QID: 662)
Answer I am not sure what the interviewer has in his mind, but I can think of only one reason,
"Java doesn't support multiple inheritance".
Do you guys have anthing to add?
Question What is meant by upcasting? (CoreJava) Discuss in Detail (QID: 661)
Answer Upcasting is where a derived object reference is cast to one of its base objects reference.
class Base
{
public void show()
{
System.out.println("In Base class");
}
}
class Derived extends Base
{
public void show()
{
System.out.println("In Derived class");
}
public static void main(String args[])
{
//upcasting
Base base = new Derived();
base.show();
}
}
When an object is upcast it becomes a base object for the purpose of the cast, therefore any new fields and methods
declared in the derived class are not accessible.
Question What is the differences between inheritance and composition? (CoreJava) Discuss in Detail (QID: 660)
Answer Inheritance:
Inheritance is the ability to derive one class from another; the derived class (also called the subclass) inherits all
of the methods and data members of its superclass.
class Fruit {
//...
}
class Apple extends Fruit {
//...
}
In the above example, class Apple is related to class Fruit by inheritance, because Apple extends Fruit. In this
example Fruit is superclass and Apple is subclass.
Composition:
Composition (called "has-a") is a relationship between classes where one class has a data member that is an instance of
the other class.
class Fruit {
//...
}
class Apple {
private Fruit fruit = new Fruit();
//...
}
In the example above, class Apple is related to class Fruit by composition, because Apple has an instance variable that
holds a reference to Fruit object.
In this example, Apple is what I will call front-end class and Fruit is what I will call back-end class.
In a composition relationship, the front-end class holds a reference in one of its instance variables to a back-end class.
Question In a scenario, where you have to write an application which navigates between different pre-defined states of the
application, what should I be using, an Abstract class or an Interface? (CoreJava) Discuss in Detail (QID: 659)
Answer I would suggest Abstract class as your application is navigating through pre-defined states of the application.
Anyone with better ideas?
Question Can an interface have variables defined in it? How do you use them? (CoreJava) Discuss in Detail (QID: 658)
Answer Yes we can have variables defined in an Interface. Have a look at the class below to
know how to use those variables
public interface MyInterface
{
String STR1 = "STR1";
String STR2 = "STR2";
}
public class MyTestClass implements MyInterface
{
public static void main(String args[])
{
System.out.println(STR1);
}
}
Question Does java support global variables? (CoreJava) Discuss in Detail (QID: 657)
Answer Though java doesn't support global variables, you can achieve this by creating variables public and static.
Example
public class Global {
public static int x = 37;
public static String s = "test";
}
Such members can be accessed by saying:
public class test {
public static void main(String args[])
{
Global.x = Global.x + 100;
Global.s = "bbb";
}
}
Question Does java support pointers? (CoreJava) Discuss in Detail (QID: 656)
Answer Strictly speaking, in Java, a pointer is a reference that is guaranteed not to be null. However, when people use the
term pointer, they usually mean C++ style direct hardware address pointers.
How can you write serious code without pointers? Java does not have raw pointers like C or C++. It has something almost
as powerful, but many times safer called references (Java refers to them as pointers in one place, the NullPointerException).
They are like pointers, except that the dangerous features are removed.
Question What is the disadvantage of using an inner class? (CoreJava) Discuss in Detail (QID: 655)
Answer Java bytecode has no concept of inner classes, so the compiler translates inner classes into ordinary classes that are
accessible to any code in the same package. An inner class gets access to the fields of the enclosing outer class-even if
these fields are declared private and the inner class is translated into a separate class. To let this separate class
access the fields of the outer class, the compiler silently changes these fields' scope from private to package. As a
result, when you use inner classes, you not only have the inner class exposed, but you also have the compiler silently
overruling your decision to make some fields private.
Question What are the different inner classes available in java? Explain each inner class with an example. (CoreJava) Discuss in Detail (QID: 654)
Answer There are four types of inner classes in java
1. Member class
2. Static member class
3. Local class
4. Anonymous class
1. Member class
A member class is defined as a member of a class. The member class is instance specific and has access to any and all
methods and members, even the parent's "this" reference. All public, protected, default, and private members are visible
to instances of member class.
You must provide an instance of the enclosing class when you create a new instance of member class.
public class EnclosingClass {
private int instVar = 1;
public class MemberClass {
public void innerMethod () {
instVar++;
}
}
public MemberClass createMember () {
return this.new MemberClass ();
}
}
If you need to create an instance of member class outside of the scope of the enclosing class, you need to use an
instance of the enclosing class to create the member instance:
EnclosingClass ec = new EnclosingClass ();
EnclosingClass.MemberClass mc = ec.new MemberClass ();
or
EnclosingClass.MemberClass mc = new EnclosingClass ().new MemberClass ();
member classes can be declared as abstract and final. The access specifiers, public, protected, default and private
can be used within the class.
2. Static member class
A static member class is a static member of a class. Like any other static method, a static member class has access to
all static methods of the parent, or top-level, class. These classes can use instance variables and methods only
through an object reference. Only public, final, and static are permitted as modifier inside a static member class.
E.g.
public class EnclosingClass {
private static int static_var = 0; // Has got access
public int instance_var = 0; // Has got no access
public static class StaticInnerClass {
}
}
Because the inner class is static, it can access only the static_var variable, even though it is private
It cannot access the instance_var variable because it is not static, regardless of the fact that it is public
The fully qualified class name for the inner class is EnclosingClass.StaticInnerClass
These classes can be declared as public, abstract and final.
public class Outer {
public String name = "Outer";
public static void main (String argv[]) {
Inner i = new Inner ();
i.showName ();
} //End of main
private static class Inner {
String name = new String ("Inner");
void showName () {
System.out.println (name);
}
} //End of Inner class
}
3. Local class
Local classes are declared within a block of code and are visible only within that block, just as any other method
variable. Local classes are good way to maintain Encapsulation.
Local classes, like local variables, cannot be declared public, protected, private, or static.
Local classes cannot have static members.
Local classes can only access final local variables and method arguments of the enclosing method.
Local inner classes can be declared as abstract and final.
Example
public class AnyClass {
void localClassDemo() { // a function
class LocalClass { // a class inside a function definition
void func() {
System.out.println( ?in Local class?);
}
}
LocalClass local = new LocalClass();
local.func() ;
}
}
4. Anonymous class
An anonymous class is a local class that has no name. An anonymous class is implicitly final.
Anonymous classes cannot be public, protected, private, or static. The syntax for anonymous inner classes does not
allow for any modifiers to be used. An anonymous inner class can extend a superclass or it can implement an interface.
But not both.
Example
public class SomeGUI extends JFrame
{
protected void buildGUI()
{
button1 = new JButton();
button2 = new JButton();
button1.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
});
}
}
Question Can an exception be re-thrown? (CoreJava) Discuss in Detail (QID: 651)
Answer Yes, the exception can be rethrown. And it will be rethrown to the caller method to handle the exception. This process
continues till a method that handles this exception is called.
Its better to handle the exception using "Exception" class as its the parent class that is being extended by all other
exception classes.
Question int[] array = new int[5];
int[] array1 = {1,2,3,4,5};
Why not new is used in second statement?
(CoreJava) Discuss in Detail (QID: 650)
Answer In the first line we are creating an int array with size 5 but in the second line we are creating an int array with 5 elements in it.
In short you are initializing an int array in line one and you are creating an int array with elements in line two.
Question Can we write a static keyword before the main class? (CoreJava) Discuss in Detail (QID: 647)
Answer No
Question Can main() of one java program be invoked in another java program's main()? (CoreJava) Discuss in Detail (QID: 646)
Answer Yes, This is possible. Have a look at the below code
package corejava;
public class A
{
public static void main(String args[])
{
System.out.println("in A");
}
}
package corejava;
public class B
{
public static void main(String args[])
{
System.out.println("in B");
String str = "one,two";
String[] strArray = str.split(str);
A.main(strArray);
}
}
Question What is the maximum size of Integer wrapper class? (CoreJava) Discuss in Detail (QID: 643)
Answer 2 TO THE POWER OF 31 - 1 or 2147483647 int value. Its little hard to remember all these stuff :(
Question What is Tight Encapsulation? (CoreJava) Discuss in Detail (QID: 642)
Answer Encapsulation is for member variables in a classes that may not be accessed by any other classes. Below are few examples
Example 1:
class Test {
private String name;
}
This class is tightly encapsulated as you can't access the member "name".
Example 2:
class Test2 {
private String name;
public void setName(String name) {
if(name.equals("test2") {
this.name = name;
}
else {
//throw user exception
}
}
public String getName() {
return name;
}
}
The standard way to protect the data is to make it private, so that no other class can get direct access to it, and
then write public methods to get the data and set the data. The method that sets the data should carry out appropriate
checks to make sure the incoming data is valid.
In Example 2 we are validating the incoming data with "test2". If its test2 we are allowing the data to be set, else
we are throwing an exception.
Tight encapsulation will not only protect direct access to data members, but will also prevent those members from being
set to improper values.
Question How does a try statement determine which catch clause should be used to handle an exception? (CoreJava) Discuss in Detail (QID: 628)
Answer When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear.
The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored
Question Assume you have an ArrayList with 7 objects in it. And there is an int[] as
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;
How do you go about deleting objects from ArrayList based on the values present in int[]? (CoreJava) Discuss in Detail (QID: 619)
Answer This looks to be very simple question as we can make a for loop and remove objects from
ArrayList. But remember that for the first time when you try to remove an object at index 2 from ArrayList,
you would end up with an ArrayList size reduced from 7 to 6.
And your code would be throwing ArrayIndexOutOfBoundsException. Have a look at this piece of code
public void testArrayList()
{
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;
ArrayList al = new ArrayList();
for(int i=0; i <>
{
al.add("test "+i);
}
System.out.println(al);
for(int x=0; x <>
{
System.out.println(al.remove(intArray[x]));
}
}
The above code doesn't work as the ArrayList size would shrink when you try to remove the first element.
Have a look at this working code below
public void testArrayList()
{
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;
ArrayList al = new ArrayList();
for(int i=0; i <>
{
al.add("test "+i);
}
System.out.println(al);
for(int x = intArray.length-1; (x != -1); x--)
{
System.out.println(al.remove(intArray[x]));
}
}
You should try to delete from the bottom of the ArrayList. So that the size of the ArrayList doesn't effect the index of the objects
that we are trying to delete.
Question Why do we require public static void main(String args[]) method in Java programme? (CoreJava) Discuss in Detail (QID: 595)
Answer Following are few reasons why there is public static void main(String args[])
a. public: The method can be accessed outside the class / package
b. static: You need not have an instance of the class to access the method
c. void: Your application need not return a value, as the JVM launcher would return the value when it exits
d. main(): This is the entry point for the application
If the main() was not static, you would require an instance of the class in order to execute the method.
If this is the case, what would create the instance of the class? What if your class did not have a public constructor?
java Test
would get converted to Test.main() there by invoking the main()
Question Have a look at the following code.
How do I execute the method d() in class B without creating another instance in the main method.
class A {
void c() {
System.out.println("In A class");
}
}
public class B extends A {
void d() {
System.out.println("In B class");
}
public static void main(String args[]) {
A a = new B();
}
}
(CoreJava) Discuss in Detail (QID: 590)
Answer you will need to typecast the object to ((B)a).d();
Question What will the output of the following programme be? Look at the programme carefully, we have an instance method and
static method (class method) defined in both Animal class and Cat class.
public class Animal {
public static void hide() {
System.out.format("The hide method in Animal.%n");
}
public void override() {
System.out.format("The override method in Animal.%n");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.format("The hide method in Cat.%n");
}
public void override() {
System.out.format("The override method in Cat.%n");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
//myAnimal.hide(); //BAD STYLE
Animal.hide(); //Better!
myAnimal.override();
}
}
(CoreJava) Discuss in Detail (QID: 587)
Answer The output of the programme will be..
The hide method in Animal.
The override method in Cat.
For class methods, the runtime system invokes the method defined in the compile-time type of the reference on which the
method is called. In the example, the compile-time type of myAnimal is Animal. Thus, the runtime system invokes the hide
method defined in Animal. For instance methods, the runtime system invokes the method defined in the runtime type of the
reference on which the method is called. In the example, the runtime type of myAnimal is Cat. Thus, the runtime system
invokes the override method defined in Cat.
An instance method cannot override a static method, and a static method cannot hide an instance method.
Question How do you know if an explicit object casting is needed? (CoreJava) Discuss in Detail (QID: 566)
Answer If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
Question What would you use to compare two String variables - the operator == or the method equals()? (CoreJava) Discuss in Detail (QID: 565)
Answer I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the
same instance of a String object.
Question It is valid to declare an inherited method as abstract? (CoreJava) Discuss in Detail (QID: 564)
Answer Yes its valid to declare an inherited method abstract. But it would be of no use as you need to define the class
abstract again.
e.g.
abstract class AbsTest
{
abstract void setName(String name);
}
public class AbsTest1 extends AbsTest //compile error is thrown as there is an abstract method, declare the class abstract
{
abstract void setName(String name){} // error, abstract method cannot have body
}
Question What's the difference between constructors and other methods? (CoreJava) Discuss in Detail (QID: 563)
Answer Constructors must have the same name as the class and can not return a value. They are only called once while
regular methods could be called many times.


No comments:
Post a Comment