Archive

Author Archive

Interview Questions : Java Fundamentals

June 30th, 2009

1. Give a few reasons for using Java?

a.  Java is a fun language. Let’s look at some of the reasons:

  • Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).
  • Object Oriented (OO).
  • Better portability than other languages across operating systems.
  • Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised APIs (Application Program Interfaces).

2. What is the main difference between the Java platform and the other software platforms?

a.  Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc. ava Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms.  Byte codes are the machine language of the JVM.

3. What is the difference between C++ and Java?

a.  Both C++ and Java use similar syntax and are Object Oriented, but:

  • Java does not support pointers. Pointers are inherently tricky to use and troublesome.
  • Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implement those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically on those methods.
  • Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized. Avoid using finalize() method to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these resources through the finalize() method.
  • Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework (Collection Framework)
  • All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.
  • C++ requires explicit memory management, while Java includes automatic garbage collection.

4. What are the advantages of Object Oriented Programming Languages (OOPL)?

a. The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account, Customer etc. The features of the OO programming languages like polymorphism, inheritance and encapsulation make it powerful.

[Tip: remember pie which, stands for Polymorphism, Inheritance and Encapsulation are the 3 pillars of OOPL]

5. What is the difference between aggregation and composition?

a.  Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole.
For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship.

Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.
For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.

6. How does the Object Oriented approach improve software development?

a. The key benefits are:

  • Re-use of previous work: using implementation inheritance and object composition.
  • Real mapping to the problem domain: Objects map to real world and represent vehicles, customers, products etc: with encapsulation.
  • Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.

The increased quality and reduced development time are the by-products of the key benefits discussed above. If 90% of the new application consists of proven existing components then only the remaining 10% of the code
have to be tested from scratch.

7. Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?

a. The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. Example Serializable, Cloneable etc

8. When is a method said to be overloaded and when is a method said to be overridden?
a. Method Overloading :

  • Overloading deals with multiple methods in the same class with the same name but different method signatures.

class MyClass {
public void initParams(int param) {…}
public void initParams(int param1, long param2)
{ … }
}

  • Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.
  • Overloading lets you define the same operation in different ways for different data.

Method Overriding:

  • Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.

class BaseClass{
public void initParams(int param) {…}
}
class MyClass extends BaseClass {
public void initParams(int param) { …}
}

  • Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass.
  • Overriding lets you define the same operation in different ways for different object types.

9. What is the main difference between an ArrayList and a Vector? What is the main difference between Hashmap and Hashtable?

a. Vector/Hashtable: Original classes before the introduction of Collections API. Vector & Hashtable are synchronized. Any method that touches their contents is thread-safe.
ArrayList/Hashmap: So if you don’t need a thread safe collection, use the ArrayList or Hashmap. Why pay the price of synchronization unnecessarily at the expense of performance degradation.

10. So which is better?

a. As a general rule, prefer ArrayList/Hashmap to Vector/Hashtable. If your application is a multithreaded application and at least one of the threads either adds or deletes an entry into the collection then use new Java collection API‘s external synchronization facility as shown below to temporarily synchronize your collections as needed:

Map myMap = Collections.synchronizedMap (myMap);
List myList = Collections.synchronizedList (myList);

Java arrays are even faster than using an ArrayList/Vector and perhaps therefore may be preferable. ArrayList/Vector internally uses an array with some convenient methods like add(..), remove(…) etc.

S.Chandru Java , , , , ,

interview Questions : Java

June 15th, 2009

1. what are the Native methods in Java?

a. When you want to call functions or subroutines which are written in some other language other than Java like C, C++ or VB6 etc.., These methods are Native methods in Java.

2. Explain Garbage Collection in Java?

a. Garbage collection is the process of automatically freeing object that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many bugs. Thus making programmers more productive as they can put more effort in coding rather than worrying about memory management. The only disadvantage of garbage collector is it adds overheads. Because the JVM has to keep a constant track of the objects which are not referenced and then free these unreferenced objects on fly. This whole process has slight impact on the application performance.

