Thursday, December 11, 2008

How to empty a StringBuffer

We know that StringBuffer is reusable , We may want to empty a String Buffer ( lets say at end of a loop )
so how do you do it ?

The easiest way i came across use the method setLength()
public void setLength(int newLength)
You may have the case like
StringBuffer sb = new StringBuffer("HelloWorld")
// after many iterations and manipulations
sb.setlength(0);
// reuse sb

Please note you cant say
StringBuffer sb = "";
You will get a type mismatch error saying that "Cannot assign a value of type String to StringBuffer"
Makes sense as StringBuffer is not String , and they both inherit from java.lang.Object

Thursday, November 27, 2008

Java ques

There are three types of empty string, null, "" and " ". Here is how to check for each flavour:

if ( s == null ) echo ( "was null" );
else if ( s.length() == 0 ) echo ( "was empty" );
else if ( s.trim().length () == 0 ) echo ( "was blank or other whitespace" );

We cant use the following
String s="";
if(s.equals(""))
sop("string equal");

Java tricky ques

Q: How can I check a string has no numbers?

A: The simplest way to check that a String does not contain any numbers is to use the regular expression class Pattern in the java.util.regex package. The method below uses the regular expression [^0-9]+ to check that none of the characters in the input string is a number. The square brackets define a character class. The negation modifier, ^, followed by the number range 0-9 means "not a number". The + quantifier asks the regular expression to match the character class one or more times.

Wednesday, November 26, 2008

Java String tricky ques

String s1 = "hello world";
String s2 = "hello world";

if(s1==s2)
System.out.println("Yes");
else
System.out.println("No");

// output of first is Yes
the reason being that in above code you are comparing two references

public static void point1()
{
String s = new String("Friday");
String s1 = new String("Friday");
if (s == s1)
System.out.println("Equal A");
if (s.equals("Friday"))
System.out.println("Equal B");
}
ANS : Equal B
Because they are two different objects on heap , refering diff memeory addresses
hence their reference is not same.

more explanation here.

Tuesday, November 4, 2008

Sunday, September 28, 2008

Netbeans 6.1 and Tomcat 5.5

I was trying add Tomcat5.5 , i had used windows installer for it , to netbeans6.1 on windows and I always get the error "cannot find catalina.bat you cannot start your server through netbeans"
After spending quite some time on why was i getting this error I figured out that i must "Download the .zip formated Tomcat, not the Windows executable. It will have the files netbeans6.1 needs."

A lesson learned :)

Installing Netbeans without glassfish

Hi
This is crazy but true , you can install netbeans 6.1 without glassfish .. how ?? simple if you have no space in C drive and install Netbeans in D drive , i tried it out today and saw it happened that way for me

:)

Windows Vista and Tomcat 5.5


Seems like vista is incompatible with tomcat 5.5 too , because of renaming permission ...

Saturday, September 27, 2008

Windows Vista and NetBeans6.1 Axis2 plugin issue


Hi
Discovered that Netbeans 6.1 Axis2 plugin is incompatible with windows vista. The methods at http://www.netbeans.org/kb/61/websvc/gs-axis.html

To deploy an Axis2 web service to the server:

1. Right-click the web service's node. The context menu opens. Select Deploy to Server. The IDE compiles an Axis2 AAR file and copies it to the axis2.war file used by the application server.

The above step cant be completed in windows vista because , windows vista gives a popup and expects user to click "OK" to rename a file.

Error is Unable to rename old file axis.war , because

Eclipse 3.4 Axis2 1.4 invocationtargetexception

Hi
After wasting few precious hour , i finally concluded that Eclipse 3.4 and Axis2 1.4 are not compatible
many people have faced similar errors ..

http://wuhai.wordpress.com/2008/07/28/axis2-codegen-for-eclipse-invocationtargetexception/
http://wso2.org/library/1719

and the posts are as old as march 08 , and still the members of eclipse dev team havent corrected it , no wonder Eclipse which used to be KING of Java editor is no longer "recommended" anymore , and Netbeans has taken over !!

Solution ?
Take Axis2 eclipse codegen wizard 1.4 from http://www.javaeye.com/post/560587
Or take Eclipse 3.0.1 from http://archive.eclipse.org/eclipse/downloads/drops/R-3.0.1-200409161125/index.php

Tuesday, August 19, 2008

Social Networking & Adverstising



I agree with him on quite a few points ,
  • mobile phone is the center of gravity for teens today !
  • Virtual gifting is growing at a rapid pace ( $600,000 a month ) any one send you a scrap but how do i show that i really care ... spend on a virtual gift !! People show off virtual gifts on the social networking sites.
  • Dating is Gaming... It has been traditionally popular on tv shows , it will be HUGE hit on internet
  • Twitter has grown from "what are you doing" to "what r u doing & where are you"
  • Etsy : Your place to buy and sell handmade things online. its limited place
  • Threadless : consumer generated fashion label
  • StartMobile :
An individual seeks "youtube" , "google" , "etsy" , "threadless" all day and advertisers sees them on these sites.

Bebo n Me

I am not talking of Bebo as in Kareena Kapoor , the bollywood star , who happens to be nicknamed as Bibo , To be very frank there is nothing that will force ANYONE to put my name and her name in the same sentence ;-)

Anyways I heard about this social networking that...
  • Bebo is a social networking website
  • This social networking site is about sharing content.
  • You can share the videos , music etc that you like with your friends
  • You can even create a quiz and pass it to your friend.
  • Bebo has skins ( like most soc networking do ) that can be sponsored
  • Created by Michael Birch and Xochi Birch
  • The growing popularity drew the attention of media giants, and AOL shelled out $850 million for Bebo earlier this year.
the couple was recently intervievied on Europe 2007

One can create an application on facebook and port it to bebo. They seem to be compatible.

Wednesday, July 30, 2008

ActionScript and MXML relation

How do MXML and ActionScript relate to one another? The compiler, after parsing through the different idioms, translates MXML into the same objects, so that
< mx:button id="btn" height="100" label="My Button" >

and

var btn:Button = new Button();
btn.label = "My Button";
btn.height = 100;

produce the same object. ActionScript and MXML compiles into a SWF file

Sunday, July 20, 2008

Friday, July 18, 2008

Flex : Self Growing Button

I have been experimenting around with flex , figured out you can make a Self growing button easily in flex.

< id="button1" label="Click to Increase Size" height="20" click="button1.width+=10;button1.height+=5; ">

I am not trying to display something unusual here. But just a thought its so easy in Flex. If I had to do something similar in JSF or Ajax then it would have involved lot more coding and would use Partial Page Refresh.

Thursday, July 17, 2008

Password Management : Too Many passwords ... how do u manage them ??

With technology touching our lives more than ever before , this is becoming a common issues faced by MANY ...
A partial solution came up ... OpenID With some drawbacks
  • Not applicable to secure sites like banking etc
  • Adopted by most NOT ALL.
