Apr 26, 2008

Executable Jar


Within Windows, it is also possible to set up Windows Explorer so that you can double click on the JAR file icon to execute the file (handy for GUI applications). The first thing you must do is set up the correct association with the 'javaw.exe' application that JDK for Windows will have. Click here for an older example with pictures! Open Windows Explorer and select Tools | Folder Options | File Types.

If there is no JAR file type, create it. Give it a description like

jar - Executable Jar File

to ensure it sorts under 'jar'. Create or edit the action called "open" and associate it with the following action:

"C:\Java\jdk1.4.0\bin\javaw.exe" -jar "%1"

Of course, you will replace "C:\Java\jdk1.4.0\bin\javaw.exe" with whatever path is correct on your machine.

IMPORTANT: include the double quotes to take care of names with spaces.


I felt this would be useful for my CD/DVD indexing app which can be found at
http://vishwasshrikhande.googlepages.com/home

Apr 1, 2008

Notes on JavaScript functions and objects



 
 

Sent to you by Prof via Google Reader:

 
 

via sandip chitale's blog by sandipchitale on 3/29/08

functions

static (or definition) context

  • All functions have a property named prototype. The value of prototype is an object with a property named constructor. The value of constructor is the function itself.
  • All functions have a property called length which specifies the expected number of parameters.
  • The value of constructor property of a function is function Function that is because the hidden super instance of a function is the value of the prototype property of function Function.

execution context

  • While a function executes there is a special variable arguments holds the actual arguments that were passed in when the function was invoked.
  • While a function executes there is a special variable arguments is of type Arguments which is an array-like object with a property length which gives the number of actual parameters passed in during invocation.
  • While a  function executes there is a special variable arguments.callee holds a reference to the function object itself. Thus  arguments.callee.length gives us the number of expected parameters.

Function function

static (or definition) context

  • Function being a function has a property named prototype. The value of prototype is an anonymous function function(){} with a property named constructor. The value of constructor is the function Function.
  • The value of constructor property of function Function is function Function. That is because the hidden super instance of a function is the value of the prototype property of function Function.

objects such as {} or new Object()

  • All objects inherit properties from a hidden super instance - the prototype object. The prototype object is the same as the value of the prototype property of function which was used to create the object using the new operator. Note: objects do not have a property named prototype.
  • The inherited properties behave in a copy-on-set manner.
  • All objects inherit a property named constructor from their hidden super instance - the prototype object.
  • The constructor of an object {} or new Object(){} is of course the function Object.

Object function

static (or definition) context

  • Object being a function has a property named prototype. The value of prototype is an anonymous object {} with a property named constructor. The value of constructor is the function Object.
  • The value of constructor property of function Object is function Function. That is because the hidden super instance of a function is the value of the prototype property of function Function.
Let us say we have code like this:
function Rectangle(width, height) { 
this.width = width;
this.height = height;
}

var twoByFourRectangle = new Rectabgle(2, 4);

+--------------------------------------+
inherits | +---------constructor property ----+ | +----------------------------------+
from | | | | inherits | |
| v | v from v |
function Function --- prototype property---> function() <------- function Object --- prototype property---> {constructor: Object}
^ ^
inherits | +---------------------------------------+ |
from | | | | inherits
| v | | from(?)
function Rectangle --- prototype property ----> {constructor: Rectangle}--+
^
inherits |
from |
|
object twoByFourRectangle --- width property ----> 2
+--- height property --> 4

Tricky huh? It was for me.


 
 

Things you can do from here:

 
 

May 28, 2007

SCWCD Exam Objectives


Section 1: The Servlet Technology Model

   * For each of the HTTP Methods (such as GET, POST, HEAD, and so
on) describe the purpose of the method and the technical
characteristics of the HTTP Method protocol, list triggers that might
cause a Client (usually a Web browser) to use the method; and identify
the HttpServlet method that corresponds to the HTTP Method.
   * Using the HttpServletRequest interface, write code to retrieve
