Sunday, August 9, 2009

Imortant Revision Notes for Classes and Constructors in Java

Class Declaration--> Syntax of class declaration is as follows:

(class modifiers) class (class name)
               (extends clause) (implements clause)  // Class header

{ // Class body
    -- field declarations
     --method declarations
     --nested class declarations
     --nested interface declarations
     --constructor declarations
     --initializer blocks
}

Methods of a Class--> They are the class members and are also called operations. They define behaviour of the class. 

Syntax of their declaration is as follows:

(method modifiers) (return type) (method name) ((formal parameter list))
         (throws clause) // Method prototype


{ // Method body
    --local variable declarations
    --nested local class declarations
    --statements
}

Method Overloading--> This means several methods share same name but have different argument list.

Constructor--> It is a special method which is used to initialize state of an object when it is created using new operator. 

It has following syntax:

(accessibility modifier) (class name) ((formal parameter list))
            (throws clause) // Constructor header
  { // Constructor body
    --local variable declarations
    --nested local class declarations
    --statements
  }

However there are few constraints for a method to be constructor:
a) Their modifiers can be only accessibility modifiers.
b) They cannot have a return type
c) Their should be same as the class name.

Default Constructor--> It is the constructor with no argument. Its syntax is: classname()

Implicit Default Constructor-->If no constructor is defined in the class, then implicit default constructor is provided by java.

Its syntax is:

classname(){super();}

Sunday, July 12, 2009

Important Points to Remember in Java

Method Parameters:
Types of Method Parameters in Java:

a) Formal Parameters-->They are the parameters defined in the method definition.


b) Actual Parameters--> They are the parameters defined in the method call.


c) Final parameter--> If a formal parameter is declared to be final, then its value cannot be changed during its lifetime in the method body.



Note: Widening, narrowing, type promotion rule applies to the parameter passing as well. They are equivalent to assignment conversions.


***************************************
2. Arrays: 


a) Array--> Its a collection of homogeneous data elements.

b) Array Declaration-->Syntax for array declaration is as follows:


    (datatype)[](arrayname) or (datatype) (arrayname)[]

c) Array Construction--> This means allocating space to the array in computer memory. Its syntax is:


  (arrayname)=new (datatype)[(arraysize)]

d) Value assignment--> This means assigning values to the array elements.

e) Array Initialization--> Java provides the means of declaring, constructing and explicitly initializing an array in one declaration. Its syntax is:


(datatype)[](arrayname)={(array initialization list)};








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


3. Anonymous Array--> They are used to initialize the array objects which are already declared. like:
   int a[];
 a=new int[]{1,5,5,3,9,7,3}; we cannot use a={1,5,5,3,9,7,3}; to initialize an array already declared.





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

Tuesday, June 16, 2009

Java More Definations and Concepts

Types of variables



1) Instance variables--> They are non static members of a class. Every object of a class has its own copy of these variables. Their values exist as long as object containing them exists. Initialized to default valued by default.

2)Static Variables-->They belong to the class and are created when class is loaded first time at runtime.They exists as long as class exists. Initialized to default value by default.

3)Local variables-->Created in method or block and executed for method or block. After the execution of method or block, they are no more accessible. They should be explicitly initialized in a non conditional statement, before being used.


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


Main method--> This is the method where from execution of a program can start. It must be public, static and void. It should be public so that it can be accessed by Java Interpreter. It should be static so that It can be accessed without object of a class being created. public and static keywords can appear in any order.


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


Typecasting and converstions:


1) Narrowing--->Conversion of broader datatype to narrower datatype is called narrowing. It results in loss of magnitued information. This means bits from the left of the binary respresentation are truncated to fit in the destination variable. Like conversion from float to int. In this explicit cast is required.


2)Widening--->Conversion from narrower type to the broader one is called widening. In this no explicit cast is required.


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


Unary Numeric Promotion--> In a unary operator if type of operand is narrower than int, it is converted to int. It is applicable to +,-,>>,<<,>>>,~ and expressions in array initialization and array indexes. Note: not applicable to ++, -- operators.


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