So how to solve it ??

Well the answer is simple ALGORITHM .. he he .. wondering how ??
let me give you an example...

Generate an algorthim , exploiting the fact that the website names are unique.
If you are member of two websites www.websiteone.com and websitetwo.com
your password may be ... webONEsite and webTWOsite
And if you decide to join another www.websitethree.com then following your example you may keep your password as webTHRsiteEE

The algorithm used above is ... take the 1st three letters of website , append with the last three letters of website and then followed by the remaining letters.

Intelligent lot may think of Exceptional cases like
  • What if the website name is less than 6 letters ( eg yahoo.com , gmail.com )
  • What if it is exactly 6 letter
  • etc , etc ....
Well i would say that its YOUR responsibility to make a proper algorithm that works for most of the sites that you log on to. And i just gave an example here to make your life easier I am not researching on this technique to make EFFICIENT ALGOs.

There are certain Implicit Requirement of this technique. The generated password must follow certain guidelines.

for example your Algorithm may be take the first three letters of website and then append with last three letter's ascii value.
So
www.websiteone.com => web797869
www.websitetwo.com => web848779

Well thats better.. you are a quick learner. :)

But the downside of this algorithm is that it will give same password for sites like webXXXone.com and webYYYone.com or infact webYYYYone.com well thats not a downside how can someone know that you have same password for two of your website ??

Hope this helps
~cheerz !!

Wednesday, June 25, 2008

FileInputStream is slow

http://bannister.us/weblog/2008/06/22/why-fileinputstream-is-slow/

others
http://www.wbrogden.com/
http://www.ghostganz.com/blog/articles/2008/06/24/tostring-is-evil
http://www.jroller.com/eu/entry/throwng_npe
http://tech.puredanger.com/2008/06/24/performance-testing-tip-keep-a-log/

Java puzzle

Good puzzle...
interface.getSuperClass( ) will return null
as interface allows multiple inherutance

http://tech.puredanger.com/2008/06/24/java-puzzler-interface-super-classes/

Friday, June 6, 2008

Java 5 Oracle driver : bug ?

Nice read
http://www.jroller.com/morisil/entry/can_i_trust_oracle_jdbc

Linked Architecture

good read ...

http://cookiesareforclosers.com/blog/2008/06/linkedin-architecture

Difference between JVM , JRE , JDK

Simple some say ... Tricky as seen by others ... your decision :)
Answer is

JVM : Have you ever seen a software to install JVM ? NO ... Because you cant install it . Its considered to be subpart of JRE. Engineers at sun say its hypothetical Java engine that reads and run byte code.

JRE : = JVM + everything needed to run java program ( or should i say class file )

JDK : = JRE + extra tools needed to make java progran. see figure below.




Can you install JRE without JDK ? yes find them on suns site.

You might as well have observed when installing JDK JRE also gets installed

String Buffer vs StringBuilder vs Concatination Operator +

Run this code ... you will realize using concatination operator is better than stringBuilder
Most of us ( including me ) had the idea that StringBuilder will be fast



long now = System.currentTimeMillis();
for (int i=0; i<10000000; i++) {
String str = "one; two " +
";three four; five; six" +
"seven eight nine ten";
}
long then = System.currentTimeMillis();
System.out.println("+ " + Long.toString(then - now));

now = System.currentTimeMillis();
for (int i=0; i<10000000; i++) {
StringBuilder sb = new StringBuilder(200);
sb.append("one; two ");
sb.append(
";three four; five; six");
sb.append(
"seven eight nine ten");
String str = sb.toString();
}
then = System.currentTimeMillis();
System.out.println("StringBuilder " + Long.toString(then - now));

now = System.currentTimeMillis();
for (int i=0; i<10000000; i++) {
StringBuffer sb = new StringBuffer(200);
sb.append("one; two ");
sb.append(
";three four; five; six");
sb.append(
"seven eight nine ten");
String str = sb.toString();
}
then = System.currentTimeMillis();
System.out.println("String Buffer " + Long.toString(then - now));

Output on my PC was ...

+ 32
StringBuilder 9031
String Buffer 12125

Good Blogs

http://tech.puredanger.com/2008/06/03/favorite-java-resources/
http://www.techper.net/2008/06/03/flex-leads-to-clash-between-java-and-flash-communities/
http://thoughts.bharathganesh.com/2008/06/interesting-leak.html
http://linkmingle.com/user/interview_questions/google_interview_questions
http://jeremymanson.blogspot.com/

Thursday, June 5, 2008

Shutdown Windows using Java

Using JNI for it may be an overkill ...


may try

String command = ""; ( click here for shutdown_command )
Process child = Runtime.getRuntime().exec(command);


Or may be try one of these ...
Try one of these (they've both worked, but there might be problems with one - too long ago, don't remember, though )

C:\WINDOWS\RUNDLL32.EXE SHELL32.DLL,SHExitWindowsEx 1
C:\WINDOWS\RUNDLL32.EXE user,exitwindows

All Head First Series eBooks

This is an outdated post
please use http://it-ebooks.info/ or http://en.booksee.org/ to get any ebook you want

For those of you ... who like to collect eBooks ...
Heres the BAAP of all eBooks you collected so far

and above all most of them don't require password ...

Save the links ... as i may delete the post soon ... :)

I couldnt find password less links for ... "Head First Ajax" may be someone can help me with that ....

cheerz !!

More links

http://ebooksresource.wordpress.com/category/design-pattern/
http://martinfowler.com/books.html#eaa
http://knowfree.net/

Is Java Pass by value or pass by reference

Congratulations .... you are the 99,99,999 person to ask that ... click "here" to clain your prize.... ;-)
Let me see .. whats the correct ans....
Some of you may say its "pass by value for primitive data types and pass by reference for objects" ... hmmmm wrong ... actually the intellignet lot ( at least the booky's ) would say "java is pass by value for primitive types and passes refernce by value for objects.. so java is pass by value"... correct buddy ..... you the man !!

BUT ... thats incomplete my friend ... complete answer is .... java is pass by value for primitive types , passes reference by value for object types ... and when passing objects to remote method (ie RMI) its pass by object copy NOT reference copy.

Tuesday, June 3, 2008

Saturday, May 31, 2008

Implicit VS explicit cursor

  1. PL/SQL employs an implicit cursor for each UPDATE, DELETE, or INSERT statement you execute in a program. You cannot, execute these statements within an explicit cursor, even if you want to.
  2. You have a choice between using an implicit or explicit cursor only when you execute a single-row SELECT statement (a SELECT that returns only one row).
  3. When SELECT returns more than one row you may or may not have to use explicit cursor depends on usecase.
  4. If you use an implicit cursor, Oracle performs the open, fetches, and close for you automatically; these actions are outside of your programmatic control.

SQL Faqs

find the two minimum salaries among table
This Query returns duplicate value.
select sal from (select * from order by sal asc) where rownum < 3

This Query retuns only the second minimum salary
Select min(salary) from where Salary>(Select min(salary) from )

Whereas the following Query returns the distinct first two minmum salary in a table
Select min(salary) from union
Select min(salary) from where salary>(Select min(salary) from )

Find out nth highest salary from emp table
directly we can not give the condition as rownum=2....this is the most optimal soluton for the given problem
select * from (select rownum r,salary from (select distinct(salary)from employees where salary is NOT NULL order by salary desc)) where r=2
Best way is using CORRELATED SUBQUERY : as below
Select * From TableName T1 Where (N-1) = (Select Count(Distinct(E2.ColumnName)) From TableName T2 Where T2.ColumnName > T1.ColumnName)
For Required Case We can use it as :-
Select * From EMP T1 Where (2-1) = (Select Count(Distinct(E2.sal)) From EMP T2 Where T2.sal > T1.sal)

XML vs HTML : differences

  1. XML is basically ment to represent data in portable way while HTML to show data.
  2. XML have custom tags HTML has predefined tags.
  3. XML is case sensitive and HTML is not.
  4. XML document has to wellformed HTML doc need not be.

Looking forward for your input... :)