HTML form parameters from the request, retrieve HTTP request header
information, or retrieve cookies from the request.
   * Using the HttpServletResponse interface, write code to set an
HTTP response header, set the content type of the response, acquire a
text stream for the response, acquire a binary stream for the
response, redirect an HTTP request to another URL, or add cookies to
the response.
   * Describe the purpose and event sequence of the servlet life
cycle: (1) servlet class loading, (2) servlet instantiation, (3) call
the init method, (4) call the service method, and (5) call destroy
method.



Section 2: The Structure and Deployment of Web Applications

   * Construct the file and directory structure of a Web Application
that may contain (a) static content, (b) JSP pages, (c) servlet
classes, (d) the deployment descriptor, (e) tag libraries, (d) JAR
files, and (e) Java class files; and describe how to protect resource
files from HTTP access.
   * Describe the purpose and semantics of the deployment descriptor.
   * Construct the correct structure of the deployment descriptor.
   * Explain the purpose of a WAR file and describe the contents of a
WAR file, how one may be constructed.



Section 3: The Web Container Model

   * For the ServletContext initialization parameters: write servlet
code to access initialization parameters; and create the deployment
descriptor elements for declaring initialization parameters.
   * For the fundamental servlet attribute scopes (request, session,
and context): write servlet code to add, retrieve, and remove
attributes; given a usage scenario, identify the proper scope for an
attribute; and identify multi-threading issues associated with each
scope.
   * Describe the Web container request processing model; write and
configure a filter; create a request or response wrapper; and given a
design problem, describe how to apply a filter or a wrapper.
   * Describe the Web container life cycle event model for requests,
sessions, and web applications;create and configure listener classes
for each scope life cycle; create and configure scope attribute
listener classes; and given a scenario, identify the proper attribute
listener to use.
   * Describe the RequestDispatcher mechanism; write servlet code to
create a request dispatcher; write servlet code to forward or include
the target resource; and identify and describe the additional
request-scoped attributes provided by the container to the target
resource.



Section 4: Session Management

   * Write servlet code to store objects into a session object and
retrieve objects from a session object.
   * Given a scenario describe the APIs used to access the session
object, explain when the session object was created, and describe the
mechanisms used to destroy the session object, and when it was
destroyed.
   * Using session listeners, write code to respond to an event when
an object is added to a session, and write code to respond to an event
when a session object migrates from one VM to another.
   * Given a scenario, describe which session management mechanism
the Web container could employ, how cookies might be used to manage
sessions, how URL rewriting might be used to manage sessions, and
write servlet code to perform URL rewriting.



Section 5: Web Application Security

   * Based on the servlet specification, compare and contrast the
following security mechanisms: (a) authentication, (b) authorization,
(c) data integrity, and (d) confidentiality.
   * In the deployment descriptor, declare a security constraint, a
Web resource, the transport guarantee, the login configuration, and a
security role.
   * Compare and contrast the authentication types (BASIC, DIGEST,
FORM, and CLIENT-CERT); describe how the type works; and given a
scenario, select an appropriate type.



Section 6: The JavaServer Pages (JSP) Technology Model

   * Identify, describe, or write the JSP code for the following
elements: (a) template text, (b) scripting elements (comments,
directives, declarations, scriptlets, and expressions), (c) standard
and custom actions, and (d) expression language elements.
   * Write JSP code that uses the directives: (a) 'page' (with
attributes 'import', 'session', 'contentType', and 'isELIgnored'), (b)
'include', and (c) 'taglib'.
   * Write a JSP Document (XML-based document) that uses the correct syntax.
   * Describe the purpose and event sequence of the JSP page life
cycle: (1) JSP page translation, (2) JSP page compilation, (3) load
class, (4) create instance, (5) call the jspInit method, (6) call the
_jspService method, and (7) call the jspDestroy method.
   * Given a design goal, write JSP code using the appropriate
