SIDE-BANNERSIDE-BANNER * Oh God! Let there be PEACE. Make them calm, gentle, humble and stable. Make them realize their mistakes. Make them to confess, seek and pray for forgiveness. Let there be forgiveness for true hearts. Show them the right path on which they can walk. Let there be justice, satisfaction and happiness. Let them know that you are the justice and truth. Let them know that the innocent is never punished. Give them the strength, courage and wisdom to quit bad and to achieve good purpose. Let there be leaders who are followed by goodness. Make them competitive to achieve good. Remove their greed, wickedness and bad ambitions. Let them know that your love is infinite. Speak to them in simple ways so they understand. May your heart hear their pure hearts. * Never say die.Live and let live.* Accept Good if not, it Perishes.* What you Sow is what you Reap.* United we Stand divided we Fall.* Where there is a Will there is a Way.* Love is the strongest Power on earth.* When going gets Tough the Tough gets going.* For every problem created there is a perfect Solution.* When your hand starts paining you don't Cut it, Cure it.* A good purpose of life is the persistence to be constructive.* The arch of justice is wide, but it bends towards freedom and justice.* Lion king says he wants all the Power but none of the Responsibilities.* Life is a puzzle which can be solved by Hard work, Character and Discipline.* Money is like Manure, Spread it and it does good.* Pile it up in one place and it Stinks.* When a man wants to be a King he should exactly know the responsibilities of a King.* The only thing necessary for evil to triumph is for good men to do nothing - Edmund Burke.* Face is the reflection of mind.* A purpose of life is a life of purpose.* Beauty lies in the eyes of the beholder.* Necessity is the mother of all inventions. Real friends are those who help us in troubles.* Freedom and Power are lost if it’s miss utilized. Repeating mistakes will lead to sin and blunders.* Quantity is appreciated only when it has Quality.* Everyday is a new day, which brings hope with it.* Ego of superiority is the destruction of individuality.* We cannot learn to swim without going into the water.* Everything happens for good and thus leads to destiny.* Every problem has a perfect solution, we need to find them.* A good purpose of life is the persistence for constructiveness.* It’s hard to create good things where as it’s easy to break them.* Ideas are appreciated and respected only when we express them.* Mistakes do happen by humans, they are forgiven when we pray.* Freedom means giving others the right to achieve good purposes.* We have to put our efforts and leave the rest for destiny to decide.* All big things start with a first step.* First step is sometimes difficult.* Prayers come true when the purpose is good, thus pray for everyone.* Dreams come true when we have faith and pray for good things in life.* We got to have strength, courage and wisdom to achieve good things in life.* Every relationship has a meaning; we have to give them the proper meaning.* The only thing necessary for the triumph of evil is for good men to do nothing.* If wealth is lost, nothing is lost. If health is lost, something is lost. But, if character is lost, everything is lost.* “Stand up, be bold, be strong. Take the whole responsibility on your own shoulders, and know that you are the creator of your own destiny.” - Swami Vivekananda.
HOME-PAGEREALIZATIONQUOTESPUZZLESPRAYERSPERCEPTIONSMUSIC-DOWNLOADSTORIESJOKES
BOOKSBITTER-TRUTHANCIENT-SCRIPTURESBEAUTIFUL-LIFETHOUGHTSFRIENDSHIPPRAYERS-TO-WORSHIPWinning-Publications

QUANTITY is appreciated only when it has QUALITY. Recitation is the mother of Memory. Necessity is the mother of Invention. Knowledge grows when distributed. Enrichment for Information Technology. Persistence to be constructive is the key to success.

Monday, February 18, 2008

CORE-JAVA (oop)