All About JSP : TagHandler

The package javax.servlet.jsp.tagext package has interfaces
  1. Tag
  2. IterationTag
  3. BodyTag

There are classes provided in the javax.servlet.jsp.tagext package which provide default implementation for the above interfaces :
  1. TagSupport
  2. BodyTagSupport
THERE s no IterationTagSupport

Tag interface
The six methods which Tag interface provides and which we have to implement are :
  1. setPageContext(PageContext pc)
  2. setParent(Tag parent)
  3. getParent()
  4. doStartTag()
  5. doEndTag()
  6. release()
Above six methods are a must.
If there are attributes in tag then we have additional setter & getter for them.

Tag Interface Lifecycle
  1. The setPageContext() method : is the first method that is called in the life cycle of a custom tag.
  2. The setParent() and getParent() methods : are used when custom tags are nested one inside the other. The JSP container calls the setParent() method on the child tag and passes it a reference to the parent tag. The getParent() method is usually called by one of the child tags and not directly by the JSP container.
  3. the setters of attributes are called
  4. doStartTag() method : After setting up the tag with appropriate references by calling the setPageContext(), setParent(), and setter methods, the container calls the doStartTag() method on the tag. After initialization, the doStartTag() method decides whether or not to continue evaluating its body content. As a result, it returns one of the two integer constants defined in the Tag interface: EVAL_BODY_INCLUDE or SKIP_BODY. May throw a JSPException.
  5. doEndTag() method : After the body of the tag is evaluated or skipped (depending on the return value of doStartTag()), the container calls the doEndTag() method. May throw a JSPException.
  6. release() method : Finally, the container calls the release() method on the handler class when the tag handler object is no longer required. A custom tag may occur multiple times on a JSP page. A single instance of the tag handler may be used to handle all of these occurrences. The JSP container calls the release() method on the handler class when the handler object is no longer required. It is important to note that this method is not called after every call to doEndTag().

IterationTag Interface

The IterationTag interface extends the Tag interface and allows us to include the body content multiple times, in a way that is similar to the loop functionality of a programming language. The IterationTag interface declares one method and one constant

int doAfterBody() : This method is called after each evaluation of the tag body. It can return either of two values: IterationTag.EVAL_BODY_AGAIN or Tag.SKIP_BODY. The return value determines whether or not the body needs to be reevaluated.

EVAL_BODY_AGAIN : Return value for doAfterBody(). This constant instructs the JSP engine to evaluate the tag body and include it in the output.

If doStartTag() returns SKIP_BODY, then the body is skipped and the container calls doEndTag(). In this case, the doAfterBody() method is never called on the iterative tag. However, if doStartTag() returns EVAL_BODY_INCLUDE, the body of the tag is evaluated, the result is included in the output, and the container calls doAfterBody() for the very first time.

BodyTag Interface

The BodyTag interface extends IterationTag and adds a new functionality that lets the tag handler evaluate its body content in a temporary buffer. This feature allows the tag to process the generated contents at will. For example, after evaluation, the tag handler can view the body content, discard it completely, modify it, or add more data to it before sending it to the output stream. Since it is derived from IterationTag, BodyTag can also handle the evaluation and processing of the content as many times as required.

void setBodyContent(BodyContent) : Called by the JSP container to pass a reference to a
BodyContent object.

void doInitBody( ) : Called by the JSP container after calling setBodyContent(), to allow the tag handler class to perform initialization steps on BodyContent.

EVAL_BODY_BUFFERED : A constant defined as a return value for doStartTag() and doAfterBody() for tags that want to buffer the evaluation of their content

LifeCycle

The doStartTag() method of a class that implements the BodyTag interface returns any one of three values: EVAL_BODY_INCLUDE or SKIP_BODY inherited from the Tag interface, or EVAL_BODY_BUFFERED, which is defined in the BodyTag interface. The actions taken by the JSP container for the return values EVAL_BODY_INCLUDE and SKIP_BODY are the same as for the IterationTag interface.

However, if doStartTag() returns EVAL_BODY_BUFFERED, the JSP container takes a different course of action. It first creates an instance of the BodyContent class. The BodyContent class is a subclass of JspWriter and overrides all the print and write methods of JspWriter to buffer any data written into it rather than sending it to the output stream of the response. The JSP container passes the newly created BodyContent instance to the tag handler using its setBodyContent() method, calls doInitBody() on the tag, and finally evaluates the body of the tag, filling the BodyContent buffer with the result of the body tag evaluation.

The container calls doAfterBody() after evaluating the body, writing the data directly into the output or buffering it, as the case may be. If the output was buffered, we can add, modify, or delete the contents of this buffer. Finally, this method returns EVAL_BODY_AGAIN or EVAL_BODY_BUFFERED to continue evaluating the body in a loop, or returns SKIP_BODY to terminate the loop.

Finally, the container calls doEndTag(), and, as with the other interfaces, the tag handler class that is implementing the BodyTag interface can return either SKIP_PAGE or EVAL_PAGE.

Friday, May 30, 2008

All about JSP : Custom Tags

What's Custom Tag ? and Whats Use ??
Custom tags allow us to move the presentation logic outside the JSP pages into independent Java classes. One may choose to make custom tag for particular project or as an independent jar file.

There are diff kinds of custom tags
  1. Empty Tags
  2. Tags with attributes
  3. Tags with JSP code
  4. Tags with nested tags

Whats TagHandler ?
As name suggest its something that handles Tag and that something can only be java class. A tag handler is a Java class that implements one of the tag interfaces—Tag, IterationTag, or BodyTag—of the package javax.servlet.jsp.tagext.