implicit objects: (a) request, (b) response, (c) out, (d) session, (e)
config, (f) application, (g) page, (h) pageContext, and (i) exception.
   * Configure the deployment descriptor to declare one or more tag
libraries, deactivate the evaluation language, and deactivate the
scripting language. 6.7Given a specific design goal for including a
JSP segment in another page, write the JSP code that uses the most
appropriate inclusion mechanism (the include directive or the
jsp:include standard action).



Section 7: Building JSP Pages Using the Expression Language (EL)

   * Given a scenario, write EL code that accesses the following
implicit variables including pageScope, requestScope, sessionScope,
and applicationScope, param and paramValues, header and headerValues,
cookie, initParam and pageContext.
   * Given a scenario, write EL code that uses the following
operators: property access (the . operator), collection access (the []
operator).
   * Given a scenario, write EL code that uses the following
operators: aritmetic operators, relational operators, and logical
operators.
   * Given a scenario, write EL code that uses a function; write code
for an EL function; and configure the EL function in a tag library
descriptor.



Section 8: Building JSP Pages Using Standard Actions

   * Given a design goal, create a code snippet using the following
standard actions: jsp:useBean (with attributes: 'id', 'scope', 'type',
and 'class'), jsp:getProperty, and jsp:setProperty (with all attribute
combinations).
   * Given a design goal, create a code snippet using the following
standard actions: jsp:include, jsp:forward, and jsp:param.



Section 9: Building JSP Pages Using Tag Libraries

   * For a custom tag library or a library of Tag Files, create the
'taglib' directive for a JSP page.
   * Given a design goal, create the custom tag structure in a JSP
page to support that goal.
   * Given a design goal, use an appropriate JSP Standard Tag Library
(JSTL v1.1) tag from the "core" tag library.



Section 10: Building a Custom Tag Library

   * Describe the semantics of the "Classic" custom tag event model
when each event method (doStartTag, doAfterBody, and doEndTag) is
executed, and explain what the return value for each event method
means; and write a tag handler class.
   * Using the PageContext API, write tag handler code to access the
JSP implicit variables and access web application attributes.
   * Given a scenario, write tag handler code to access the parent
tag and an arbitrary tag ancestor.
   * Describe the semantics of the "Simple" custom tag event model
when the event method (doTag) is executed; write a tag handler class;
and explain the constraints on the JSP content within the tag.
   * Describe the semantics of the Tag File model; describe the web
application structure for tag files; write a tag file; and explain the
constraints on the JSP content in the body of the tag.



Section 11: J2EE Patterns

   * Given a scenario description with a list of issues, select a
pattern that would solve the issues. The list of patterns you must
know are: Intercepting Filter, Model-View-Controller, Front
Controller, Service Locator, Business Delegate, and Transfer Object.
   * Match design patterns with statements describing potential
benefits that accrue from the use of the pattern, for any of the
following patterns: Intercepting Filter, Model-View-Controller, Front
Controller, Service Locator, Business Delegate, and Transfer Object.



Tapan Maru
Sun Certified Java Programmer

May 25, 2007

30 Java 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 FileNoFoundException 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.

** 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.


Questions taken from http://soa.sys-con.com/read/48839.htm, please visit this site for more reference material.

May 18, 2007

Understanding Java Byte Code

Hi All,

I know i havnt posted in quite some time, but not much has happened these days.
So note to myself, post more for JAVA.

I just found out a good link for understanding java byte code.
http://www.theserverside.com/tt/articles/article.tss?l=GuideJavaBytecode
Please look into it.

Mar 28, 2007

Escape Sequence


char a = '\u000A'. Why is this invalid?  

Unicode escape characters of the form '\Uxxxx', where xxxx is a hexadecimal value, are processed very early in the translation process (see JLS 3.10.4 ). As a result, the special characters '0A' (line feed) and '0D' (carriage return) are interpreted literally as "end of line."

