Arulkumaran Kumaraswamipillai, Sivayini Arulkumaran, “Java/J2EE Job Interview Companion - 400+ Questions & Answers”ISBN:1411668243 | April 5, 2007 | 356 pages | PDF | 3.5MB
A place for Java Beginners and Java Developers.
Arulkumaran Kumaraswamipillai, Sivayini Arulkumaran, “Java/J2EE Job Interview Companion - 400+ Questions & Answers”Posted by Shahid 0 comments
Labels: Java E-Books, SCJP and Interview Questions
Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 (CX-310-055)
The Sun Certified Programmer for Java 2 Platform 5.0 certification exam is for programmers experienced using the Java programming language.
Exam number: CX-310-055
Available at: Authorized Prometric testing centers
Prerequisites: None
Other exams/assignments required for this certification: None
Exam Type: Multiple choice and Drag and Drop
Cost: 150 USD
Number of questions: 72
Pass score: 59% (43 of 72 questions)
Time Limit: 175 minutes (2 hrs and 55 minutes)
Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 Upgrade Exam (CX-310-056)
The Sun Certified Programmer for Java 2 Platform 5.0 certification exam is for programmers experienced using the Java programming language.
Exam number:CX-310-056
Available at:Authorized Prometric testing centers
Prerequisites:Successful completion of previous version of Sun Certified Programmer for Java 2 Platform exam
Other exams/assignments required for this certification:None
Exam Type:Multiple choice and Drag and Drop
Cost:100 USD
Number of questions:46
Pass score:58% (27 of 46 questions)
Time Limit:105 minutes (1 hr and 45 minutes)
Posted by Shahid 0 comments
Labels: SCJP and Interview Questions
Generics
Generics were added to the Java language syntax in version 1.5. This means that code using Generics will not compile with Java 1.4 and less.
Java was long criticized for the need to explicitly type-cast an element when it was taken out of a "container/collection" class. There was no way to enforce that a "collection" class contains only one type of object. This is now possible since Java 1.5.
In the first couple of years of Java evolution, Java did not have a real competitor. This has changed by the appearance of Microsoft C#. With Generics Java is better suited to compete against C#.
What are Generics?
Generics are so called because this language feature allows methods to be written generically, with no foreknowledge of the type on which they will eventually be called upon to carry out their behaviors. A better name might have been type parameter argument. Because, it is basically that, to pass a Type as a parameter to a class at creation time.
When an object is created, parameters can be passed to the created object, through the constructor. Now with Generics, we can also pass in Types. The type-place-holders will be replaced with the specified type, before the object is created.
Type parameter arguments can be set:
for a class
When an object is created from that class the type-parameter-argument will be replaced with the actual Type.
public class Person
{
private Person
...
}...// --- Create an Employee person ---
Person
...
// --- Create a Customer person ---
Person
for a method
Just like class declarations, method declarations can be generic--that is, parameterized by one or more type parameters.
static public
{
person.setPerson( obj );
}
use of generics is optional
For backwards compatibility with pre-Generics code, it is okay to use generic classes without the generics type specification thing (
Introduction
Java is a "strongly" typed language. That's why it is so easy to use. Many potential problems are caught by the compiler. One area where Java was criticized was regarding the "Container/Collection" objects. Container objects are objects that contain other objects. Before Generics were introduced there was no way to ensure that a container object contains only one type of objects. When an object was added to a container, it was automatically cast to Java Object. When it was taken out an explicit cast was needed. Normally an explicit cast is checked by the compiler.
String st = "This is a String";
...
Integer integer = (Integer) st; // --- Compilation Error --
But in the case of container classes, the compiler was not able to catch an invalid type casting.
1 Collection collString = new ArrayList();
2 collString.add( "This is a String" );
...
3 Integer integer = (Integer) collString.get(0); // --- No Compilation Error; RunTime CastException
Just looking at line 3, we do not know what type of objects collString contains. If that contains Integers then the code is fine.
The above code using Generic:
Collection<String> collString = new ArrayList<String>();
collString.add( "This is a String" );
...
Integer integer = (Integer) collString.get(0); // --- Compilation Error
collString is a container object, that can contain only String objects, nothing else, so when we get out an element it can be casted only to class that normally a String can be casted.
With Generics, Java strict type checking can be extended to container objects. Using Generics with container classes, gives an impression that a new container type is created, with each different type parameter. Before Generics:
Collection collCustomer = new ArrayList();
collCustomer.add( new Customer() );
...
Collection collObject = collCustomer; // --- No problem, both collObject and collCustomer have the same type
With generics:
Collection
collCustomer.add( new Customer() );
...
Collection(object) collObject = collCustomer; // --- Compilation Error
Both collObject and collCustomer have the same type, BUT it is against the Generic rule, that is collCustomer can contain only Customer objects, and collObject can contain only Object object. So there is an additional check to the normal type checking, the type of the parameter type has to be matched too.
Note for C++ programmers
Java Generics are similar to C++ Templates in that both were added for the same reason. The syntax of Java Generic and C++ Template are also similar.
There are some differences however. The C++ template can be seen as a kind of macro, that generates code before compilation. The generated code depends on how the Template class is referenced. The amount of code generated depends on how many different types of classes are created from the Template. C++ Templates do not have any run-time mechanisms. The compiler creates normal code to substitute the template, similar to any 'hand-written' code.
In contrast, Java Generics are built into the language. The same Class object handles all the Generic type variations. No additional code is generated, no matter how many Generic objects are created with different type parameters. For example.
Collection
Collection
There is only one Class object created. In fact, at runtime, both these objects appear as the same type (both ArrayList's). The generics type information is erased during compilation (type erasure). This means, for example, that if you had function that takes Collection
The Class
public final class Class
...
}
The T type here represents the type that is handed to the Class object. The T type will be substituted with the class being loaded.
Class
Since Java 1.5, the class java.lang.Class is generic. It is an interesting example of using genericness for something other than a container class.
For example, the type of String.class is Class
In particular, since the newInstance() method in Class now returns a T, you can get more precise types when creating objects reflectively.
Now we can use the newInstance() method to return a new object with exact type, without casting.
Customer cust = Utility.createAnyObject(Customer.class); // - No casting
...
public static
T ret = null;
try
{
ret = cls.newInstance();
}
catch (Exception e) {
// --- Exception Handling
}
return ret;
}
And the above code without Generics:
Customer cust = (Customer) Utility.createAnyObject(Customer.class); // - Casting is needed
...
public static Object createAnyObject(Class cls)
{
Object ret = null;
try
{
ret = cls.newInstance();
}
catch (Exception e)
{ // --- Exception Handling }
return ret;
}
Get exact type when getting JavaBean property, using reflection
See the following code where the method will return the exact type of the Java Bean property, based on how it will be called.
// --- Using reflection, get a Java Bean property by its name ---
public static
{
if (bean == null propertyName == null propertyName.length() == 0)
{
return null;
} // --- Based on the property name build the getter method name ---
String methodName = "get" +propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
T property = null;
try
{
java.lang.Class c = bean.getClass();
java.lang.reflect.Method m = c.getMethod(methodName, null);
property = (T) m.invoke(bean, null);
}
catch (Exception e)
{ // --- Handle exception -- }
return property;
}
Variable Argument
With Generic it is very easy to define a method with variable argument. Before generic usually passing in array was close to the variable argument. The only requirement is that the arguments in the list must have the same type.
The following code illustrates the method that can be called with variable arguments:
/**
* Method using variable argument list
* @param
* @param args
*/
public static
{
List
for (int i = 0; i <>
{
argList.add(args[i]);
}
return argList;
}
And the above method can be called with variable argument, see below:
List<String> list1 = makeAList("One", "Two", "Three");
List<String> list2 = makeAList("One", "Two", "Three", "Four");
In the above calls the arguments must be String. If we for the T, then we can pass in any kind of objects regardles of their type. See below:
List list3 = makeAList("One", 10);
Note: the number 10 in the above code will be converted (autoboxed) to Integer.
See also: java.util.Arrays.asList(T... a)
Wildcard Types
As we have seen above, generics give the impression that a new container type is created with each different type parameter. We have also seen that in addition to the normal type checking, the type parameter has to match as well when we assign generics variables.
In some cases this is too restrictive. What if we would like to relax this additional checking? What if we would like to define a collection variable that can hold any generic collection, regardless of the parameter type it holds?
Wildcard
The wildcard type is represented by the character , and pronounced Unknown, or Any-Type. This Unknown type matches anything, if it is used only by itself. Any-Type can be express also by . Any-Type includes Interfaces, not only Classes.
Posted by Shahid 0 comments
Labels: Core Java, SCJP and Interview Questions
Core Java FAQs or Interview Questions:--2
1)What is the difference between an Abstract class and Interface?
Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
-- An class can implement any number of interfaces, but subclass at most one abstract class.
--An abstract class can have nonabstract methods. All methods of an interface are abstract.
--An abstract class can have instance variables. An interface cannot.
--An abstract class can define constructor. An interface cannot.
--An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package).
--An abstract class inherits from Object and includes methods such as clone() and equals().
2)What are checked and unchecked exceptions?
Java defines two kinds of exceptions :
-->Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples - SQLException, IOxception
-->Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroException typically, programming errors.
3)What is a user defined exception?
User-defined exceptions may be implemented by
* defining a class to respond to the exception and
* embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).
The developer can define a new exception by deriving it from the Exception class as follows:
public class MyException extends Exception {
/* class definition of constructors (but NOT the exception handling code) goes here */
public MyException() {
super();
}
public MyException( String errorMessage ) {
super( errorMessage );
}
}
The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax.
throw new MyException("I threw my own exception.")
To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:
public myMethodName() throws MyException
4)What is the difference between C++ & Java?
Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..".
:* Java is multithreaded
* Java has no pointers
* Java has automatic memory management (garbage collection)
* Java is platform independent (Stroustrup may differ by saying "Java is a platform"
* Java has built-in support for comment documentation
* Java has no operator overloading
* Java doesn’t provide multiple inheritance* There are no destructors in Java
5)What are statements in JAVA ?
Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon
* Assignment expressions
* Any use of ++ or --
* Method calls
* Object creation expressions
These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.
6)What is JAR file ?
JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.
7)What is JNI ?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages.
Advantages:
* You want to use your existing library which was previously written in other language.
* You want to call Windows API function.
* For the sake of execution speed.
* You want to call API function of some server product which is in c or c++ from java client.
Disadvantages:
* You can’t say write once run anywhere.
* Difficult to debug runtime error in native code.
* Potential security risk.
* You can’t call it from Applet.
8)What is serialization ?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.
9)Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable
10)Is synchronised a modifier?indentifier??what is it??
It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Posted by Shahid 0 comments
Labels: Core Java, SCJP and Interview Questions
Core Java FAQs or Interview Questions
1)What is singleton class?where is it used?
Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.
2)What is a compilation unit?
The smallest unit of source code that can be compiled, i.e. a .java file.
3)Is string a wrapper class?
String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and vice-versa.
4)Why java does not have multiple inheritance?
The Java design team strove to make Java:
Simple, object oriented, and familiar
Robust and secure
Architecture neutral and portable
High performance
Interpreted, threaded, and dynamic
The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple).
In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache.
5)Why java is not a 100% oops?
Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question..
6)What is a resource bundle?
In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key.
7)What is transient variable?
Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
8)What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map.
9)Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
10)What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:
* Neither Abstract classes or Interface can be instantiated.
Posted by Shahid 18 comments
Labels: Core Java, SCJP and Interview Questions
J2EE FAQs or Interview Questions.
1.What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multi tiered, and web-based applications.
2. What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.
3.What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
o Application clients and applets are client components.
o Java Servlets and Java Server Pages TM (JSPTM) technology components are web components.
o Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
o Resource adapter components provided by EIS and tool vendors.
4. What are the four types of J2EE modules?
1. Application client module
2. Web module
3. Enterprise JavaBeans module
4. Resource adapter module
5. What does application client module contain?
The application client module contains:
o class files,
o an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.
6. What does Enterprise JavaBeans module contain?
The Enterprise JavaBeans module contains:
o class files for enterprise beans
o An EJB deployment descriptor.
EJB modules are packaged as JAR files with a .jar extension.
7.What does resource adapt module contain?
The resource adapt module contains:
o all Java interfaces,
o classes,
o native libraries,
o other documentation,
o A resource adapter deployment descriptor.
Resource adapter modules are packages as JAR files with a .rar (Resource adapter Archive) extension.
8.How many development roles are involved in J2EE application?
There are at least 5 roles involved:
1. Enterprise Bean Developer
* Writes and compiles the source code
* Specifies the deployment descriptor
* Bundles the .class files and deployment descriptor into an EJB JAR file
2. Web Component Developer
* Writes and compiles Servlets source code
* Writes JSP and HTML files
* Specifies the deployment descriptor for the Web component
* Bundles the .class, .jsp, .html, and deployment descriptor files in the WAR file
3. J2EE Application Client Developer
* Writes and compiles the source code
* Specifies the deployment descriptor for the client
* Bundles the .class files and deployment descriptor into the JAR file
4. Application Assembler : The application assembler is the company or person who receives application component JAR files from component providers and assembles them into a J2EE application EAR file. The assembler or deployer can edit the deployment descriptor directly or use tools that correctly add XML tags according to interactive selections. A software developer performs the following tasks to deliver an EAR file containing the J2EE application:
* Assembles EJB JAR and WAR files created in the previous phases into a J2EE application (EAR) file
* Specifies the deployment descriptor for the J2EE application
* Verifies that the contents of the EAR file are well formed and comply with the J2EE specification
5. Application Deployer and Administrator
* Configures and deploys the J2EE application
* Resolves external dependencies
* Specifies security settings & attributes
* Assigns transaction attributes and sets transaction controls
* Specifies connections to databases
* Deploys or installs the J2EE application EAR file into the J2EE server
* Administers the computing and networking infrastructure where J2EE applications run
* Oversees the runtime environment
But a developer role depends on the job assignment. For a small company, one developer may take these 5 roles altogether.
9. What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever.
J2EE 1.4 includes:
o Java API for XML-Based RPC (JAX-RPC 1.1)
o SOAP with Attachments API for Java (SAAJ),
o Web Services for J2EE(JSR 921)
o J2EE Management Model(1.0)
o J2EE Deployment API(1.1)
o Java Management Extensions (JMX),
o Java Authorization Contract for Containers(JavaACC)
o Java API for XML Registries (JAXR)
o Servlet 2.4
o JSP 2.0
o EJB 2.1
o JMS 1.1
o 2EE Connector 1.5
The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service endpoints based on Servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols.
The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment requirements for Web services and utilizes the JAX-RPC programming model.
In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform Web services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses the Java Management Extensions API (JMX).
The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of J2EE applications.
The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are integrated into J2EE containers.
The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension API, among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource adapter and Java Message Service (JMS) plug ability. New features in Enterprise JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB QL and message-driven beans.
The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined using XML Schema which can also be used by developers to validate their XML structures.
Note: The above information comes from SUN released notes.
10. Is J2EE application only a web-based?
NO. A J2EE application can be web-based or non-web-based. If an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a Servlet running in the web tier.
Posted by Shahid 0 comments
Q.What are the potential trips/traps in the SCJP exam?
Posted by Shahid 0 comments
Labels: SCJP and Interview Questions
*Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?
A. The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
*Q2. What's the difference between an interface and an abstract class?
A. 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.
*Q3. Why would you use a synchronized block vs. synchronized method?
A. Synchronized blocks place locks for shorter periods than synchronized methods.
*Q4. Explain the usage of the keyword transient?
A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
*Q5. How can you force garbage collection?
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
*Q6. How do you know if an explicit object casting is needed?
A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example: Object a; Customer b; b = (Customer) a;When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
*Q7. What's the difference between the methods sleep() and wait()
A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
*Q8. Can you write a Java class that could be used both as an applet as well as an application?
A. Yes. Add a main() method to the applet.
*Q9. What's the difference between constructors and other methods?
A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
*Q10. Can you call one constructor from another if a class has multiple constructors
A. Yes. Use this() syntax.
*Q11. Explain the usage of Java packages.
A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
*Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows: c:\>java com.xyz.hr.Employee
*Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?
A.There's no difference, Sun Microsystems just re-branded this version.
*Q14. What would you use to compare two String variables - the operator == or the method equals()?
A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
*Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNotFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
*Q16. Can an inner class declared inside of a method access local variables of this method?
A. It's possible if these variables are final.
*Q17. What can go wrong if you replace && with & in the following code: String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.
*Q18. What's the main difference between a Vector and an ArrayList
A. Java Vector class is internally synchronized and ArrayList is not.
*Q19. When should the method invokeLater()be used?
A. This method is used to ensure that Swing components are updated through the event-dispatching thread.
*Q20. How can a subclass call a method or a constructor defined in a superclass?
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor
=============For senior-level developers:================
**Q21. What's the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
**Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
**Q23. What comes to mind when you hear about a young generation in Java?
A. Garbage collection.
**Q24. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.
**Q25. If you're overriding the method equals() of an object, which other method you might also consider?
A. hashCode()
**Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
A. ArrayList
**Q27. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().
**Q28. How can you minimize the need of garbage collection and make the memory use more effective?
A. Use object pooling and weak object references.
**Q29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
*Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.
Posted by Shahid 1 comments
Labels: SCJP and Interview Questions