Binary Numeric Promotion--> In binary numeric promotion type of the expression is promoted to the type of broadest operand which is atleast an int.


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

String Concatenation-->When an operand is added to a string object using '+' sign, then any of the following cases take place:


a) If other operand is primitive datatype(int, long etc) its value is converted to the string object with string representation of its value.


b) Values like true, false and null are also converted to String objects their corresponding string respresentation. A reference variable with null value is also converted to String with string representation as "null"


c) For all other references, String is constructed by calling toString method of the referred object.


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


Conditional Operators:

They are used to check the condition of an expression.


&& --> Shortcircuit AND


& --> Bitwise AND

|| --> Shortcircuit OR

| --> Bitwise OR

Difference between && and & is as given below:


In case of && if first expression is false then next condition is not checked. However in case of & if first condition is false, still next condition is checked.
! --> NOT

It  is used to invert the value of a boolean expression. true is changed to false and vice versa.

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


Integer Bitwise operators:


~ Bitwise Compliment--> Inverts all bits of an operand


& Bitwise AND--> Returns 1 if both corresponding bits of two operands are 1, else returns 0.


! Bitwise OR--> Returns 0 if both corresponding bits of two operands are 0, else returns 1.


^ Bitwise Exclusivley OR--> Returns 1 if one bit of the two operands is 0 and another one is 1, else returns 0.


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


Shift Operators


a>>n--> Right shift carry sign bit


a<--> Left shift zero fill.


a>>>n--> Right shift zero fill.


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

Wednesday, June 10, 2009

Java Important Terms, Definations and Concepts

Features of Java

--------------------------------


1) Encapsulation--> This means grouping of data members and member functions into single unit called class. This also means grouping of related entities into single unit. For ex grouping of classes, interfaces and subpackages into single package.

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

2)Polymorphism-->This means one interface many forms.We can also so existing in many forms. This can be of two type:


a) Static Polymorphism--> This means specifying things at compile type. For example method overloading. We specify at compile time by passing arguments that which method to be called.


b)Dynamic Polymorphism--> This means specifying things at runtime. For example method overriding. Say for ex: a super class variable can have object of super class or any of its sub classes. If we call an overriden method, then its the method of the class whose object is referred by super class variable at runtime.

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

3)Inheritance--> It is the fundamental mechanism of creating a new class from an existing one. This way new class has properties of base class as well as new class. This is called is-a relation. This should be used where is-a relation is maintained throughout the lifecycle of the objects involved.

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


4)Aggregation-->This means creating a new class using existing class as datamember of the new class. This is called has-a relation.


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


5)Class--> A class is a blueprint or category of objects. A class specifies properties and behaviour of a an object. The properties of a class are called attributes and defined by fields in Java. The behaviour of a class is operations and defined by methods in Java. They both collectively are called members.


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


6)Object--> It is an instance of a class. It is constructed using blueprint of the class.


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


7)Object References--> Its same as object variable.


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


8)Static Members--> Static members belong to the class and not to a particular object.


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


9)Instance Members--> They belong to a particular object.Each object has its own copy of instance  member.


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


10) Static block--> This is the block contained in a class and is executed each time class is loaded. That is its called even if a class contains no main method and we execute the class.It is generally used to initialize static members.


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


11)Non Static Block--> It is called each time an object of a class is created. If static, non-static and constructor are there in the class, then they are executed in following order: static blok-->non-static block--> constructor.


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


There are two ways of defining a new class from an existing class, inheritance and aggregation.






Inheritance-->This means defining a new class from an existing one, which contains its own properties, apart of properties from a base class. Its an "is a relation" in uml notation.






Aggregation-->In this approach a new class is constructed using objects from other classes as constituent or members of this class.


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


12)Lexical tokens--> The low-level language elements are called lexical tokens and are used to construct more complex language constructs. identifiers, numbers, operators and special characters are called lexical tokens.


*****************************************
13)Keywords--> Keywords are reserved identifiers in a language and cannot be used to denote other entities.


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


14) Literal--> It denotes a constant value.