For example, the expression...

 char A = '\u000A';

...therefore becomes...

 char A =;

...which results in a compile-time error.

To avoid this error, always use the special escape characters '\n' (line feed) and '\r' (carriage return

SCJP Hints


What are some potential trips/traps in the SCJP exam?  

  • Two top-level public classes cannot be in the same source file.
  • main() cannot call an instance (non-static) method.
  • Methods can have the same name as the constructor(s).
  • Watch for thread initiation with classes that don't have a run() method.
  • Local classes cannot access non-final variables.
  • Case statements must have values within permissible range.
  • Watch for Math class being an option for immutable classes.
  • instanceOf is not the same as instanceof.
  • Constructors can be private.
  • Assignment statements can be mistaken for a comparison; e.g., if(a=true)...
  • Watch for System.exit() in try-catch-finally blocks.
  • Watch for uninitialized variable references with no path of proper initialization.
  • Order of try-catch-finally blocks matters.
  • main() can be declared final.
  • -0.0 == 0.0 is true.
  • A class without abstract methods can still be declared abstract.
  • RandomAccessFile descends from Object and implements DataInput and DataOutput.
  • Map does not implement Collection.
  • Dictionary is a class, not an interface.
  • Collection (singular) is an Interface, but Collections (plural) is a helper class.
  • Class declarations can come in any order ( e.g., derived first, base next, etc.).
  • Forward references to variables gives a compiler error.
  • Multi-dimensional arrays can be "sparse" -- i.e., if you imagine the array as a matrix, every row need not have the same number of columns.
  • Arrays, whether local or class-level, are always initialized
  • Strings are initialized to null, not empty string.
  • An empty string is not the same as a null reference.
  • A declaration cannot be labelled.
  • continue must be in a loop (e.g., for, do, while). It cannot appear in case constructs.
  • Primitive array types can never be assigned to each other, even though the primitives themselves can be assigned. For example, ArrayofLongPrimitives = ArrayofIntegerPrimitives gives compiler error even though longvar = intvar is perfectly valid.
  • A constructor can throw any exception.
  • Initializer blocks are executed in the order of declaration.
  • Instance initializers are executed only if an object is constructed.
  • All comparisons involving NaN and a non-NaN always result in false.
  • Default type of a numeric literal with a decimal point is double.
  • int and long operations / and % can throw an ArithmeticException, while float and double / and % never will (even in case of division by zero).
  • == gives compiler error if the operands are cast-incompatible.
  • You can never cast objects of sibling classes (sharing the same parent).
  • equals() returns false if the object types are different. It does not raise a compiler error.
  • No inner class can have a static member.
  • File class has no methods to deal with the contents of the file.
  • InputStream and OutputStream are abstract classes, while DataInput and DataOutput are interfaces.


Jan 3, 2007

Have a Happy Aromatic Year.

Nov 26, 2006

Reference variables

There is a lot of difficulty for C++ programmers to understand the reference data types.
In Java when we declare variables of reference data types (arrays, interfaces, classes and enums) then no Object is created. eg. when we declare String s; then variable s is not a String object. It is a reference which can refer to instances of String only. The assignment operator is used to make an reference variable refer to another instance. eg in the code below:

String s = "Hello";
s = s + " world";

In the first line the reference variable s is made to refer to a String Object with the value of "Hello", and thne in the second line the right hand side evaluates to a new String Object created by concatenating the two String values. The second assignment makes the reference variable s refer to this new Object created. Assignment for reference data types does not update the Object but only makes the reference variable refer to a new instance.

Nov 23, 2006

Immutable

Immutability of String are quite confusing at first.
Why is it that a string
String s = "Hello"
changes to Hello World on performing the following operation.
s = s + " World"

The thing to notice here is , the actual String object Hello is not modified.
But a new object of value "Hello World" is created and assigned to var s.

Hence the point to notice is there is 1 reference variable and 3 objects.