3. How can we force the garbage collector to run?

a. Garbage collector can be run forcibly using “System.gc()” or “Runtime.gc()”

4. What is use of method “finalize()” in Java?

a. Sometimes the objects needs to perform some action before the object is destroyed. For instance object is holding some non-java resources such as file handle which you might want to make sure are released before the object is destroyed. For such conditions java provides mechanism called finalization. You can add finalizer in a class by simply defining the “finalize()” method. JVM calls that method whenever it is about to recycle an object of that class.

5. Are String objects immutable, can you explain the concept?

a. Yes String object is immutable, Once you have assigned a String a value, that value can never change. Lets try to understand the concept by the below code snippet

String s1 = “hello”;

s1 = s1 + ” World”;

The VM took the value of String s (which was “hello”), and tacked ” world” onto the end, giving us the value “abcdef more stuff”. Since Strings are immutable, the VM couldn’t stuff this new value into the old String referenced by s1, so it created a new String object, gave it the value “hello world”,and made s1 refer to it. At this point in our example, we have two String objects: the first one we created, with the value “hello”, and the second one with the value ” world”. Technically there are now three String objects, because the literal argument to concat, ” world”, is itself a new String object.

6. Why String objects are immutable in Java?

a.To make Java more memory efficient, the JVM sets aside a special area of memory called the “String constant pool.” When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.) Now we can start to see why making String objects immutable is such a good idea. If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String’s value.

You might say, “Well that’s all well and good, but what if someone overrides the String class functionality; couldn’t that cause problems in the pool?” That’s one of the main reasons that the String class is marked final. Nobody can override the behaviors of any of the String methods, so you can rest assured that the String objects you are counting on to be immutable will, in fact, be immutable.

7. What is StringBuffer class and how does it different from String class?

a. StringBuffer is a peer class of String that provides almost all functionality of Strings. String represent fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and write-able character sequences. But StringBuffer does not create new instance as String so it’s more efficient when it comes to intensive concatenation operation.

8. What is the difference between StringBuilder and StringBuffer class?

a. StringBuffer is synchronized and StringBuilder is not.

9. What are the packages?

a. Packages group related class and interfaces together and thus avoiding any name conflicts. Classes are group together in package using “package” keyword.

10. What is use of JAVAP tool?

a. “javap” disassembles compiled Java files and spits out the representation of the Java program. This is a useful option when the original source code is unavailable.

S.Chandru Java ,

Not able to connect to the Jboss server remotely?

April 29th, 2009

Not able to connect to the server remotely? All the services appear to be bound to localhost only. Here is the solution for connecting Jboss remotely.

Before 4.2.0.GA jboss always bound to the any address “0.0.0.0″. Many people would put unprotected instances of JBoss on the internet, or even on their own local LAN. For Security reason Jboss is bound only to localhost, now you have to explicitly choose to bound to any address or specific address, so with the “-b” option of jboss you can bound to any address. e.g.

For UNIX users:

./run.sh -b 0.0.0.0

For Windows users:

run.bat -b 0.0.0.0

Note: Starting the server with -b 0.0.0.0 will get things going for you.

S.Chandru Jboss , , ,

Creating a Flex 3 Web application in Tomcat integrated Server in MyEclipse

April 24th, 2009

This article is continuation of my previous article on Installing Flex Builder Plugin in MyEclipse In this article I’ve focused on how to create and deploy a Flex 3.0 and Java Web application using BlazeDS in Tomcat integrated server in MyEclipse.

Prerequisites:
  • Should have integrated Flex Builder with MyEclipse.
  • Download latest release of binary version of BlazeDS from Adobe Open source site - Point to be noted BINARY DISTRIBUTION TO BE DOWNLOADED NOT ‘TURNKEY’ VERSION - Turnkey version has Tomcat & Samples in built.
  • After download, unzip the zip file & further unzip the “blazeDS.war” file to a temp folder.
  • The temp folder contains two folders “META-INF” & “WEB-INF”. Keep this in one place.