String Literal example>"Hello","world"


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


Primitive Datatypes and Literal Examples:


Integer Literal example-> 2,3


Floating Point Literal example-> 2.45,3.15


Boolean Literal example--> true, false


Character literal example-->'a','2','\u002'(four digit hexadecimal number from \u0000 to \uffff), '\121'(octal number from \0 to \377)


Long Literal example-->10l,20l


double literal example-->3.21d,5.54d


octal literal example-->012,07


Hexadecimal literal example-->0x1b,0x10

Thats all for the day !!!!

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

Friday, May 15, 2009

Java Mock Exam Questions with detailed answers

Q1     Given:

 class J {
  private static int notFinalized;
  public static int notFinalized() {return notFinalized;}
  private K k;
  private int name;
  public int name() {return name;}
  public J(K k, int i) {this.k = k; name = i; notFinalized++;}
  public void finalize() {
    synchronized (k) {
      System.out.print(name);
      notFinalized--;
      k.notify();
    }
  }
}

class K {
  private void m1() {
    J j = null;
    for (int i = 0; i < 5; i++) {
      j = new J(this, i);       // 1
    }
    Runtime.getRuntime().gc();  // 2
    synchronized (this) {
      while (J.notFinalized() > 0) {
        try {wait();} catch (InterruptedException ie) {}
      }
    }
  }
  public static void main(String[] args) {
    new K().m1();
  }
}


When the processing of line 2 begins how many objects of type J that were created at line 1 are eligible for garbage collection?

    (1)     0
    (2)     1
    (3)     4
    (4)     5
    (5)     Can not be determined without more information
    (6)     Compiler error
    (7)     Run time error
    (8)     None of the above
       
    Answer : 3
    Explanation :

 Method K.m1 creates five objects of type J. Each instance has a name represented by an integer between 0 and 4 inclusive.
If the garbage collector does not run then the program will produce no output.If the garbage collector does run then the output of the program could be a series of integers that are the names of four of the five objects.
As each new object is created its reference is assigned to the reference variable j.The previously referenced object then becomes eligible for garbage collection. The last object created, 4, is not available for garbage collection until method m1 runs to completion.
The while loop in the synchronized block will never complete because J.notFinalized will never return zero.
 This program is intended to provide a working example of garbage collecting objects referenced by local variables.
       
Q2    What is the output of the following code when compiled and run? Select two correct answers


1 public class Sample {
2    public static void main(String[] args){
3        int y=0;               
4        int x=z=1;   
5        System.out.println(y+","+x+","+z);
6    }
7 }



    (1)     Prints 0,1,1
    (2)     Error during compilation at line 3
    (3)     Prints 0,0,1
    (4)     Error during compilation at line 4
    (5)     Error during compilation at line 5
       
    Answer : 4,5
    Explanation :

Variable z is not declared, thus, z cannot be resolved on lines 2 and 3. In Java, z cannot be declared that way. In order to get this code to compile, we have to write either:
int z=1,x=z;
Or
int z=1;
int x=z;
Or
int z=1;
int x=1;
       
Q3     What is the output of the following code when compiled and run? Select one correct answer


1 public class Sample {
2    public static void main(String[] args){
3        int j = 017;
4        int i = (byte)j >> 2;
5        System.out.println(Integer.toBinaryString(i));
6    }
7 }



    (1)     Prints 3
    (2)     Error during compilation at line 4
    (3)     Error during compilation at line 5
    (4)     Prints 11
    (5)     Prints 0
       
    Answer : 4
    Explanation :

First off, 017 is an octal integer literal having the decimal value 15. Second, the cast to byte only applies to j and not to j >> 2 as a whole. Thus, j is downcast to byte and then upcast to int again before the shifting.Briefly, the cast has no effect here. Then, the binary sequence of 15 is 00000000 00000000 00000000 00001111, which, shifted 2 bits to the right, yields 00000000 00000000 00000000 00000011. Finally, the binary sequence, 11, is printed. Note that the prefixed 0's are dismissed.
       