The JSP specification defines a tag handler as a runtime, container-managed object that evaluates custom actions during the execution of a JSP page.

Whats Tag library descriptor ?
Its the way to let JSP engine know the tag handler classes for custom tags.

How to inform JSP Engine about custom tag library ?
TWO ways
(1) Use the taglib directive

< % @ taglib prefix="test" uri="testLib.tld" % >

(2) Use jsp root
< jsp="http://java.sun.com/JSP/Page" test="testLib.tld" version="1.2">
...JSP PAGE...
< / jsp:root>

Above examples shows URI. It can be of many type right ?
Three Types
(1) Absolute URI :
A URI that has a protocol, a hostname, and optionally a port number.
http://localhost:8080/mytaglibs

(2) Root Relative URI :
A URI that starts with a / "and" that does not have a protocol, a hostname, or a port number. It is interpreted as relative to the document root of the web application.
/myLib
/mytaglib/myLib

(3) Non-root Relative URI :
does not start with a / "and" that does not have a protocol, a hostname, or a port number. It is interpreted as relative to either the current JSP page "or" the WEB-INF, depending on where it is used.
myLib
mytaglib/myLib

< % @ taglib prefix="test" uri="sampleLib.tld" % >
The JSP engine searches for the file in the same directory as the JSP page.
Though keeping all the JSP pages and the TLD files in the same directory is the simplest way to use a taglib directive, it has two major drawbacks: security and flexibility.

How is the URI mapped to TLD ?
Through mapping ... standard reason ... achieve security & flexibility by maintaining a level of redirection ... If we wanted to switch to a newer version of the library, say myLib2.tld, then we would have to manually modify all the JSP pages that are affected by this change. The JSP container maintains a map between the URIs that we use in taglib directives and the actual physical location of the TLD files in the file system.
With this approach, instead of using a page-relative path, we use an absolute URI path:
< % @ taglib prefix="test" uri="http://www.myserver.com/myLib" % >
When the JSP engine reads the above URI, it refers to its internal map to find the corresponding
TLD file location.

The JSP specification mandates that, when deployed in a JAR file, a TLD file be
placed either directly under or inside a subdirectory of the META-INF directory. In
addition, the name of the TLD file must be taglib.tld. Thus, a JAR file containing
a packaged tag library is typically structured like this:
  • myPackage/myTagHandler1.class
  • myPackage/myTagHandler2.class
  • myPackage/myTagHandler3.class
  • META-INF/taglib.tld
How can the jsp container populate the taglib map
Three ways ...
• First, the container reads the user-defined mapping entries present in the deployment descriptor. This is called explicit mapping. We will learn how to add new entries to the deployment descriptor in the next section.
• Then, the container reads all the taglib.tld files present in the packaged JARs. For each jarred TLD file that contains information about its own URI, the JSP container automatically creates a mapping between the specified URI and the current location of the JAR file. This is called implicit mapping. We will learn how to add the URI information to a TLD file in the next chapter, where we will create a custom tag library.
• Finally, the JSP container adds entries for the URIs that are known to the container by default. These URIs are called well-known URIs. The element of a JSP document contains an example of a well-known URI: http://java.sun.com/JSP/Page

Algorithm ?
• If the value of the uri attribute matches any of the entries, the engine uses the value of the corresponding to locate the actual TLD file.
• If the value is a root-relative URI (that is, it starts with a /), the JSP engine assumes the location to be relative to the web application’s document root directory. Thus, the location for the URI http://www.manning.com/studyKit in listing 15.1 will resolve to
the TLD file /myLibs/studyKit.tld.
• If the value is a non-root relative URI (that is, it starts without a /), the JSP engine prepends /WEB-INF/ to the URI and assumes the location to be relative to the web application’s document root directory. Thus, the location for the URI http://www.manning.com/
sample.jar in listing 15.1 will resolve to the TLD file /WEB-INF/yourLibs/studyKit.tld.

• If the value of the uri attribute of the taglib directive does not match any of the entries, then the following three possibilities arise:
• If the specified uri attribute is an absolute URI, then it is an error and is reported at translation time.
• If the specified uri attribute is a root-relative URI, it is assumed to be relative to the web application’s document root directory.
• If the specified uri attribute is a non-root-relative URI, it is assumed to be relative to the current JSP page. Thus, if the JSP file /jsp/test.jsp contains the directive < % @ taglib prefix="test" uri="sample.tld" % >, the engine will expect to find the sample.tld file at /jsp/sample.tld.


Ques Where will it look for TLD file ?
< % @ taglib uri="www.myserver.com/myLib.tld" prefix="mylib" % >
Ans
The URI www.myserver.com/myLib.tld does not contain a protocol; therefore, it is not an absolute URI. It does not start with a /, so it is not a root-relative URI either. It is a page-relative URI. After failing to find an entry in the map, the engine will search for the file hello.tld at the location relative to the current page. Suppose the JSP page is at location
C:\tomcat\webapps\app15\test.jsp
The engine will look for the file at
C:\tomcat\webapps\app\www.myserver.com\hello.tld

Note
The value of cannot be an absolute URI. and both the and are mandatory when defining absoulte way.

google collections library

Link is more than enough :)
http://code.google.com/p/google-collections/

Wednesday, May 28, 2008

Java Tricky Question - 6

whats the difference between

< servlet-mapping >
< servlet-name >ServletOne< / servlet-name >
< url-pattern >/mywebsite/myservlet< / url-pattern >
< / servlet-mapping >

< servlet-mapping >
< servlet-name >ServletTwo< / servlet-name >
< url-pattern >/mywebsite/myservlet/< / url-pattern >
< / servlet-mapping >