*[READ: Why-JAVA] *[Start-Learning-JAVA] *[Why-Java's-Hot] *[Start-Using-LINUX] *[Java-Q-&-A] *[Question] *[Java-SE-6-Doc] *[Struts-Doc] *[Java-Tutorial-Index] *[Java-Certification]
*[Tech.] *[Struts.] *[Servlet.] *[JSP.] *[EJB.] *[JNDI-JMS] *[SQL.] *[JDBC.]
CORE-JAVA: *[OOP] *[CLASS] *[ABSTRACT] *[EXCEPTIONS] *[THREADS] *[UTILS] *[PACKAGES] *[JVM] *[CASTING] *[NETWORKING] *[RMI-XML] * Add to Google


Nuts-N-Bolts. Tutorial.
Compile Java code online over the web: Remote compiling service.

* What are the four corner stones of OOP ? (oop) (java-OOP) (Oop-Concept)
Abstraction, Encapsulation, Polymorphism and Inheritance.

* What are the advantages of OOPL? (OOP)
Object oriented programming languages directly represent the real life objects. The features of OOPL as inheritance, polymorphism, encapsulation makes it powerful.

* What do we mean by polymorphism, inheritance, encapsulation? (OOP)
Polymorphism: is a feature of OOPL that at run time depending upon the type of object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

* What do you mean by virtual methods in C++? (virtual)
virtual methods are used to accomplish the polymorphism in C++. Say class A is inherited from class B. If we declare say function f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

* What are some alternatives to inheritance? (oop)
A: Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

* Why Java does not support multiple inheritance? (oop)
A: Java DOES support multiple inheritance via interface implementation.

* What do you mean by multiple inheritance in C++? (oop)
Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.

* Can you write Java code for declaration of multiple inheritance in Java ? (oop)
Class C extends A implements B { }

* Difference Between Abstraction and Encapsulation. (oop)
Abstraction is removing some distinctions between objects, so as to show their commonalities.
Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation.


* * * * * * * * * * * * *
*[Read: Liberate the Sole.] *[The Qualities of Vaishnava.] *[Sanskrit Peace Translations.] *[The path of victory.]

*[Read: Significance of Nava-ratna (Nava-Graha).] *[Amazing Constructive Vibrations.] *[Things become inevitable!]

Read: Peace

Home Download Music Prayers Life Is Beautiful

*Realizations. *Realizations In Real Life. *Amazing Constructive Vibrations. *Astrology. *Creating Leaders. *How ideas are concluded and decisions are materialized. *Relationships & Partnerships. *The path of victory. *An attempt for definition. *Speak with a heart. *These are contagious. *Happy kingdom. *MIRACLES. *Better to create one ! *Cast, God and religion ! *Things become inevitable ! *We are all looking for! *Phase of Life. *Destiny, Karma and God. *Struggle, perfection and Money. *Independence and Freedom. *Relationships and Happiness.

CORE-JAVA (Class, Variable & Method)

*[READ: Why-JAVA] *[Start-Learning-JAVA] *[Why-Java's-Hot] *[Start-Using-LINUX] *[Java-Q-&-A] *[Question] *[Java-SE-6-Doc] *[Struts-Doc] *[Java-Tutorial-Index] *[Java-Certification]
*[Tech.] *[Struts.] *[Servlet.] *[JSP.] *[EJB.] *[JNDI-JMS] *[SQL.] *[JDBC.]
CORE-JAVA: *[OOP] *[CLASS] *[ABSTRACT] *[EXCEPTIONS] *[THREADS] *[UTILS] *[PACKAGES] *[JVM] *[CASTING] *[NETWORKING] *[RMI-XML] * Add to Google


* What is the difference between a constructor and a method? (corejava) (Constructor) (Method) (Test(open))

A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

* What is the difference between declaring a variable and defining a variable? (Variable) (Declaring Variable)
A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

* What is the default value of an object reference declared as an instance variable?
A: null unless we define it explicitly.

* What type of parameter passing does Java support? (Pass by value) (Argument)
A: In Java the arguments are always passed by value .

* Are Primitive data types passed by reference or passed by value? (Argument)
A: Primitive data types are passed by value.

* Are Objects passed by value or by reference?
A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

* What is passed by reference and what by value ?
All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references.

* What are pass by reference and pass by value? (corejava)
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

* Which class should you use to obtain design information about an object? (Class)
The Class class is used to obtain information about an object’s design.

* Does Java provide any construct to find out the size of an object?
A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.

* Is sizeof a keyword in C/C++ language?
The sizeof operator is not a keyword.

* What is the Local class? (Local)
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. A local class is a nested class that is not a member of any class and that has a name.

* What is the difference between a field variable and a local variable? (variable)
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

* What is a LOCAL, MEMBER and a CLASS variable?
Variables declared within a method are LOCAL variables.
NON-STATIC Variables declared within the class i.e not within any methods are MEMBER variables (INSTANCE variables).
STATIC Variables declared within the class i.e not within any methods and are defined as static are CLASS variables.

* Why are there no "global variables" in Java, as in C language?
Global variables is a concept of C language which is considered as wrong, for a variety of reasons: Adding state variables breaks referential transparency. State variables lessen the cohesion of a program. In terms of Java, "global variables" are similar to "public static MEMBER variables".
In the spirit of encapsulation, it is a best practice to have member variables as private. However we can access these values indirectly with public get() and set() methods, which can obtain the values of member variables. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When we add one variable, we limit the use of our program to one instance. What we thought was global, someone else might think of as local: they may want to run two copies of our program at once. For these reasons, Java decided to ban global variables.

* How are this() and super() used with constructors? (constructor) (Super) (this Keyword) (Super Keyword)
A: Keyword this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

* Are true and false keywords? (keyword) (Boolean)
No, the values true and false are not keywords, they are Boolean values.

* In System.out.println(),what is System, out and println, explain.
A: "System" is a predefined final class, "out" is a PrintStream object and "println" is a built-in overloaded method in the out object.

* Can a private method of a superclass be declared within a subclass? (Requirements in Overriding and Hiding)
A subclass can declare a method with the same signature as a private method in one of its superclasses. But it cannot override the method.
A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding.

* What restrictions are placed on method overriding? (overriding)
Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown by the overridden method.
Methods may be overridden to be more public, not more private.

* What is Overriding? (overriding)
A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass.
Methods may be overridden to be more public, not more private.

* What is the difference between method overriding and overloading? (overriding)
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments (signature).
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures. Methods are overridden on a signature-by-signature basis.

* What are the Object and Class classes used for?
The OBJECT class is the highest-level class in the Java class hierarchy.
Class OBJECT is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
The CLASS class is used to represent the classes and interfaces that are loaded by a Java program. Instances of the class CLASS represent classes and interfaces in a running Java application.

* What is the difference between inner class and nested class? (inner)
When a class is defined within a scope of another class, it becomes a inner class.
If the access modifier of the inner class is static, then it becomes nested class.
Nested classes are divided into two categories: static and non-static.
Nested classes that are declared "static" are simply called "static nested classes".
"Non-static" nested classes are called "inner classes".

* What modifiers may be used with an inner class that is a member of an outer class? (inner)
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
"Non-static nested classes" (inner classes) have access to other members of the enclosing class, even if they are declared private.
"Static nested classes" do not have access to other members of the enclosing class.
As a member of the OuterClass, a nested class can be declared private, public, protected, or package private (default).
Outer classes can only be declared public or package private (default).

* What are different types of inner classes? (inner)
A: Static Nested class, Member inner classes(Non Static), Local classes and Anonymous classes
* Static Nested classes - If we declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.
* Member inner classes (Non Static) - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.
* Local classes - We can declare an inner class within the body of a method. Such a class is known as a "local inner class".
Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable.
* Anonymous classes - We can also declare an inner class within the body of a method without naming it. These classes are known as "anonymous inner classes". Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

* Is null a keyword? (keyword)
Null is a value and not a keyword.

* What is a native method? (native)
A native method is a method that is implemented in a language other than Java.

* What are "order of precedence" and "associativity", and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions.
Associativity determines whether an expression is evaluated left-to-right or right-to-left. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first.
* All "Binary operators" except for the assignment operators are evaluated from left to right. Binary operators are often called logical operators AND, OR ( && || )
* All "Assignment operators" are evaluated right to left.
There are 12 assignment operators, ( = *= /= %= += -= <<= >>= >>>= &= ^= |= )
Ex: a=b=c means a=(b=c) (right-to-left)
* class Test {
---public static void main(String[] args) {
---int i = 2;
---int j = i * (i=3);
---System.out.println(j); // output is 6 (* is left to right)
---i = 2;
---int j = (i=3) * i;
---System.out.println(j); // output is 9
---System.out.println(++j); // output is 10
---System.out.println(j++); // output is 10
---System.out.println(j); // output is 11
---j += (j = 3);
---System.out.println(j); // output is 14
---j = j + (j = 3);
---System.out.println(j); // output is 17 } }

* If a variable is declared as private, where may the variable be accessed? (variable)
A private variable may only be accessed within the class in which it is declared.

* Which class is extended by all other classes?
The Object class is extended by all other classes.

* How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero. Also see: Math, DecimalFormat. Primitive Conversion: Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Narrowing conversions may lose information about the overall magnitude of a numeric value. (Constant Values of integers)
* Widening:
# byte to short, int, long, float, or double
# short to int, long, float, or double
# char to int, long, float, or double
# int to long, float, or double
# long to float or double
# float to double
* Narrowing:
# byte to char
# short to byte or char
# char to byte or short
# int to byte, short, or char
# long to byte, short, char, or int
# float to byte, short, char, int, or long
# double to byte, short, char, int, long, or float

* Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses. A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

* What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.

* Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.

* I made my class Cloneable but I still get "Can't access protected method clone". Why?
A class implements the Cloneable interface to indicate the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.
We have to override/implement our own public clone() method, even if it doesn't do anything special other than calling super.clone(). All the below statements are true for a clone:
x.clone() != x
x.clone().getClass() == x.getClass()
x.clone().equals(x)

* Difference between a Class and an Object ?
A CLASS is a definition or prototype whereas an OBJECT is an instance or living representation of the prototype

* Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly:
* Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
* The instance variables of the objects are initialized to their default values.
* Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed.
* The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

* What is constructor chaining and how is it achieved in Java ?
A child object constructor always first needs to construct its parent (which in turn calls its parent constructor). In Java it is done by an implicit call to the no-args constructor as the first statement.
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

* Is "abc" a primitive value?
The String literal "abc" is not a primitive value. It is a String object.

* You can create a String object as String str = "abc"; Why cant a button object be created as Button btn = "abc";? Explain.
The main reason you cannot create a button by Button btn= "abc"; is because "abc" is a literal string (something slightly different than a String object, by-the-way) and btn is a Button object.
The only object in Java that can be assigned a literal String is java.lang.String. Ex:
Button btn = new Button("String-Name");
Important to note that we are NOT calling a java.lang.String constuctor when we type String s = "abc", as it is a special support given by the Java language. The String class is not technically a primitive "data type". String objects are immutable, which means that once created, their values cannot be changed.

* To what value is a variable of the String type automatically initialized?
The default value of an String type is not null, but an empty character.
String str = new String(); // represents an empty character sequence.
System.out.println( str.length() ); // is "0" and not "null"

* What is the output from System.out.println("Hello"+null);
Hellonull

* Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiguity for the compiler.

* Is a class a subclass of itself?
Yes, a class is a subclass of itself.

* What is the difference between a while statement and a do statement? (statement) (while-statement)
A: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

* What is the purpose of a statement block? (statement) (Expressions, Statements, and Blocks)
A statement block is used to organize a sequence of statements as a single statement group.

* What is the difference between an if statement and a switch statement? (statement) (if-then-Statement) (Switch-statement)
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed.
The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

* What is the difference between a break statement and a continue statement? (statement) (Break-and-Continue-Statement)
A break statement results in the termination of the statement to which it applies (switch, for, do, or while).
A continue statement is used to end the current loop iteration and return control to the loop statement.

* What restrictions are placed on the values of each case of a switch statement? (statement)
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

* How are commas used in the initialization and iteration parts of a for statement? (statement) (for-statement)
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. Ex:
for (initialization; termination; increment) { statement(s) }

* Can a for statement loop indefinitely? (statement)
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

Difference between Swing and Awt? (corejava)
A: AWT are heavy-weight components. Swings are light-weight components. Hence swing works faster than AWT.

What if the main method is declared as private? (main)
A: The program compiles properly but at runtime it will give an error message "Main method not public.".

What if the static modifier is removed from the signature of the main method? (main)
A: Program compiles. But at runtime throws an error "NoSuchMethodError".

What if we write static public void instead of public static void? (main)
A: Program compiles and runs properly.

What if we do not provide the String array as the argument to the method? (main)
A: Program compiles but throws a runtime error "NoSuchMethodError".

What is the first argument of the String array in main method? (main)
A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

If we do not provide any arguments on the command line, then the String array of Main method will be empty or null? (main)
A: It is empty. But not null.

How can one prove that the array is not null but empty? (main)
A: Print args.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 args.length.

* What is the argument type of a program's main() method? (main)
A program's main() method takes an argument of the String[] type.

Can an application have multiple classes having main method? (main)
A: Yes it is possible. 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 no conflict amongst the multiple classes having main method.

Can I have multiple main methods in the same class? (main)
A: No the program fails to compile. The compiler says that the main method is already defined in the class.

* What is the return type of a program’s main() method? (main)
A program’s main() method has a void return type.

How are Observer and Observable used?
A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. (Ex.)
The Observer interface is implemented by objects that observe Observable objects.

How does Java handle integer overflows and underflows?
A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

* What are the legal operands of the instanceof operator?
The left operand is an object reference or null value, and the right operand is a class, interface, or array type.
(Ex:) Parent obj1 = new Parent(); Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); // true
Output: obj1 instanceof Parent: true

* What are E and PI? (Math)
E is the base of the natural logarithm and PI is mathematical value pi.
java.lang.Math (Constant Values)
public static final double - E - 2.718281828459045
public static final double - PI - 3.141592653589793

* To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false

* What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation. (Ex: ++int)
The postfix form returns the current value of the expression and then performs the increment operation on that value. (Ex: int++)

* How can we convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com? (Networking)
String hostname = InetAddress.getByName("192.18.97.39").getHostName();

* Which non-Unicode letter characters may be used as the first character of an identifier?
The non-Unicode letter characters "$" or "_" may appear as the first character of an identifier.

* Which characters may be used as the second character of an identifier, but not as the first character of an identifier?
The digits 0 through 9 may NOT be used as the first character of an identifier but they may be used after the first character of an identifier. (RFID and Auto-ID)

* How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
Note: "Bit" is the smallest unit of information in a computer, with a value of either 0 or 1.
"Byte" is a sequence of eight bits.
"Bytecode" is the Machine-independent code generated by the Java-Compiler and executed by the Java Interpreter.

* What is the range of the char type?
The range of the char type is (0) to (2^16 - 1).
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

* What is the difference between the Boolean "& operator" and the "&& operator"?
If an expression involving the Boolean "& operator" is evaluated, both operands are evaluated. Then the & operator is applied to the operand.
When an expression involving the "&& operator" is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Ex: if (a=b & b=c) compare both a=b and b=c.
if (a=b && b=c) compare b=c only if a=b is true.

* Which Java operator is right associative (from right to left)?
There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a. The = operator is right associative.
The conditional operator (?) is syntactically right-associative.
(it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

* What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. (Link:1) (Link:2)
First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use.
The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process un-handled events, as is the case of the event-inheritance model.

* What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

* Is the ternary operator written (x : y ? z) or (x ? y : z) ?
It is written x ? y : z.
Ex: result = someCondition ? value1 : value2; // if true then value1, else value2.

* What is a "stateless" protocol ?
HTTP is a stateless protocol, there is no retention of state between a transaction which is a single request response combination. Each command is executed independently, without any knowledge of the commands that came before it.

* What is the difference between logical data independence and physical data independence?
Logical Data Independence - meaning immunity of external schema to changes in conceptual schema.
Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema.
(Data Independence)
* Internal schema describing details of data storage and their access paths.
* Conceptual schema, describing a model of the real world the database represents.
* External schema, one for each user to represent, hiding what that user is not interested in.
* Logical data independence: capacity to change the conceptual schema without having to change external schema (and the applications using it) – e.g. adding new concepts, or new relations, to the conceptual schema will not influence external views already defined of new concepts.
* Physical data independence: capacity to change the internal schema without having to change conceptual (or external) schema – e.g. changing the way the physical files are stored.

* What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

* What is the range of the short data type?
The range of the short type is -(2^15) to 2^15 - 1. The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).

* Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?
The import statement does not bring methods into our local name space. It lets us abbreviate class names, but not get rid of them altogether.
Moreover java.lang.Math is a "final" class which means it can't be extended.

* Why does it take so much time to access an Applet having Swing Components the first time?
Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.

* Why are the methods of the Math class static? (static)
So they can be invoked as if they are a mathematical code library.

* What is the difference between static and non-static variables? (static)
A: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

* What does it mean that a method or field is "static"? (static)
A: Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.

* What do you mean by static methods? (static)
By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.

* What is static in java? (static)
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class. 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, it is not possible to override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

* What is the difference between a static and a non-static inner class? (static)
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

* What happens to a static var that is defined within a method of a class? (static)
Can’t do it. You’ll get a compilation error.

* How many static init can you have? (static)
As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.

* What is final? (final) (sun link)
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

* Write the Java code to declare any constant (say gravitational constant) and to get its value. (final)
---Class ABC
----{ static final float GRAVITATIONAL_CONSTANT = 9.8;
-----public void getConstant()
-----{ system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT); } }

* What does it mean that a class or member is final? (final)
A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;

* What does the “final” keyword mean in front of a variable? A method? A class? (final)
FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived.

* What is a transient variable?
Transient variable is a variable that may not be serialized. Transient meaning: not lasting longer, temporary, staying only a short time. Variables may be marked transient to indicate that they are not part of the persistent state of an object.
If an instance of the class Point:
class Point { int x, y;
transient float rho, theta; }
were saved to persistent storage by a system service, then only the fields x and y would be saved. This specification does not specify details of such services; see the specification of java.io.Serializable for an example of such a service.

What is serialization? (serialize)
A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

How do I serialize an object to a file? (serialize)
A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a FileOutputStream. This will save the object to a file.

Which methods of Serializable interface should I implement? (serialize)
A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

How can I customize the seralization process? i.e. how can one have a control over the serialization process? (serialize)
A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

What is the common usage of serialization? (serialize)
A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serialized.

What is Externalizable interface? (serialize)
A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods. Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in).

What happens to the object references included in the object? (serialize)
A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized along with the original object.

What one should take care of while serializing the object? (serialize)
A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

What happens to the static fields of a class during serialization? (serialize)
A: There are three exceptions in which serialization does not necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of any particular state. 2. Base class fields are only handled if the base class itself is serializable. 3. Transient fields.

* How many methods do u implement if implement the Serializable Interface? (serialize)
The Serializable interface is just a "marker" interface, with no methods of its own to implement. Other 'marker' interfaces are
java.rmi.Remote
java.util.EventListener

* Why does JComponent have add() and remove() methods but Component does not? (Swing)
Because JComponent is a subclass of Container, and can contain other components and jcomponents.

* Can applets communicate with each other? (applet)
A: At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable. An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once we get a reference to an applet, we can communicate with it by using its public members. It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial. A Java class can be used both as an applet as well as an application by adding a main() method to the applet.

* Why isn't there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

* What is Singleton Design Pattern?
Its a design used to create only one instance of a class, or to control the number of object creations. The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. (Ex:)
public class MySingleton {
--private static MySingleton single;
--private MySingleton() { MySingleton.getInstance(); // construct object }
--public static synchronized MySingleton getInstance() {
---if (single==null) { single = new MySingleton(); }
--return single; } }

Reflection. Java.lang.reflect. Helps to examine or modify the runtime behavior of applications. Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods.

* * * * * * * * * * * * *
*[Read: Significance of Nava-ratna (Nava-Graha).] *[Read: Amazing Constructive Vibrations.] *[Liberate the Sole.]

Read: Peace Home Download Music Prayers Life Is Beautiful
Winning Publications.
*Significance of Nava-ratna (Nava-Graha). *Amazing Constructive Vibrations. *The piercing of the ears (karnavedha) . *Nature Cure. *Steps to improve work place. *Steps Involved In Relationships. *Some of the aspects which materialize the relationships.

Thursday, February 14, 2008

CORE-JAVA (Abstarct, Interface)

*[READ: Why-JAVA] *[Start-Learning-JAVA] *[Why-Java's-Hot] *[Start-Using-LINUX] *[Java-Q-&-A] *[Question] *[Java-SE-6-Doc] *[Struts-Doc] *[Java-Tutorial-Index] *[Java-Certification]
*[Tech.] *[Struts.] *[Servlet.] *[JSP.] *[EJB.] *[JNDI-JMS] *[SQL.] *[JDBC.]
CORE-JAVA: *[OOP] *[CLASS] *[ABSTRACT] *[EXCEPTIONS] *[THREADS] *[UTILS] *[PACKAGES] *[JVM] *[CASTING] *[NETWORKING] *[RMI-XML] * Add to Google

* What is the difference between an Interface and an Abstract class?
* [INTERFACE] An Interface can only declare constants and instance methods, but cannot implement default behavior.
All the methods and properties defined in Interface are by default public and abstract.
Interfaces are recommended to be used when something in design will change frequently
We use abstract class and Interface for the base class in our application.
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

* [ABSTRACT] An abstract class can have instance methods that implement a default behavior.
An abstract class is a class that is declared abstract.
It may or may not include abstract methods.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon). Ex: abstract void moveTo(double deltaX, double deltaY);
Abstract classes cannot be instantiated.
Abstract classes can only be subclassed.
If a class includes abstract methods, the class itself must be declared abstract.
Ex: public abstract class GraphicObject {
// declare fields and non-abstract methods
abstract void moveTo(double deltaX, double deltaY);
abstract void draw(); } (compile online)
An abstract class may have the usual flavors of class members (private, protected, etc.)

* What modifiers are allowed for methods in an Interface? (Interface)
A: Only public and abstract modifiers are allowed for methods in interfaces.

* What is meant by "Abstract Interface"? (Interface)
A: First, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods.

* Why it is not recommended to have instance variables in Interface. (interface)
By Default, All data members and methods in an Interface are public. Having public variables in a class that will be implementing it will be violation of the Encapsulation principal. Although its possible to have variables.

* What are the characteristics of an interface? (interface)
An interface can extend any number of interfaces. (Ex.)
public interface GroupedInterface extends Interface1, Interface2, Interface3 {
--// constant declarations
are implicitly public, static, and final. (cannot be private)
--double E = 2.718282; // base of natural logarithms
--// method signatures
are implicitly public (cannot be private)
--void doSomething (int i, double x);
--int doSomethingElse(String s); } (compile online)
If access specifier is not indicated before an interface as public, then by default the interface will be accessible only to classes defined in the same package as the interface.
All methods declared in an interface are implicitly public, thus the public modifier can be omitted.
An interface can contain constant declarations. All constant values defined in an interface are implicitly public, static, and final. Thus, specifying these modifiers in the code can be omitted. Interfaces can have inner classes.

* What must a class do to implement an interface? (interface)
It MUST implement all of the methods of the interface and identify the interface in its implements clause. All methods defined by that interface must appear in its source code.

* What modifiers may be used with an interface declaration? (interface)
An interface may be declared as public or abstract or default (no modifier).

* Can an Interface be final? (interface)
No, an Interface cannot be final, private or protected. It can only be either public, abstract or default (when access is not specified). Public is available in any package, and default is in the same package.

* Can an Interface have an inner class? (interface)
Yes it can. Ex:
public interface abc
{ static int i=0; void dd(); // constant variable and public method.
class a1 // it cannot be private
-{
--a1()
---{ int j; System.out.println("inside"); };
--public static void main(String a1[])
---{ System.out.println("in interfia"); }
-}
}
(compile online)

*
What is an abstract class? (abstract)
A: Abstract class MUST be extended/subclassed. It serves as a template.
An abstract class must NOT be instantiated (ie, you may not call its constructor)
Abstract class must NOT be declared as PRIVATE or FINAL.
An abstract class MAY contain PRIVATE and STATIC data.
Any class with an abstract method MUST be declared as abstract.
An abstract method must NOT be PRIVATE or STATIC.
An NON-abstract method MAY be PRIVATE STATIC or public.
This prevents it from being instantiated but non-abstract methods can be used in its inherited subclasses. (Ex:)
abstract class Abstract1 { // cannot be private
--private static int x, y; // private static variable.
--private static void moveTo(int newX, int newY) { // private static method.
---System.out.println("in abstract class, non-abstract method"); }
--abstract void draw(); // cannot be PRIVATE or STATIC.
}
(compile online)
Note: non-abstract methods can be static but not abstract methods.

* Can we make an instance of an abstract class? For example - java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class. (abstract)
A: No! We cannot make an instance of an abstract class. An abstract class has to be sub-classed. If we have an abstract class and we want to use a method which has been implemented, we may need to subclass that abstract class, instantiate our subclass and then call that method.

* Can an abstract class be final? (abstract)
An abstract class may not be declared as final NOR private.

* Can there be an abstract class with no abstract methods in it? (abstract)
Yes, it is possible.

* What is an abstract method? (abstract)
An abstract method is a method whose implementation is deferred to a subclass.

* What does the "abstract" keyword mean in front of a method? A class? (abstract)
Abstract keyword declares either a method or a class.
Abstract method may have only arguments and return types.
Abstract methods act as placeholder methods that are implemented in the subclasses.
Abstract classes can't be instantiated.
If a class contains any abstract method it must be declared as abstract.

* What does it mean that a method or class is abstract? (abstract)
An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

* Can an ABSTRACT class implement an INTERFACE?
Yes we can! It is possible, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. For example:
abstract class X implements Y { // implements all but one method of Y }
class XX extends X { // implements the remaining method in Y }
Note that class XX is not abstract, thus it has to implement all methods of Y.

* Can an nested Anonymous class be declared as implementing an interface and extending a class? (interface) (nested)
An anonymous class may implement an interface OR extend a superclass, but may NOT be declared to do BOTH.

* How can we take decision about when we have to use Interface and when Abstract Class? When should we use both? Interfaces and abstract classes seem superficially to provide almost the same capability. How do we decide which to use?
* ABSTRACT class is a abstract view of any real word entity and INTERFACE is a more abstract one. When we thinking about the entity there are two things one is intention and one is implementation. Intention is we know about the entity and also may have the idea about its state as well as behavior but don't know about how its looks or works or may know partially. Implementation means actual state and behavior of entity.
Consider this example. In a Content Management System where CONTENT is a generalize form of ARTICLES, REVIEWS, BLOGS etc.
So CONTENT is our base class now we have to decide whether CONTENT class should be an ABSTRACT class, INTERFACE or REGULAR class.
Consider REGULAR class vs other types (abstract and interface). If CONTENT is not a core entity of this application. As per the business logic if ARTICLES, BLOGS and REVIEWS are the core parts of business logic, then CONTENT class should not be a REGULAR class because we will never make instance of that class. Thus ABSTRACT class and INTERFACE are the more appropriate choices.
Between Interface and Abstract Class.
As we can see CONTENT having behavior method named PUBLISH. According to our business logic if PUBLISH is having some default behavior which is applicable to other classes then we prefer CONTENT class as an ABSTRACT class. If there is no default behavior for the PUBLISH and if every drive class makes its own implementation, then there is no need to implement PUBLISH behavior in the base class, thus we prefer INTERFACE. These are the in general ideas of deciding between ABSTRACT class, INTERFACE and REGULAR class.
If we make CONTENT class as INTERFACE then it is difficult to make changes in the base class, as if we add a new method or property in CONTENT interface then we may have to implement this new method in every drive class. These problems may be avoided if we are using ABSTRACT CONTENT class and the new method is not of an ABSTRACT type. So we can replace INTERFACE with ABSTRACT class. This will restrict the multiple inheritance of the base class.
CAN-DO and IS-A relationship will also define the difference between INTERFACE and ABSTRACT class. As discuss INTERFACE can be use for multiple inheritance. For example if we have another INTERFACE named ICOPY which is having a behavior method named COPY and if every drive class has to implement its own implementation of COPY. If ARTICLE class is derived from ABSTRACT class CONTENT as well as ICOPY then ARTICLE "CAN-DO" COPY also.
IS-A is for "generalization" and "specialization". If CONTENT is a generalized form of Articles, Blogs, Reviews and if Articles, Blogs, Reviews are a specialized forms of CONTENT. So, ABSTRACT class defines core identity. If we are thinking in term of speed then ABSTRACT is quicker then INTERFACE, as interface requires extra in-direction.
As per the example, as ABSTRACT class is having upper-hand if compared to an INTERFACE. The only advantage of INTERFACE is multiple inheritance.
An INTERFACE facilitates us to start from scratch to implement our interface in some other code whose original/primary purpose was quite different from our interface. For others, our interface is only incidental, something that has to be added on to the their code to use our package.
An ABSTRACT class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. It may be inconvenient to extent the class if the programmers using our package who have already developed the class hierarchy. As in Java, a class can inherit from only one base class.


*Read:
*[ Religion of the Universe.] *[The piercing-of-the-ears-(Karnavedha).] *[Nature-Cure/Therapy.]

"WE" has More Power than "I". Please leave a comment if you encounter any problems or have any suggestions.

Read: Peace Home Download Music Prayers Life Is Beautiful
The Bitter Truth.
*Duty, Responsibility, Law and Order. *"Happy Kingdom" proudly proclaimed as "Paradise" *Trying to learn something for the first time. *Time is the only solution. *For every Action there is an Equal and Opposite Reaction. *Logic of Good and Bad. *Duties, Responsibilities verses Luxuries and Pleasures. *Beggars!

CORE-JAVA (Exceptions)

*[READ: Why-JAVA] *[Start-Learning-JAVA] *[Why-Java's-Hot] *[Start-Using-LINUX] *[Java-Q-&-A] *[Question] *[Java-SE-6-Doc] *[Struts-Doc] *[Java-Tutorial-Index] *[Java-Certification]
*[Tech.] *[Struts.] *[Servlet.] *[JSP.] *[EJB.] *[JNDI-JMS] *[SQL.] *[JDBC.]
CORE-JAVA: *[OOP] *[CLASS] *[ABSTRACT] *[EXCEPTIONS] *[THREADS] *[UTILS] *[PACKAGES] *[JVM] *[CASTING] *[NETWORKING] *[RMI-XML] * Add to Google

* What is the purpose of garbage collection in Java, and when is it used? (garbage)
A: Garbage collection is known for Automatic Memory Management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the existing objects. In Java, it is good idea to explicitly assign null value to a variable, thus by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee as to when all the objects will be garbage collected. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes "UnReachable" to the program in which it is used. (GC Tuning.) (Reducing GC time.)

* Can an object be garbage collected while it is still reachable? (garbage)
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.

* Can an object’s finalize() method be invoked while it is reachable? (garbage)
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.

* Can an unreachable object become reachable again? (garbage)
A: An unreachable object may become reachable again when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. The finalize method may take any action, including making this object available again to other threads. The purpose of finalize, is to perform cleanup actions before the object is discarded.

* If an object is garbage collected, can it become reachable again? (garbage)
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

* Does garbage collection guarantee that a program will not run out of memory? (garbage)
A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

* What is the purpose of finalization? (garbage)
The purpose of finalization is to give an unreachable object the opportunity to perform any "cleanup processing" before the object is garbage collected.

* How many times may an object's finalize() method be invoked by the garbage collector? (garbage)
An object's finalize() method may only be invoked once by the garbage collector.

* What are Checked and UnChecked Exceptions? (exception)
A: A checked exception is a SUBCLASS of EXCEPTION (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be THROWN. eg, IOException thrown by java.io.FileInputStream's read() method. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. (different exceptions)
* Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses are also unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
Checked exceptions must be caught at compile time. UnChecked Runtime exceptions do not need to be. Note: THROWABLE is the super class of ERROR and EXCEPTION. RUNTIMEEXCEPTION is a subclass of Exception.
* ERROR is a third kind of UnChecked exception. In case of ERROR the application usuall
y prints a stack trace and exits. Errors often CANNOT be caught. (download java examples)

* What are runtime exceptions? (unchecked exception)
A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

* What class of exceptions are generated by the Java run-time system? (unchecked exception)
The Java runtime system generates RuntimeException and Error exceptions.

* What happens if an exception is not caught? (checked exception)
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. It is called by the JVM when a thread in this thread group stops because of an uncaught exception.

* Which arithmetic operations can result in the throwing of an ArithmeticException? (exception)
Integer "divide by zero" that is, "/" and "%" can result in the throwing of an ArithmeticException.


* What is user defined exception? (checked exception)
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending the "Exception" class.

* How to create custom exceptions? (checked exception)
A: Our class should extend the class Exception, or some more specific type there of. EXCEPTION
is a subclass of THROWABLE.

* What is the catch or declare rule for method declarations? (checked exception)
A: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

* What are checked exceptions? (exception)
A: Checked exception are those which the Java compiler forces us to CATCH. e.g. IOException are checked Exceptions.

* What is the difference between Error and an Exception? (exception)
A: An Error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These are JVM errors and we can not repair them at runtime.
While Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

* If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? (exception)
A: One can not do anything in this scenario. Because Java does not allow multiple inheritance and does NOT provide any exception INTERFACE as well.

* How does an exception permeate through the code? (exception)
A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

* What are the different ways to handle checked exceptions? (exception)
A: There are two ways to handle exceptions, (1) By wrapping the desired code in a TRY block followed by a CATCH block to catch the exceptions. (2) List the desired exceptions in the THROWS clause of the method and let the caller of the method handle those exceptions.

* What is the basic difference between the 2 approaches to exception handling:
(1) TRY-CATCH block and (2) specifying the candidate exceptions in the THROWS clause? Which approach should be used when? (checked exception)
A: In the first approach as a programmer of the method, we are dealing with the exception. This is fine if you are in a best position to decide what should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

* Can an exception be rethrown? (exception)
Yes, an exception can be rethrown.

* What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution? (checked exception)
A method's throws clause must declare any checked exceptions that are not caught within the body of the method.

* How to Retrieve Warnings? (exception)
SQLWarning objects are a subclass of SQLException that deal with database connection warnings. Warnings do not stop the execution of an application, as exceptions happen they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, or to a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which must be invoked in order to see the first warning reported on the calling object.
SQLWarning warning = stmt.getWarnings();
-if (warning != null) {
--while (warning != null) {
--System.out.println("Message: " + warning.getMessage());
--System.out.println("SQLState: " + warning.getSQLState());
--System.out.print("Vendor error code: ");
--system.out.println(warning.getErrorCode());
--warning = warning.getNextWarning(); } }
(compile online)

* What should we do, if we want an object of our class to be thrown as an exception object? (checked exception)
A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
Only objects that are instances of this class can be thrown by the throw statement or can be the argument type in a catch clause. throw MUST be declared in a try block.
(Ex:) public class Exp {
--public static void main(String[] args) { new Exp(); }
--public Exp() {
---try { int size=0; System.out.println("In TRY");
---cantBeZero(0); }
---catch (MyError t1) { System.out.println("In CATCH 1"); } }
--public void cantBeZero(int i) throws MyError { if (i == 0) { throw new MyError(); } } }
Below is the subclass of Throwable class.
class MyError extends Throwable { // it can extend either Exception or Error also.
--MyError() { System.out.println("In MyError"); } }
(compile online)

* What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement? (catch)
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
The catch blocks catches the exceptions of try block and thus allows the program to continue its execution.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.

* Can try statements be nested? (catch)
Yes it can be. Nested try-catch statements are compiled very much like a try statement with multiple catch clauses:
--void nestedCatch() {
---try {
----try { tryItOut(); } // try within try
----catch (TestExc1 e) { handleExc1(e); }
---} catch (TestExc2 e) { handleExc2(e); }
--}
(compile online)

* How does a try statement determine which catch clause should be used to handle an exception? (try-catch)
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 exception is executed. The remaining catch clauses are ignored.
Each catch block is an exception handler and handles the type of exception indicated by its argument. Appropriate catch block will be called depending on the exception thrown. Checked exceptions can be thrown within the try statement.
try { }
catch (ExceptionType1 name1) { }
catch (ExceptionType2 name2) { }

* What classes of exceptions may be caught by a catch clause?
(try-catch)
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. (checked and unchecked)
The Throwable class is the superclass of all errors and exceptions. Only objects that are instances of this class can be thrown by the throw statement or can be the argument type in a catch clause. ERROR and EXCEPTIONS classes are the subclasses of THROWABLE class.

* Is it necessary that each try block must be followed by a catch block? (try-catch)
A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

* If I write return at the end of the try block, will the finally block still execute? (
try-catch)
A: Yes even if we write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

* What is the difference between final, finally and finalize? (try-catch)
FINAL - keyword used to declare constants.
FINALLY - keyword handles exception.
FINALIZE - helps in garbage collection. (Examples)
Finalize method is called by the garbage collector on an object. The call System.gc() is effectively equivalent to the call: Runtime.getRuntime().gc()

* If I write System.exit (0); at the end of the try block, will the finally block still execute? (try-catch)
A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n)

* Is it true that the code in a finally clause will never fail to execute? (try-catch)
Using System.exit(1); in try block will NOT allow finally code to execute.
System.exit(n) processes return zero(0) if there is NO error and any other value if there is an error. The parameter tells why the program is being terminated.

* What is the purpose of the finally clause of a try-catch-finally statement? (try-catch)
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.


Read: Peace Home Download Music Prayers Life Is Beautiful

*Realizations. *Realizations In Real Life. *Amazing Constructive Vibrations. *Astrology. *Creating Leaders. *How ideas are concluded and decisions are materialized. *Relationships & Partnerships. *The path of victory. *An attempt for definition. *Speak with a heart. *These are contagious. *Happy kingdom. *MIRACLES. *Better to create one ! *Cast, God and religion ! *Things become inevitable ! *We are all looking for! *Phase of Life. *Destiny, Karma and God. *Struggle, perfection and Money. *Independence and Freedom. *Relationships and Happiness.

About Me

My photo
Simple guy who believes in being Competitive rather than being Ambitious. Persistence to be constructive, without frustrations, is a good purpose of life.
.

* * * * * * * * * * * * *

MeetUp Message Board:
Read: Wishes-and-Prayers. *Issue-of-Illegal-Immigration-&-Happy-Kingdom. *The-New-York-Hillary-Rodham-Clinton *Cast-God-Religion! *Barack-Obama-Meetup *Duty- Responsibility-Law-and-Order *John-Edwards-One-America *Good-Wishes-Life-is-Meaningful-&-Beautiful *Dennis-Kucinich-Meetup *Let-there-be-peace! *Bill-Richardson-for-President-2008 *Logic-of-Good-and-Bad-convert-bad-to-good *MORAL-STORY-Elephants-held-by-small-ropes.
* * * * * * * * * * * * *

Realizations.
*Realizations-In-Real-Life-Please-be-gentle-and-humble. *Manoj-D-Kargudri. *Amazing-Constructive-Vibrations. *Astrology. *Creating-Leaders. *How-ideas-are-concluded-and-decisions-are-materialized. *“Relationships-in-Life”-“Partnerships-in-Life”. *The-path-of-victory-the-path-of-life-winning-in-looseing. *An-attempt-for-definition. *Speak-with-a-heart. *These-are-contagious. *Key-to-happy-kingdom. *MIRACLES. *Better-to-create-one! *Cast-God-and-Religion! *Manoj-Kargudri. *Things-become-inevitable! *We-are-all-looking-for! *Phase-of-Life. *Destiny-Karma-and-God. *Struggle-perfection-and-Money. *Independence-and-Freedom. *Relationships-and-Happiness.
* * * * * *

Quotes.
*Love-Compassion-Tolerance-Forgiveness-Courtesy. *Manoj-D-Kargudri. *True-to-Heart-going-back-to-Basics!
* * * * * *

Puzzles-Riddles-Think.
*River-Crossing-Puzzles-Brain-Teasers. *Manoj-Kargudri. *Perpetual-Motion-Gravity-and-Kinetics. *Illusions-Paradoxes-Perpetually-ascending-staircase. *Milk-man-with-no-measureing-jar. *Amazing-Horoscope-Mind-Reader. *Find-the-hidden-images-in-these-STEREOGRAMS. *Are-they-12-or-13? *What-would-U-do? *ABCD-Four-Digit-Number. *10-Digit-Number. *4-QUESTIONS...GOOD-LUCK! *Think-Wise.
* * * * * *

Prayers.
*God-gave-us-everything-we-ever-needed. *Good-Wishes. *Manoj-Kargudri. *Love-Compassion-Tolerance-Forgiveness-Courtesy. *Interview-With-God! *He-is-the-one! *Candle-of-Hope! *Let-there-be-Peace! *Manoj-Kargudri.
* * * * * *

Perceptions.
*Issue-of-Illegal-Immigration. *To-which-religion-does-this-universe-belongs-to? *Law-and-order-helps-to-maintain-justice. *Implementing-regulations-by-justice. *Putting-our-sincere-efforts. *Religion-and-cast. *Impact-of-reservation-based-on-religion-and-cast. *Free-and-Fare-Education-system-Electoral-system.
* * * * * *

Stories.
*The-Monkey’s-Justice-for-two-cats. *The-Blind-Men-And-The-Elephant. *Manoj-Kargudri. *Two-rich-merchants-and-a-thief. *Healing-is-contagious. *Two-saints-in-a-market-place. *A-Terrible-Fight-Between-Two-Wolves. *Hen-that-laid-golden-eggs. *Healing-forgiveness-and-affection. *Elephants-held-by-small-ropes. *Story-of-Punyakoti-the-strength-of-truth. *What-is-the-reason? *Reply-Depends-on-the-Question. *Critical-mass-Experiment. *The-Brahman's-Wife-and-the-Mongoose. *The-Boy-Who-Cried-Wolf. *Difference-between-Heaven-and-Hell! *Freedom-and-Prison! *It's-in-Your-Eyes!
* * * * * *

Jokes.
*Please-listen-to-me. *The-Silent-Treatment! *Surgeon-Vs-Mechanic. *Manoj-Kargudri. *God's-doing-a-lot-better-job-lately.
* * * * * *

The-Bitter-Truth.
*Duty-Responsibility-Law-and-Order. *"Happy-Kingdom"-proudly-proclaimed-as-"Paradise". *Trying-to-learn-something-for-the-first-time. *Time-is-the-only-solution. *For-every-Action-there-is-an-Equal-and-Opposite-Reaction. *Logic-of-Good-and-Bad. *Manoj-Kargudri. *Duties-Responsibilities-verses-Luxuries-and-Pleasures. *Beggars!
* * * * * *

Life-is-Beautiful.
*Creating-successful-constructive-personality. *Why-God-Gave-Us-Friends? *Way-to-Paradise. *Creating-the-Beautiful-World. *Doing-the-job-of-goodness. *Life-is-Meaningful. *Manoj-Kargudri. *The-A-to-Z-for-Goodness. *Life-is-full-of-Tests. *History-Proves-That. *Love-in-different-forms. *True-to-the-heart.
* * * * * *

Prayers-To-Worship.
*Please-do-not-leave-me-ever. *Let’s-make-it-happen. *Faith-in-Patience. *The-only-one-I've-got. *Someone-somewhere. *How-I-Love-You. *Will-You? *Successful-Life. *Manoj-Kargudri. *Please-say-something. *Way-to-Paradise. *My-Everything.
* * * * * *

Friendship.
*Life-Still-Has-A-Meaning. *Heavenly-Garden. *GOD-SPEAK-TO-ME! *Why-God-Made-Friends? *I-asked-the-Lord! *A-Best-Friend! *Why-GOD-Gave-Us-Friends? *Portrait-of-a-Friend. *Friends-till-the-end. *Some-Assorted! *Forever-Friends. *What-is-a-friend!
* * * * * *

Winning-Publications.
*Significance-of-Nava-ratna (Nava-Graha). *Amazing-Constructive-Vibrations. *Manoj-Kargudri. *The-piercing-of-the-ears (karnavedha) . *Nature-Cure. *Steps-to-improve-work-place. *Steps-Involved-In-Relationships. *Some-of-the-aspects-which-materialize-the-relationships.
* * * * * *

Music-Download.
*Bhakti-Songs. *Manoj-Kargudri. *English-Songs. *Gazal-Bhajan-Hindi. *Hindi-Life. *Hindi-Love. *Hindi-Old-Kishore. *Hindi-Old-Mukesh. *Hindi-Old-Songs. *Hindi-Rock. *Hindi-Pops. *Instrumental. *Vocal-Ragas.
* * * * * *

Technology.
*READ: Why-JAVA *Manoj-Kargudri. *Start-Learning-JAVA *Why-Java's-Hot *Start-Using-LINUX *Java-Q-&-A *Question *Java-SE-6-Doc *Struts-Doc *Java-Tutorial-Index *Java-Certification *Tech. *Struts. *Manoj-Kargudri. *Servlet. *JSP. *EJB. *JNDI-JMS *SQL. *JDBC. *CORE-JAVA: *OOP *CLASS. *Manoj-Kargudri. *ABSTRACT *EXCEPTIONS *THREADS *UTILS *PACKAGES *JVM *CASTING *NETWORKING *RMI-XML
* * * * * *

MUSIC-DOWNLOAD.
*Hindi-Vocal-Raga. *Hindi-Remix-Rock. *Hindi-Old-Songs. *Hindi-Mukesh-Mohd-Rafi-Songs. *Hindi-LOVE-Songs. *Hindi-Remix-LIFE. *English-Rock-Songs. *Kannada-Janapada-Geete. *Kannada-Film-Songs. *Kannada-Devotional-Songs. *Instrumental-Music. *Manoj-Kargudri. *Hindi-Pop-Songs. *Hindi-Bhakti-Songs. *Hindi-Kishore-Kumar-SAD. *Hindi-Kishore-Kumar-JOY. *Hindi-R-D-Burman. *Hindi-Gazals. *English-Soft-Songs.
* * * * * *

Add to Google