Q4    Select three correct statements:

    (1)     The garbage collection thread cannot outlive the last user thread
    (2)     The garbage collection can be forced by invoking System.gc().
    (3)     The garbage collection thread is a non-deamon thread
    (4)     The finalize() method is invoked at most once by the JVM for any given object
    (5)     The finalize() method may resurrect the object upon which it has been invoked
       
    Answer : 1,4,5
    Explanation :

The garbage collection thread is a deamon thread. The latter die when there are no more users threads running. The garbage collection cannot be forced.
       
Q5     What is the output of the following code when compiled and run? Select one correct answer.

import java.io.*;
public class Mohit{
    public static void main(String[] args) {
        MohitSub myref = new MohitSub();
        try{
            myref.test();
        }catch(IOException ioe){}
    }
    void test() throws IOException{
        System.out.println("In Mohit");
        throw new IOException();
    }
}
class MohitSub extends Mohit {
    void test() {
        System.out.println("In MohitSub");
    }
}



    (1)     Prints:

    In MohitSub

    (2)     Prints:

    In Mohit

    (3)     Prints:

    In Mohit
        In MohitSub

    (4)     Prints:

    In MohitSub
        In Mohit

    (5)     The code does not compile
       
    Answer : 5
    Explanation :

The code does not compile because no IOException is thrown when invoking myref.test(). Note that myref's declared and runtime types are MohitSub and thus no dynamic lookup will be performed. However, if you change the declared type to Mohit, the code will compile and the correct answer would be A because method test() isoverridden in MohitSub
       
Q6    What is the output of the following code when compiled and run with the following command line: java Friends two three? Select two correct answers.

public class Friends {
    public static void main(String[] args) throws Exception {
        int i=2;
        boolean b = true;
        throw new Exception("Values are:"+(b!=b)+","+(i=args.length)+","+(b=i==2));
    }
}



    (1)     The exception message is Values are:false,3,true
    (2)     The exception message is Values are:true,2,false
    (3)     The exception message is Values are:false,2,true
    (4)     The final value of b is false
    (5)     An exception is thrown at runtime
       
    Answer : 3,5
    Explanation :

Do not mix b!=b and b=!b. In the former, we check if b's value is different from b's value (?!) which is clearly false. In the latter, we assign b's opposite value to itself, that is, if b is true, then after b=!b, b ends up being false.Moreover, be aware that b=i==2 is evaluated as b=(i==2) because operator = has the lowest precedence. Finally, note that the arguments to the Exception constructor are evaluatedfrom the left to the right. First, b!=b is evaluated, then i=args.length (args.length is 2, so i keeps its value), and finally, b=i==2.
       
    Q7    Select two correct statements about the code given below?


class A{}
class B extends A implements E{}    //line 1
class C extends A{}
class D extends B{}
interface E{}
public class Question07 {
    public static void main(String[] args) {
        A a = new D();    //line 2
        C c = new C();    //line 3
        E e = (E)a;    //line 4
        B b = (B)e;    //line 5
    }
}



    (1)     The code compiles without error and runs fine
    (2)     Compilation error on line 1 because interface E is not yet declared (forward-referencing)
    (3)     Compilation error on line 4 because class A does not implement interface E
    (4)     The cast on line 4 is mandatory
    (5)     The cast on line 5 is not mandatory
       
    Answer : 1,4
    Explanation :

First, pay attention to the class hierarchy (B and C are sibling classes!!) Then, there is no such thing as forward-referencing issues when using interfaces declared later in the compilation unit.On line 4, we are dealing with an object whose runtime type is D which implements interface E. The cast is mandatory, though, since the reference type (A) is not assignmentcompatible with the reference type E. The cast on line 5 is mandatory for the same reasons.
       
Q8     How many objects are eligible for garbage collection immediately after line 1? Select one correct answer.


public class HomeGC {
    public static void main(String[] args) {
        HomeGC tGC = new HomeGC();
        tGC.doSomething();    //line 1
        Thread.sleep(20000);
    }