< servlet-mapping >
< servlet-name >ServletThree< / servlet-name >
< url-pattern >/mywebsite/myservlet/*< / url-pattern >
< / servlet-mapping >


Dont ask me the answer ,,,, rather help me finding one ... ;o)
this one is still under discussion ... at java ranch

Java Tricky Question - 5

Q: How can you associate an array of values for an initialization parameter of a servlet?

A: You can’t; at least not directly! The deployment descriptor does not
allow you to specify multiple parameters with the same name. So you
have to do something like this:
< init-param >
< param-name > param1 < / param-name >
< param-value > val1 , val2 , val3 , val4 < / param-value >
< init-param >
You would then have to parse the param-value string in the servlet
and interpret the multiple values listed in the string.

Java Tricky Question - 4

Q : Your web application includes an applet packaged as a JAR file. Which directory would you keep the JAR file in?
A:
Because an applet is only run on the client side, the applet JAR file
should be accessible to the clients. This means that it may be kept anywhere
in the document root of the application except in the WEB-INF
directory and its subdirectories.
( As the contents inside the WEB-INF is not visible to client )

Java Tricky Question - 3

Both the interfaces ServletContext and ServletRequest have method getRequestDispatcher() .. whats the difference between them ??

Ans :
You can pass a relative path to the getRequestDispatcher() method of ServletRequest but not to the getRequestDispatcher() method of ServletContext. For example, request.getRequestDispatcher("../html/somePage.html") is valid, and the getRequestDispatcher() method of ServletRequest will evaluate the path relative to the path of the request. For the getRequestDispatcher() method of ServletContext, the path parameter cannot be relative and must start with /. This makes sense because ServletRequest has a current request path to evaluate the relative path while ServletContext does not.

Java Tricky Questions - 2

How can you create multiple servlet objects of the same servlet class if You are not allowed to implements the SingleThreadModel interface ??

Ans :
More than one element is defined in the web.xml file having the same servlet class names.
( some of you may say the ans is stupid ... I mean ques is more literal than technical ... but hey it can be a twister for many )

Practical Use :
You can do this if you want to have multiple sets of initialization parameters. For example, you may want one instance to connect to one database and a second instance to connect to another database.

Tuesday, May 27, 2008

Good Flex sites

the site http://www.flowww.com/

and This "Book tool" is simply superb... http://www.rubenswieringa.com/code/as3/flex/Book/

I wonder if Java ? ADF ? or JavaFX can make such tools .. sites
If yes how easy / tough would it be .... no idea ... !!

Java Tricky Questions - 1

Whats the difference between

int length = 5;
int breadth = 10;
int area = length * breadth;

and

final int length = 5;
final int breadth = 10;
int area = length * breadth;


dont scroll down until you have thought over the answer
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
gave it a thought ?
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
sure ?
.
.
.
.
.
.
.
.
.
.
.
Ok then heres the answer...
In the second code snippet multiplication is done at compile time.
In first multiplication is done at Runtime.
Reason
Java compiler uses something known as Constant Folding. Constant folding refers to the compiler precalculating constant expressions.
Query
I wonder what will happen if the code is

int length = 5;
final int breadth = 10;
int area = length * breadth;

The above code will not use constant folding for length but do so for breadth.
What if ?

static final int breadth = 10;
int area = 5 * breadth;

then compiler will use constant folding for breadth.

Monday, May 26, 2008

HashMap : Not thread safe structure

Nice Read
http://pveentjer.wordpress.com/2008/05/26/hashmap-is-not-a-thread-safe-structure/

Java Tricky questions

Found this link
bad part is answers are not explained

http://www.mydeveloperconnection.com/html/JavaTrap.htm

All About Java Exceptions

Common Java wisdom gives us a few general principles about how to work with exceptions:

1. Don’t use exceptions for flow control and expected business situations, but only for exceptional situations
2. Use unchecked exceptions for programming errors, bugs, situations where the application or the current operation cannot expect to recover from.
3. Use checked exceptions for situations where the caller is expected to be able to make a full or partial recovery after the failure

If we keep the function return type as


public boolean doSomeWork()
{
if(success)
return true;
else
return false;
...
}


two probs
1) Caller will have to check the return value : if he doesnt he may continue with wrong assumption
2) The caller doesn’t have enough information to see what went wrong

With this kind of solution we are back to the way C programs were written... but remember this is java

Another way is...

public class SomeException extends RuntimeException
{
...
}
public boolean doSomeWork()
{
if(success)
return true;
else
throw new SomeException();
...
}


You may have to do some documentation for the new exception class. Which is a disadvantage if you are LAZY ;).
Else the advantages are
* If the client code fails to treat the exception at least the program doesn’t continue on a wrong path.
* We can send more information about the failure context in the exception class through the exception type and the exception instance content.
Disadvantages
* The client code programmer is not automatically warned to treat the exception


One more way is ...

public class SomeException extends Exception
{
...
}
public boolean doSomeWork() throws SomeException
{
if(success)
return true;
else
throw new SomeException();
...
}

Client code will use try / catch block

How can you catch multiple exceptions in java ??

Statement stmt = null;
try {
// do stuff that uses Statement instance
} catch (SQLException e) {
// handle state
log.error("Bad database", e);
} catch (NullPointerException e) {
// handle state
log.error("Bad parameter", e);
} catch (Exception e) {
// handle state
log.error("Bad luck", e);
} finally {
try {
stmt.close();
} catch (Exception ex) {}
}


Summary
Rule of thumb: Use Checked Exceptions for recoverable conditions and Runtime Exceptions for programming errors.
Checked exceptions are great in theory, but in practice lots of developers use them poorly and then the rest of us are left to clean up their mess.
checked exceptions are domain exceptions.

Links
http://truecode.blogspot.com/2008/01/bypassing-java-checked-exception.html
http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html
http://dev2dev.bea.com/pub/a/2007/06/exception-advice.html
http://www.csd.uoc.gr/~andreou/

Thursday, May 22, 2008

JSF FAQs

JSF is MVC2 ?
As per my knowledge There is no MVC1 and MVC2
there is JSP model 1 and model 2 as explained in the article
http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html
JSF is in the scope of model 2


Other frameworks like JSF ?
Apple's WebObjects is a similar architecture to JSF and so is ASP.net.

Difference betwwen managed beans and backing beans ??

f:facet ??


Advantages
JSF's fine-tuned event model allows your applications to be less tied to HTTP details and simplifies your development effort.


http://forum.java.sun.com/thread.jspa?threadID=674446

Tuesday, May 20, 2008

Servlets Basics

javax.servlet.http.HttpServlet Is an abstract class that extends the javax.servlet.GenericServlet class.
All the methods in it have protected identifier and the service method is overloaded

protected void service(HttpServletRequest req, HttpServletResponse resp)

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.

 void service(ServletRequest req, ServletResponse res)

Dispatches client requests to the protected service method.

Clicking on a hyperlink always sends a GET request and thus, the doGet() method of the servlet will be called. < href = " /servlet/TestServlet " method="POST"> Some URL < / a >
The method="POST" attribute-value pair does not make sense in the anchor tag.
Retrieve Request Parameter

String[ ] getParameterValues(String paramName)

The above method is for html element like dropbox etc
 Enumeration getParameterNames() 

This method is useful when you don’t know the names of the parameters. You can iterate through the Enumeration of Strings returned by this method and for each element you can call getParameter() or getParameterValues().

Retrieve request headers

There is one difference , though; unlike parameters, headers are specific to the HTTP protocol and so the methods that deal with the headers belong to HttpServletRequest and not to ServletRequest.

 String getHeader(String headerName) 

This method returns just one of the values associated with the given header.
 Enumeration getHeaderValues(String headerName)

This method returns all the values associated with the header as an Enumeration of String object.
 Enumeration getHeaderNames() 

This method is useful when you don’t know the names of the headers. You can iterate through the enumeration returned by this method, and for each element you can call getHeader() or getHeaderValues().

Which method would you use to retrieve the number of parameters present in a request?
Neither ServletRequest nor HttpServletRequest provides any method to retrieve the number of parameters directly. You’ll have to use ServletRequest.getParameterNames(), which returns an Enumeration, and count the number of parameters yourself.

GET vs POST



















































FEATURE

GET method

POST method

Type of data
text text & binary

Amount of data
Browser dependent gen is 255 unlimited

Visibility
data is part of URL Part of body not URL

Caching
can be cached cant be

Bookmarkable
Can bookmark Cant bookmark

Spl Case
Cant be used in case data is character set other than ASCII Can use any type of character set

Use Case
used when the form processing is "idempotent" used in all other cases

Default
Its default for HTML FORM element Its not .. need to use method attribute

Monday, May 19, 2008

HashMap : Basics


package datastructure.delme;
import java.util.*;

class SimpleClass {
private String desc;
public SimpleClass(String s) {
desc=s;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "description is "+desc;
}
}

public class DelMeCollection {
public static void main(String[] args) {
System.out.println("in main");
SimpleClass s1 = new SimpleClass("one");
SimpleClass s2 = new SimpleClass("two");
SimpleClass s3 = new SimpleClass("three");
SimpleClass s4 = new SimpleClass("four");

HashMap hm = new HashMap();
hm.put("1",s1);
hm.put("2",s2);
hm.put("3",s3);
hm.put("4",s4);
Iterator hmKeyItr = hm.keySet().iterator();
while(hmKeyItr.hasNext())
{
String tempKey= (String)hmKeyItr.next();
System.out.println(tempKey+" val is "+hm.get(tempKey));
}

Iterator hmValItr = hm.values().iterator();
while(hmValItr.hasNext())
{
SimpleClass tempVal = (SimpleClass)hmValItr.next();
System.out.println(" val is "+tempVal);
}

for (Map.Entry entry: hm.entrySet())
{
System.out.println(entry.getKey() + " -> " + entry.getValue());
}


}
}



also tried UPCASTING
the following gave error


HashMap < string , object > hm = new HashMap < string , simpleclass >();
HashMap < string , simpleclass > hm = new HashMap < string , object >();
HashMap < string , simpleclass > hm = new HashMap < object , sipleclass >();
HashMap < object , simpleclass > hm = new HashMap< string , simpleclass >();



Moreover java.util.HashMap

Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

Friday, May 16, 2008

Clear the Screen In Java 5

Ask your friend to write a simple command line utility in java that gives a set of options like ...

1. Press 1 to add element to LinkedList
2. Press 2 to Delete an element in LinkedList
3. Press 3 to traverse the LinkedList
4. Press 4 to exit

Enter Your Choice : _


When user choses one of the above mentioned options ,
First , the screen should be cleared off
Second , the corresponding details (if any) should be asked ( like eneter value to add / delete )
Third , perform the action
Fourth , ReDisplay the above menu

To complete the above program you need to write a method like...


public void clearTheScreen( ) {
....
}


or may be


public boolean clearTheScreen( ) {
....
// return true if screen deleted else false
}


How to complete this method ??

hhhmmmm lets "BRAIN STORM"

"first" reply may be...
Runtime.getRuntime.exec("cls");

No you say ...
System-specific tasks such as these may be performed via Runtime.exec( )
it allows you to perform certain system-specific tasks BUT with very little control.

Actually, this won't work. Yes, the 'cls' command is invoked, *but* it is
invoked in a new process ['command.com' or 'cmd.exe' is exected creating a
new process], and *does not* clear the Java application's console.

If your friend is intelligent may argue ...
But if they can implement "beep", and they do, they should be able to implement "cls" too.
But you are MORE intelligent , you say
That's because BELL is a standard ASCII character (code 7) and it's
pretty much standard that any terminal/console would render it by beeping.


The "second" reply may be
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");

and you say ... its obviously incorrect ( BTW your friend is stupid if he mentions this option ) ,
as it scrolls the menu above so that its not visible to user NOT clean the screen.


"third" reply may be
I heard about this method:
System.out.print((char)27 + "[2J");

Dont get scared probably your friend probably was good DOS progarmmr at some time as + "[2J" is the ANSI escape sequence for clearing the screen.
However, it doen't work unless "ansi.sys" is loaded and very few WinXP user's have this.

If your friend is a Windows geek he may say

Yes, we can add the following command in the c:\windows\system32\config.nt.
device=c:\windows\system32\ansi.sys
This will load the ansi.sys

But that wont work buddy ... you may try it yourself .. and besides
Thats Platform dependent !! and Java is platform independent right ?
so take a "Chill Pill dude"

"fourth" may be ( if your friends guesses this .. he is really good with java / linux )
Printing out the form-feed character will clear the screen
System.out.print("\f");
It works but only on linux , not on windows ... But java code should be platform independent

Your friend : " So WHAT SHOULD I DO ??? "
You ( with a smile ) : Write Java Native Interface [JNI] routines which tap into the relevant operating system functionality
Your Friend : " ?? WHY ?? "
You : Unfortunately these tasks are inherently operating system-specific, and cannot be implemented in any standard way across platforms. Some platforms, in fact, don't even understand the concepts of 'screen', or 'cursor', so wouldn't even have any use for classes that implemented these abstractions. Even the 'standard' C and C++ languages which, like Java, aim for platform independance, do not implement such functionality.

Most intelligent of your friend may say ...
( you know the Phd types )

Maybe a nested class could be added to 'System', containing all the
system-specific console-management routines, something like:

class System
{
...
public class Console
{
...
public static native void cls();
public static native void setCurPos(int row, int col);
public static native String inputString();
public static native double inputNumeric();
...
}
...
}

You could then do something like:

System.Console.cls();


and YOU calmly reply ...
Amego !! It would defeat the purpose of platform-independance, since not all
platforms have the concept of a "console".


Real solution ??
Write JNI ( platform dependent way ) OR
Look at jcurses on sourceforge. ( but using this is an overkill )
http://sourceforge.net/projects/javacurses/

NeXt ... ask your friend .. to write a code to Accept input [say a single keystroke] without pressing ENTER and let me know how it goes ;o)

Contradiction
Contradicting my self ... Recently discovered that with Java 6 , Its very much possible ...
In Java 6 a better way of interacting with the command prompt was introduced, the java.io.Console class.
Together with the utility class java.util.Scanner introduced in Java 5 this new API can be used to develop more advanced Java console applications.

For more detaisl checkout
http://java.dzone.com/news/console-applications-java-6
http://java.sun.com/javase/6/docs/api/java/io/Console.html

Java Sort

http://mindprod.com/jgloss/sort.html

Thursday, May 15, 2008

Java Hashing

lets start with hashing in general and how does java implement same and what are the drawbacks ( if any )

hashing is a process of generating an index or address ( which is of smaller length) basing on ur data . A good hash function is the one which generates distinct addresses for distinct file names.

As a simple example of the using of hashing in databases, a group of people could be arranged in a database like this:
Abernathy, Sara Epperdingle, Roscoe Moore, Wilfred Smith, David (and many more sorted into alphabetical order)
Each of these names would be the key in the database for that person's data. A database search mechanism would first have to start looking character-by-character across the name for matches until it found the match (or ruled the other entries out). But if each of the names were hashed, it might be possible (depending on the number of names in the database) to generate a unique four-digit key for each name. For example:
7864 Abernathy, Sara 9802 Epperdingle, Roscoe 1990 Moore, Wilfred 8822 Smith, David (and so forth)
A search for any name would first consist of computing the hash value (using the same hash function used to store the item) and then comparing for a match using that value. It would, in general, be much faster to find a match across four digits, each having only 10 possibilities, than across an unpredictable value length where each character had 26 possibilities.

The hashing algorithm is also called hash function


Uses of hashing
(i) Hashes play a role in security systems where they're used to ensure that transmitted messages have not been tampered with. The sender generates a hash of the message, encrypts it, and sends it with the message itself. The recipient then decrypts both the message and the hash, produces another hash from the received message, and compares the two hashes. If they're the same, there is a very high probability that the message was transmitted intact.

(ii) Hashing is also a common method of accessing data records.

Java and hashing
Every Java object has a hashCode() and an equals() method. While the Java language does not provide direct support for associative arrays -- arrays that can take any object as an index -- the presence of the hashCode() method in the root Object class clearly anticipates the ubiquitous use of HashMap (and its predecessor, Hashtable). Under ideal conditions, hash-based containers offer both efficient insertion and efficient retrieval; supporting hashing directly in the object model facilitates the development and use of hash-based containers.

if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).

Why override equals() and hashCode()?

What would happen if a class did not override equals() and hashCode()? Nothing, if we never used an that class as a key in a HashMap or other hash-based collection. However, if we were to use such a classes object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same classes instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.

There are some restrictions placed on the behavior of equals() and hashCode(), which are enumerated in the documentation for Object. In particular, the equals() method must exhibit the following properties:
· Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)
· Reflexivity: For all non-null references, a.equals(a)
· Transitivity: If a.equals(b) and b.equals(c), then a.equals(c)
· Consistency with hashCode(): Two equal objects must have the same hashCode() value
· For any non-null reference value x, x.equals(null) must return false.

public boolean equals(Object o) {
if (o == null)
return false;
...
}

public boolean equals(Object o) {
if (!(o instanceof MyType))
return false; // also return null if o is null .. no spl check required
...
}

Building hashing into the root object class of the Java class library was a very sensible design compromise -- it makes using hash-based containers so much easier and more efficient. However, several criticisms have been made of the approach to and implementation of hashing and equality in the Java class library. The hash-based containers in java.util are very convenient and easy to use, but may not be suitable for applications that require very high performance. While most of these will never be changed, it is worthwhile to keep in mind when you're designing applications that rely heavily on the efficiency of hash-based containers. These criticisms include:

Too small a hash range. Using int, instead of long, for the return type of hashCode() increases the possibility of hash collisions.


Bad distribution of hash values. The hash values for short strings and small integers are themselves small integers, and are close to the hash values of other "nearby" objects. A more well-behaved hash function would distribute the hash values more evenly across the hash range.


No defined hashing operations. While some classes, such as String and List, define a hash algorithm to be used in combining the hash values of its constituent elements into a single hash value, the language specification does not define any approved means of combining the hash values of multiple objects into a new hash value.

Difficulty writing equals() when extending an instantiable class that already overrides equals(). The "obvious" ways to define equals() when extending an instantiable class that already overrides equals() all fail to meet the symmetry or transitivity requirements of the equals() method. This means that you must understand the structure and implementation details of classes you are extending when overriding equals(), and may even need to expose private fields in the base class as protected to do so, which violates principles of good object-oriented design.

Basically what happens is when hashCode returns a number then its searched for in collection and gets a list, and then it uses equals( ) to search in bucket that it got.

Equals( ) defines logical equality

Recipie for a equals( ) method

1. Use the == operator to check if the argument is a reference to this object.
If so, return true. This is just a performance optimization, but one that is worth
doing if the comparison is potentially expensive.
2. Use the instanceof operator to check if the argument is of the correct
type. If not, return false. Typically, the correct type is the class in which the
method occurs. Occasionally, it is some interface implemented by this class.
Use an interface if the class implements an interface that refines the equals
contract to permit comparisons across classes that implement the interface. The
collection interfaces Set, List, Map, and Map.Entry have this property.
3. Cast the argument to the correct type. Because this cast was preceded by an
instanceof test, it is guaranteed to succeed.
4. For each “significant” field in the class, check to see if that field of the argument
matches the corresponding field of this object. If all these tests succeed,
return true; otherwise, return false.
5. When you are finished writing your equals method, ask yourself three
questions: Is it symmetric, is it transitive, and is it consistent?

Here is the contract, copied from the java.lang.Object specification:
n Whenever it is invoked on the same object more than once during an execution
of an application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the
object is modified. This integer need not remain consistent from one execution
of an application to another execution of the same application.
n If two objects are equal according to the equals(Object) method, then calling
the hashCode method on each of the two objects must produce the same
integer result.
n It is not required that if two objects are unequal according to the equals(Object)
method, then calling the hashCode method on each of the two objects
must produce distinct integer results. However, the programmer should be
aware that producing distinct integer results for unequal objects may improve
the performance of hash tables.

References
http://java.sun.com/docs/books/effective/chapters.html
http://www.owasp.org/index.php/Hashing_Java

Java Iterator

Iterator also has a method remove( ) , when its called it will remove from source the last item retrieved from next( )

If remove is called twice in succesion without a call to next in between IllegalStateException is thrown can get Concurrent MOdification exceptiion if someone else is modifying the collection

according to http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html#remove()
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.


import java.util.*;
public class DelMeCollection {
public static List l = new ArrayList(25);
static class ListIterateThread extends Thread {
public void run( ){
System.out.println("thread started ");
Iterator listItr = l.iterator();
System.out.println("got the iterator ");
try {
while(listItr.hasNext())
System.out.println("val is "+listItr.next());
} catch(Exception e ) {
System.out.println("some exception "+e);
// wonder why no concurrent modification exception
}
}
}

public static void main(String[] args) {
System.out.println("inside main THREAD");
ListIterateThread lt= new ListIterateThread();
List l = new ArrayList(25);
lt.start();
l.add("1"); System.out.println("added 1");
l.add("2"); System.out.println("added 2");
l.add("3"); System.out.println("added 3");
l.add("4"); System.out.println("added 4");
l.add("5"); System.out.println("added 5");


l.add("11"); System.out.println("added 11");
l.add("12"); System.out.println("added 12");
l.add("13"); System.out.println("added 13");
l.add("14"); System.out.println("added 14");
l.add("15"); System.out.println("added 15");

try {
Thread.currentThread().sleep(5);
} catch (InterruptedException e) {
System.out.println("exception "+e);
}

l.add("21"); System.out.println("added 21");
l.add("22"); System.out.println("added 22");
l.add("23"); System.out.println("added 23");
l.add("24"); System.out.println("added 24");
l.add("25"); System.out.println("added 25");

l.add("31"); System.out.println("added 31");
l.add("32"); System.out.println("added 32");
l.add("33"); System.out.println("added 33");
l.add("34"); System.out.println("added 34");
l.add("35"); System.out.println("added 35");

}
}


Got Output


inside main THREAD
added 1
added 2
added 3
added 4
thread started
added 5
got the iterator
added 11
added 12
added 13
added 14
added 15
added 21
added 22
added 23
added 24
added 25
added 31
added 32
added 33
added 34
added 35


If you want to iterate through "Filtered Collection" try this

Java Collections

Framework consisits of three parts
  1. interfaces -
  2. implementation - of above interfaces
  3. algorithms - general applicable to either interfaces / implementation
Interfaces
  1. Collection - A collection represents a group of objects, known as its elements. may or may not have duplicate elements .. defines no order. JDK has no direct implementation of this interface.
  2. List - defines order , may have dup
  3. Set - no dup
  4. SortedSet - set with order
  5. Map - not part of hierarchy , just store key value pairs

Implementations
Keeping the two concepts ( interface & implementation) seperate can help you write code like
List l = new ....{ }

You can change implementation when your business condition require you to do so

<>

LinkedList is gr8 if u want to add/remove data from middle , if you want indexed access then ArrayList is better

  • All implementations are unsynchronised
  • All implementations offer fail fast iterators
  • All implementations are serializable and cloneable
  • All implementations support having null elements

Algorithm
the Collections class has methods that allow you to perform action on these data
This class consists exclusively of static methods that operate on or return collections.
Has static variables like EMPTY_LIST , EMPTY_MAP , EMPTY_SET
methods like binarySearch , min , max , reverse

java.util.Collection
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Adding Elements Framework consisits of three parts
(i) interfaces -
(ii) implementation - of above interfaces
(iii) algorithms - general applicable to either interfaces / implementation

Interfaces
  • Collection - A collection represents a group of objects, known as its elements. may or may not have duplicate elements .. defines no order. JDK has no direct implementation of this interface.
  • List - defines order , may have dup
  • Set - no dup
  • SortedSet - set with order
  • Map - not part of hierarchy , just store key value pairs

Implementations
Keeping the two concepts ( interface & implementation) seperate can help you write code like
List l = new ....{ }
You can change implementation when your business condition require you to do so



















































INTERFACE

HASH TABLE

RESIZABLE ARRAY

BALANCED TREE

LINKED LIST

HISTORICAL

SET
Hah Set
TreeSet


SORTEDSET


TreeSet


LIST

ArrayList
LinkedList

MAP


HashMap



WeakHashMap



TreeMap


Vector



Stack



HashTable



Properties



SORTEDMAP


TreeMap



LinkedList is gr8 if u want to add/remove data from middle , if you want indexed access then ArrayList is better

  • All implementations are unsynchronised
  • All implementations offer fail fast iterators
  • All implementations are serializable and cloneable
  • All implementations support having null elements

Algorithm
the Collections class has methods that allow you to perform action on these data
This class consists exclusively of static methods that operate on or return collections.
Has static variables like EMPTY_LIST , EMPTY_MAP , EMPTY_SET
methods like binarySearch , min , max , reverse

java.util.Collection
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Adding Elements
public boolean add(Object a) -- can only throw UnsupportedOperation exception , not nullpointerExcep
public boolean addAll(Collection c)

Removing Elements
public void clear()
public boolean remove(Object elem)
public boolean removeAll(Collection c)
if original was {1,5,3,8,1,8,2,4,1,3,7,6}
and passed list is {1,7}
every instance of 1 nad 7 will be removed
you get {5,3,8,8,2,4,3,6}

public boolean retainAll(Collection c)
opposite of remove

public Iterator iterator()

finding elements
public boolean contains(Object elem)
public boolean containsAll(Collection c)

checking size
public int size()
public boolean isEmpty()

copy and cloning collection
public Object[] toArray( )
public Object[] toArray(Object[] a)
consults the passed collection in terms of return type and size
if collections.siz() <= a.size() ... elements are returned in array and returned

Collection c = ....
String array[] = new String[c.size()];
array = (String[])c.toArray(array);


check for equality
public boolean equals(Object o)
Note besides Object.equals() interface also has this method to imphasize the fact that need to override Its not necessary to override the Object.equals( ) The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. -- dont try to add colection to itself

List l = new ArrayList(6);
l.add("1");
System.out.println("added 1");
l.add("2");
System.out.println("added 2");
l.add(l);
System.out.println("KABOOM !!");
Iterator listItr = l.iterator();
while(listItr.hasNext())
System.out.println("val is "+listItr.next());

I got the output

added 1
added 2
KABOOM !!
val is 1
val is 2
val is [1, 2, (this Collection)]


collection VS Collection VS Collections

Java Garbage Collection

A garbage collector is responsible for
  • allocating memory
  • ensuring that any referenced objects remain in memory, and
  • recovering memory used by objects that are no longer reachable from references in executing code.

Space is allocated by a large space called heap. The JVM's heap stores all objects created by an executing Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free blocks of heap memory are left in between blocks occupied by live objects

Code for System.gc is as follows

public static void gc() {
Runtime.getRuntime().gc();
}


System.gc() is just more convinient to call/use

freeMem = Runtime.getRuntime().freeMemory();
System.gc();
System.out.println("free memory after running gc(): " + freeMem);


Interesting links
http://chaoticjava.com/posts/garbage-collection-the-comic-panel/
http://chaoticjava.com/posts/how-does-garbage-collection-work/
http://chaoticjava.com/posts/parallel-and-concurrent-garbage-collectors/
http://chaoticjava.com/posts/gc-tips-and-memory-leaks/

Wednesday, May 14, 2008

Java and MS-Office

Just in case ever need to
  1. Read a Microsoft word document in Java
  2. Import Excel in JTable
In Conference Java One 2008 , Oracle also gave demo on how to integrate MS-Excel with ADF

Java Strings Immutable

Many modern languages (like java) employ “the immutable object” paradigm, which solves a lot of problems including the
  1. Memory conservation
  2. Addressing concurrency concerns
  3. Cache localization
Memory Conservation - A pool of string objects ( constant ) is maintained with references pointing to the constant objects. Instead of each variable having new String object. Re usability leads to lesser memory usage.

Concurrency Concerns - if you change any string need to consider that more than one references may be pointing to same string , so if you will change that string all references must also be updated ( thats tough ) so a new object for changed string will be created and only that particular reference will be point to that new object hence actual object will never change.

I am not sure about cache localization ??