Creating and Deploying Flex web application step by step:

  • Open MyEclipse
  • Create a new Web Project, not Flex Project as shown below.new-web-project
  • New Web Project Window screen appears. Fill in all credentials as shown in below image.webprojdetails
  • [Note: Below are the credentials which are used in this document]
  1. Project Name: “FlexSampleWeb”
  2. Location: “use default location”, or user can have their choice of directory here
  3. Source Folder: “src”
  4. Web root folder: “WebRoot”
  5. Context root url: “/FlexSampleWeb”.
  6. If user has JDK or Java EE 5.0 Version of Java installed, it might alert for the same, click Ok button. It basically means to use JDK 1.4 or whatever default version selected to be used for this project [Make sure it should be JDK 1.4 or higher - as it is required for BlazeDS]
  • Click Finish to See Web Project being created.
  • Now minimize MyEclipse, and go to “FlexSampleWeb” Project root directory which is created just few steps before. In general scenario it would be present in “[WorkSpace Folder] > FlexSampleWeb” directory or path.
  • Also open the blazeDS.war extracted directory
  • Copy both “META-INF” & “WEB-INF” directories from blazeDS extracted directory to “FlexSampleWeb” project’s “WebRoot” directory.
  • Probably it will ask user for existences of few files & and asks for confirming the operation.
  • Click YES button to overwrite the files. (Don’t panic this operation is not harmful)
  • Now open or maximize the MyEclipse Editor
  • Refresh “FlexBlazeDSSample” project
  • The latest files along with “BlazeDS” config files under “WEB-INF > flex” directory are seen
  • And checking the properties of project & moving to java build path > library should also show blazeDS libraries
  • Below snapshots should be the outcomeproperties-for-flexsampleweb
  • Close all properties windows or any windows opened.
  • Go to Windows, Open Server Window View, you would basically see “Tomcat” Server with stopped status
  • Click Start to Start the Server
  • Deploy the web project which is created just now
  • Right Click on Tomcat Server on Server Panel
  • Click Manage Deployments to deploy
  • New Deployment screen appears.
  • Click Finish to deploy the web project.
  • Now, create a Flex Project which will integrate with the web project which was created earlier.
  • Either from File Menu or through right click options being Flex Development Perspective, Create new project.new-flex-project
  • Fill in the credentials as shown in above image
  • Project Name - “FlexSampleUi”
  • Project location - “use default location” - user can choose directory of their choice
  • Application Type - “Web Application”
  • Server Technology
    1. Application Server Type - “J2EE”
    2. Check on “use remote object access service”
    3. “LiveCycle Data Service” Radio button being selected
    4. Uncheck “Create combined Java/Flex project using WTP” option.
  • Click Next to continue and below screen appears.configure-j2ee-server
  • Fill in the form as shown in below picture or snapshotconfigure-j2ee-server-step-2
  • For those who cannot see the above image, follow below steps
  • Server Location - Uncheck “Use default location”
  • Root directory - Browse through folder structure of your system to Web-Project’s “WebRoot” directory [Above created web project]
  • Root Url - type in the full fledge url to access the web project on server for me it was “http://localhost:8080/FlexSampleWeb “
  • Context Root - “/FlexSampleWeb” - if you have different context root, specify that here
  • Leave compilation options as is.
  • Compiled Flex application location - output folder - would have full path of WebRoot followed by “FlexSampleUi-debug”
  • Remove “FlexSampleUi-debug” and live it as shown in next snapshotconfigure-j2ee-server-step-3
  • Click Validate Configuration button to validate the configuration.
  • This operation will result in below snapshotconfigure-j2ee-server-step-4
  • Click Finish to complete Project creation and expand the directory structure in Navigator or File Explorer should look like belowflex-development
  • Click on Run Button selecting Flex Project to see that it opens up url “http://localhost:8080/FlexSampleWeb//FlexSampleUi.html”
  • The Screen should be empty as it has no source at all.
  • Now create a Java class called “HelloWorld” in “com.test” package in “FlexSampleWeb” Web Project
  • Copy the below code into the java file

    package com.test;
    import java.util.Date;

    public class HelloWorld
    {
    private String userSaid;

    public String repeat( String said )
    {
    this.userSaid = “Reply from server: ” + said;
    return this.userSaid;
    }

    public String sayHello()
    {
    Date now = new Date();
    return “Hello World ” + now;
    }
    }

  • Open Flex Mxml file and copy below code.

    <?xml version=”1.0″ encoding=”utf-8″?>

    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>

    <mx:RemoteObject id=”myservice” fault=”faultHandler(event)” showBusyCursor=”true” destination=”Hello”>

    <mx:method name=”sayHello” result=”resultHandler(event)” />

    <mx:method name=”repeat” result=”resultHandler(event)” />

    </mx:RemoteObject>

    <mx:Script>

    <![CDATA[

    import mx.managers.CursorManager;

    import mx.rpc.events.ResultEvent;

    import mx.rpc.events.FaultEvent;

    private function faultHandler(fault:FaultEvent):void

    {
    CursorManager.removeBusyCursor();
    result_text.text = "code:\n" + fault.fault.faultCode + "\n\nMessage:\n" + fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail;
    }
    private function resultHandler(evt:ResultEvent):void
    {
    result_text.text = evt.message.body.toString(); // same as: evt.result.toString();
    }

    ]]>

    </mx:Script>

    <mx:Button x=”250″ y=”157″ label=”sayHello” width=”79″ click=”myservice.getOperation(’sayHello’).send();”/>

    <mx:Button x=”250″ y=”187″ label=”Repeat” click=”myservice.getOperation(’repeat’).send(myText.text); “/>

    <mx:TextArea x=”10″ y=”36″ width=”319″ height=”113″ id=”result_text”/>

    <mx:Label x=”10″ y=”10″ text=”Result:”/>

    <mx:TextInput x=”82″ y=”187″ id=”myText” text=”Sent to Server”/>

    </mx:Application>

  • BlazeDS server-side configuration:
    On the sever side, need to extend a BlazeDS configuration file to enable the Java service to be accessed later from the Flex client. Open the “remoting-config.xml” file in the project folder “FlexSampleWeb\WebRoot\WEB-INF\flex” and overwrite the content with the following:

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <service id=”remoting-service”
    class=”flex.messaging.services.RemotingService”>

    <adapters>
    <adapter-definition id=”java-object” class=”flex.messaging.services.remoting.adapters.JavaAdapter” default=”true”/>
    </adapters>

    <default-channels>
    <channel ref=”my-amf”/>
    </default-channels>

    <!– Flex Demo application –>

    <destination id=”Hello”>
    <properties>
    <source>com.test.HelloWorld</source>
    </properties>
    </destination>

    </service>

  • Save, Select web project back, refresh once, it should deploy the latest files on web project,
  • And start the tomcat server.
  • Now by selecting Flex Project, click on Run button to see the flex application the screen shown in snapshot below appears.output
  • Click on say hello button to see its functionality
  • Type in some message in text box & click on Repeat button to see the same on text area, which is returned from server