    public void doSomething(){
        Object[] objArray = new Object[2];
        for(int i = 0 ; i < objArray.length ; i++) {
            objArray[i] = new Object();
        }
    }
}



    (1)     0
    (2)     1
    (3)     2
    (4)     3
    (5)     4
       
    Answer : 4
    Explanation :

We declare an array of Object of length two. We then initialize each element to a new Object. We have 2 objects in the array and the array itself (which is an object, too!), that makes 3.
       
Q9     What is the output of the following code when compiled and run? Select one correct answer.


public class ABC {
    public static void main(String[] args) {
        try {
            int i = (int)(Math.random()*10);
            if(i<=5)
                System.out.println("i = "+i);
            else
                throw new Exception("i > 5");
        } catch (Exception e){
            System.err.println(e.getMessage()+" (i="+i+")");
        }
    }
}



    (1)     The output cannot be determined
    (2)     Compilation error
    (3)     An exception is thrown at runtime
    (4)     Output is i = 2
    (5)     Output is i > 5 (i=6)
       
    Answer : 2
    Explanation :

The code does not compile because i (declared in the try block!) is not in scope when accessed from the catch block.
       
Q10     What is the output of the following code when compiled and run? Select one correct answer.


public class ABCSample {
    public static void main(String[] args) {
        new ABCSample().doSomething();
    }

    public void doSomething(){
        int i=5;
        Thread t = new Thread(new Runnable(){
            public void run(){
                for(int j=0;j<=i;j++){
                    System.out.print(" "+j);
                }
            }
        });
        t.start();
    }
}



    (1)     Prints 0 1 2 3 4
    (2)     Compilation error
    (3)     No output
    (4)     IllegalThreadStateException is thrown at runtime
    (5)     Prints 0 1 2 3 4 5
       
    Answer : 2
    Explanation :

The code does not compile because the anonymous inner class (new Runnable(){...}) tries to access the non-final local variable i.

Sunday, April 19, 2009

Exam Objectives and Syllabus for SCJP 1.6


Section 1: Declarations, Initialization and Scoping

a)Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

b)Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.

c)Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

d)Develop code that declares both static and non-static methods, and - if appropriate - use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list.

e) Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.

f) Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.

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

Section 2: Flow Control

a) Develop code that implements an if or switch statement; and identify legal argument types for these statements.

b)Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.

c)Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.

d)Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.

e)Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.

f) Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.

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

Section 3: API Contents

a) Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.

b)Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console.

c) Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.

d) Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.

e) Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.

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

Section 4: Concurrency

a)Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.

b) Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.

c) Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.

d)Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.

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

Section 5: OO Concepts

a)Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.

b) Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.

c)Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.

d) Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors.

e) Develop code that implements "is-a" and/or "has-a" relationships.

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

Section 6: Collections / Generics

a)Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.

b)Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.

c)Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces.

d)Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.

e)Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.

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

Section 7: Fundamentals

a)Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.

b)Given an example of a class and a command-line, determine the expected runtime behavior.

c)Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.

d)Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method.

e)Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.

f)Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

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

Thursday, March 12, 2009

Important Java interview Questions

Q1. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.

Q2. What is the difference between a while statement and a do statement?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) 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 loop body at least once.

Q3.What is the Locale class?
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Q4.Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Q5. Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.

Q6.What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example
int i = 1000;
long j = i; //Implicit casting
Is sizeof a keyword in java?
The sizeof operator is not a keyword.

Q7.What is a native method?
A native method is a method that is implemented in a language other than Java.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

Q8.What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

Wednesday, February 11, 2009

Important Java interview Questions

What if the static modifier is removed from the signature of the main method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. 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. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

  • The global variables breaks the referential transparency
  • Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

Sunday, January 18, 2009

Java Interview Questions

Q1. What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.

Q2. What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

Q3. If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()

Q4.What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Q5.Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

Q6.What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables - the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
public class EqualsTest {

public static void main(String[] args) {

String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println("== comparison : " + (s1 == s5));
System.out.println("== comparison : " + (s1 == s2));
System.out.println("Using equals method : " + s1.equals(s2));
System.out.println("== comparison : " + s3 == s4);
System.out.println("Using equals method : " + s3.equals(s4));
}
}

Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google