Source, Reference and Credit : Srinivas’s Blog

S.Chandru Adobe Flex, Java

Installing Flex Builder Plugin in MyEclipse

April 20th, 2009

This article puts emphasis on step by step installation of flex builder plugin in MyEclipse. These installation steps are carried out within Windows platform, but no need to worry you can follow these steps in any platform, only one thing to keep in mind is, to download the platform specific flex builder from the Adobe Site.

Follow the below given steps:
  • Download the Flex builder Plugin version from Adobe Site
  • Launch the installer. Installer starts up with the language selection screen.
  • Choose language of wish (Default is English) and click Ok, Introduction screen appears, and click next.
  • Next Screen is License Agreement. Read the License Agreement and click Yes to accept and continue.
  • Next Comes Choosing program and data location.
  • For Windows default path would be “C:\Program Files\Adobe\Flex Builder 3 Plug-in“; Select the desired path and click Next to proceed.
  • Choosing Eclipse directory location screen appears to Extend Form. Create a temporary folder “Eclipse” in “C:” or “D:” drive itself. This temporary Eclipse folder acts as a container for “links” folder which Flex Builder Installer places it. It does lot more than that, but as there is no configuration folder. choosefolder
  • Click Next, a window pops up notifying that the folder does not have any eclipse version in it. Click “Proceed with Caution” to proceed.supportedversion
  • Next would be selecting Additional Installations, select whatever needed and click Next.
  • The installer takes you to Installation Summary Section, showing all the details. Please make sure you have the things you had chosen before.reviewconfig
  • Click Install to begin the Installation process and ends up with installation Wizard Complete screen as below.installationcomplete
  • Upon completion, the installation Wizard Complete screen appears, Click Done to complete the installation process.
  • Now, open MyEclipse and in Menu navigate to Help > Software Updates > Find and Install
  • Feature Updates” Screen appearsfeatureupdates1
  • Check “Search for new features to install” radio button and click Next to continue.  “Update sites to visit” page will be appeared on screen.updatesitetovisit
  • Click “New Local Site” to browse the path the Flex Builder Plugin is installed. Under this installation, there would be a directory “com.adobe.flexbuilder.update.site“, select it, click Ok.
  • Upon selection of Flex Builder Plugin path. “Edit Local Site” Window appeared again, with url field being filled in, Fill in “Name” field with “Flex Builder” and click Ok.editlocalsite
  • “Update Site to visit” screen appears, with a list of plugins. i.e., Flex 3 Builder: [with path information], and list of features available. Select only Flex Builder 3 and click Next.finishinstall
  • Click Next to see “License agreement” window. Read the License Agreement and click Yes to accept and continue.featurelicense
  • Click Finish to complete the plugin installation.clickfinish
  • Upon completion of plugin installation to MyEclipse, the popup appears, prompting the user to restart MyEclipse. Click Yes to restart.
  • To create a small Test Flex project and to check plugin installation is proper switch to “Flex Development Perspective“.
  • Create a new project “Test”, Click Finish
  • Once done, user would see that in Problems window “Error” message popups.
  • Move to “design mode“, you would see error there too
  • Fix these errors before moving on, for that delete the project.flexdevelopment
  • This error or problem occurs because MyEclipse or the builder is unable to locate the SDK’s folder. To fix this, go to “Preferences” of “myEclipse.
  • Click “Flex > Installed Flex SDKs“. Errors are appearing in the window and show the reason too.
  • Select First one of the list, click “Edit“, would end up in “Edit Flex SDK” window. And then browse through and point it to “[Flex Builder Plugin Installation]\sdks\[Version First.. it's 2.0.1], click OK.
  • Update Flex SDK Name field with “Flex 2.0.1″ & click Ok to fix the error.installflexsdkinstallflexsdk2
  • Repeat for next one in the list, this time select “3.x.x” version under “sdks” folder & name it properly according to version & click Ok. And click Apply & then Ok to accept the changes. And Click on Install All button of the next screen.installall
  • User can download as many SDKs version as he/she wish, install it under “SDKS” version of Flex Builder plugin or which ever location user want, and then just point the SDK by adding new version as mentioned in the previous steps.
  • Create new Flex project and test the functionality of builder.

Note: Users switching to new workspaces are required to set the preferences again as mentioned in the above steps.

I hope this article will be useful for the beginers to install the Adobe Flex Builder 3 plugin in MyEclipse, and soon i will be writing article on Creating and deploying Adobe Flex 3 Web application using BlazeDS, Java and Tomcat integrated Server in MyEclipse. You can read my previous Adobe Flex 3 article Data Access with Flex 3

Source, Reference and Credit : Srinivas’s Blog

S.Chandru Adobe Flex , , , , ,