Saturday, May 30, 2009

How to choose a suitable access control specifier of a method or a field?

Access Control Modifiers available for classes and members in Java

Top-level classes in Java can have only two access control modifiers - public and default (package-private) whereas the members have four access control modifiers - public, protected, default (package-private), and private. Nested Classes are treated as members of the top-level classes so all four access control modifiers are applicable to them.

Choosing suitable access control modifier for methods in Java?

Here I'm assuming that your top-level (i.e., a class which is not nested) class is 'public' as otherwise if it's having the default access control modifier then you would probably never make any member public or protected owning to the fact the class itself can't be used outside the package. When to pick 'public' as the access control modifier?

How do you normally go about choosing the access specifier/modifier of a method in your class definition - whether you start from 'public' and move on to 'private' to see which specifier would actually suit the requirements or do you go about the other way round? It probably makes more sense to go the other way - starting from 'private' and moving onto 'public'. There should be a very strong reason why you would need a method to make 'public' as it would then become a part of the public interface of the class - a commitment from the class designer to all (those who are already consuming or those who would be consuming in future).

Therefore, choosing 'public' as the access specifier should be given a thorough review as consumers of the class can (which they normally do) use them in their implementation and hence once you make something public you got to support that for the consumers of your class till eternity (making a 'public' member deprecated and subsequently getting rid of it will be a difficult and time consuming exercise). A big ask especially in a professional environment where your class is being consumed by many critical applications. So as a thumb rule make only those members 'public', which you can't make either 'private', 'package-private (default)' or 'protected'.

When to pick 'protected' as the access control specifier?

A 'protected' modifier specifies that the member can be accessed from within the same package as well as by a sub-class in some other package.

Let's pick the suitable access modifier for a member which you want any of your sub-classes to have access to. Of course you can't choose 'private' here as the access will then be limited to your class only. Next up the ladder is 'package-private (default)' which will restrict the access limited to all the classes (either a sub class or not) in the same package only. But, if you want any sub class of your class to access the member then the default access modifier won't do it for you. Next up the ladder is 'protected' which suits fine here so no need to go further up. Quite simple to pick the suitable access modifier, isn't it?

Making something 'protected' also puts you in some sort of commitment in case you are not making your class as 'final' as otherwise the sub-classes of your class may write their implementation based on the availability of your 'protected' member. You have to be careful with the fact that the 'protected' members can be used by any class in the same package, so even if you have made your class as 'final' the commitment to make the 'protected' members available to all the classes in the same package still remains. But, why would you come up with such a design? If you want the member to be accessible only from within the same package, better make it package-private (default). Making a class 'final' which is having 'protected' members would certainly draw attention as to why would anyone like to do it. You would better need to review the class design in such a case.

When to pick default access control modifier?

'package-private' or the default access control modifier puts you under only one commitment. This is towards all the classes in the same package as they will have access to all your package-private members and hence they can have their implementation dependent on those members.

When to pick 'private' access control modifier?

'private' is something private to your class and hence you have no commitment towards others. You can change them anytime you want as long as it doesn't hurt the functioning of any public/protected/default member.

How to pick access control modifier for fields in Java?

For fields, the thumb rule is quite simple - make all instance fields 'private' and have getters/setters to access/modify them. However, you would probably like to make most of your static fields as 'public' as they are class variables and meant to be accessed from outside either on the class name (preferred way) or on any instance.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.

Friday, May 29, 2009

You might think if we would ever need it? Well... you may never, but no harm in exploring whether we have any/some ways of finding this in Java or not. This question was asked by one of our visitors - Marco Servetto. Thanks Marco for bringing this question up.

For instance methods, by caller you might mean either the object instance of the caller/calling method or method/class name of the caller/calling method. But, for static methods the caller will never be an instance, but only the other two (method/class).

In case of a static method, we don't have the implicit object reference (this) passed to them as they are never called on instances (even if you call static methods on object references, the call is actually resolved at compile time only and is made on the declared type of the object reference). And hence for them the caller will never be an instance.If we are interested in finding the object associated with the calling method inside the called method then the most obvious way is to pass the reference 'this' to the called method while making the call in the calling/caller method. I doubt if we have any other JVM implementation independent way of doing this. Better to understand it by code, which is pretty simple and straightforward.

By caller if we mean the name of the caller method name OR the name of the class of the caller method then we can probably use the getStackTrace() method either on current thread instance or on a Throwable instance:

Using getStackTrace on current thread (since Java 1.5) - 'StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()' - we can use this to get the stack trace of the current thread in a StackTraceElemnt array where the first element of the array is the most recent method invocation sequence on the stack - provided the returned array is of non-zero length. StackTraceElement has methods like getClassName, getMethodName, etc., which one can use to find the caller class name or method name.

Calling getStackTrace on a Throwable instance (since Java 1.4)- creating an instance of Throwable and then calling getStackTrace() method on it, will return an array of StackTraceElement, each of which will contain one stack frame each with the first element containing the most recent inovaction and the last having the least recent. You don't really need to throw the Throwable instance, only creating one would be good enough here.

Potential Problem: In certain situations, few JVM implementations may either omit one or more stack frames from the stack trace or they might not have any stack frame info at all related to this Throwable instance as a JVM implementation is allowed to return a zero-length array by Java language specs.

Another possible issue is that compile-time inlining may show skewed results. Say if a method A internally calls another method B and B calls C. Let's suppose the method B has no other executable statement. Obviously this will be a good candidate for compile time inlining as the compiler might replace the call to method B inside method A definition with a call to method C. In such cases, the above two approaches will return the caller method of method C as method A and not as method B what the source code might suggest. Please note that this will require you to turn on the optimization of the compiler. Results may vary across compilers as different compilers may have different criteria for inlining - some might never do.Other Possible Solutions: there can be some other possible solutions using a native method (like getCallerClass method) of some JVM implementation specific classes. We should avoid such a practice as we may otherwise sacrifice the portability of the code. Even worse, in case the implementation specific class is non-public then you might not use your code on the changed version of the same JVM implementation itself.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.

Sunday, May 24, 2009

Can we pass a new-line ('\n') character or any other escape sequence via command line in Java?

One of our visitors (Vivek Athalye) asked this in response to the article - Tricky use of static initializer block. Thought of posting the answer as a separate article to increase the chances of it reaching to a wider range of audience.

The answer to the query is NO. The question arises, if you pass the same escape sequence programmtically, it works fine, so why doesn't it work well when passed via command line? For example: System.setProperty("line.separator", " Bye!\nBBye!"); will work fine, but if try to do the same via command line as (java -Dline.separator=" Bye!\nBBye!" ClassName) then '\n' will be treated as two distinct ASCII characters ('\' and 'n') and not as a single escape sequence new-line Unicode character.

This behavior was logged as a bug on Sun's Bug Database on Oct 31, 2003. But, it was closed saying 'not a bug' on Nov 05, 2003. The reason given is that interpretation of text passed on command line is a shell specific stuff and it is not reasonable to expect that to work in lines with the handling of escape sequences by any particular programming language.

It's not something to do with Java as even if you pass a command line argument having '\n' to a C program, it will be treated as two distinct ASCII characters only and not as a escape sequence.

What stops a shell to interpret escape sequences is that escape sequences are represented differently in different programming languages - like '\n' is actually a single character Unicode character whereas in C it's a two-character ASCII sequence having a different meaning because of the preceding '\' character. So, on a system which requires to run both Java and C programs, which convention should the shell use? Tomorrow, if we see any other representation of escape sequence by some other programming language, how will the already developed shell will cope up with that? Hence, shell plays it straight and simply passes everything written on command line as ASCII character sequences without giving any special meaning to any particular sequence. Fair enough, I believe.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.

Can we have the output of the above code-segment as "Hi, Mr. main. Bye!" without changing the main-method code?

Yeah, we can have the required output by using 'static initializer' blocks effectively. As we know that a static initializer block is called when a class is loaded into memory and hence it'll obviously run before the main method. Let's see how this can be used here.

The required output can be broken into three pieces - "Hi, ", "Mr. main.", and " Bye!". These parts should get printed in this order only which means the string "Hi, " should be printed before the 'println' call inside the main method prints "Mr. main." and subsequently the last string " Bye!" should be printed.

As we know that 'println' method by default ends with a new line and hence to have the last part (" Bye!") being printed in continuation with the main-method println string, we probably have only two ways:-

Re-define the default 'println' behavior - we can create an anonymous subclass (as we would not be requiring that anywhere else) of the PrintStream class and then re-define the 'println' method as per our needs.

Changing the default line separator - we can use the third part " Bye!" as the new line separator (it can be passed as a command-line argument while calling the class) in which case the 'println' of the 'main' would print this as the line separator and we will end up getting the required output.

As is the case with many other solutions which use bits intelligently, this one is also very compact. That's the beauty of bit-handling. Let's first see what the solution is and then try to understand it. It becomes very easy to understand once you get the binary sequence representations right.

Java method to check if the passed parameter is a power of 2 or not

public boolean checkIfItsPowerOf2(int n){

if( (n & -n) == n){

//passed parameter is a power of 2 return true; } else{ //not a power of 2 return false; }}

Illustration: We'll see the working of the method for a few sample numbers , say '1', '2',and '3' to understand it completely.

1: Binary representation of 1

0000 0000 0000 0000 0000 0000 0000 0001

-1: Computation of binary representation of -1 by finding 2's complement of 1

i.e., ((3 & -3) == 3) will return 'false' which is correct as 3 is not a power of 2.

Similarly we can see that the condition ((n & -n) == n) will always return 'true' for a number which is a power of 2 and will always return 'false' otherwise.

A close observation will reveal that 2's complement of a number, which is a power of 2, will always maintain (at the same time it'll never maintain for a number which is not a power of 2) the significant bit sequence of the corresponding positive number and rest of the bits will be all 1s. Hence a bit-wise AND (&) operator applied on the two (n & -n) will always result into the number (n) itself (as it will maintain the significant bit-sequence and will set rest of the bits to0s as 0 & 1 = 0). Understood? If not then go through the examples once again and think on the same lines. It should not be that difficult to visualize then.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.

Negative numbers in Java are represented using 2's complement. As we know that integers in Java occupy 4 bytes so to understand how a negative integer (say -4) is represented internally in Java, we first need to find the binary equivalent of the positive value of the integer (in this case 4) and subsequently by finding the 2's complement of that binary representation.

Okay, so how do find 2's complement of a binary number? Simply by adding '1' to the 1's complement of that number. But, how to find 1's complement of a binary number then? Just by reverting the bits of the number i.e., changing 1s to 0s and 0s to 1s. An example may of of some help here.

Thus, we see that integer -4 is represented by the binary sequence (1111 1111 1111 1111 1111 1111 1111 1100) in Java.

Once we have an understanding of how the numbers are represented internally, bit-level manipulation becomes easily understandable, which otherwise is obviously one of the hardest things in Java (or any other language supporting that) to visualize.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.

Saturday, May 2, 2009

Puzzle: There is a huge pile of quarters and a circular table. There are two people to play a game of placing the quarters down on the table alternately without any overlap. The one who can't put down a quarter loses. Assuming that the pile of quarters is non-exhaustive what will be your winning strategy? Whether you would like to start or let your partner start?

Solution: The winning strategy here will be to find a way where you always end up getting a section of free space on the table to place down the quarter in your hand. That's fine, but how can one always ensure free space on the table? The table is circular and hence due to symmetry every place on the table (except for the centre) will have its own corresponding counterpart right opposite to it on the other side of the centre.

Got the answer now? Since the centre of the table is the only exception (not having a symmetrically opposite area) here and any other area on the table can always be guaranteed to have a directly opposite area where the centre of the table will be right in the middle of the two.

For winning the game you got to start first and place the quarter exactly in the centre of the table. From now on, any area your parter chooses to put down the quarter in their hand, will have its corresponding symmetrically opposite area on the other side of the centre of the table where you can place the quarter on your turn.

This will guarantee that you never fall short of free space on the table as this way you would be occupying the last usable (free) section of the table and consequently your partner will be the one failing to find a free area on the table to place the quarter on. How long/soon that happens, will depend upon the size of the quarters and that of the table.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.

Viewing/Editing files without having the required s/w or tools installed

Wonder what will you do in case you end up getting caught in a situation where none of the widely used tools/softwares (such as MS Office, Flash, File Viewers/Editors like Acrobat, etc.) are installed on a machine on which you need to at least view (or maybe edit if possible) some docs/files?

Well... until recently it was simply not possible, but the release of Google Docs has made it possible for many file types including PDF, Doc, etc. and now also for PowerPoint and TIFF. Now you only need a browser and an Internet connection and you can easily View/Print (and also Edit some of types) most of these popular file types.

This all can be done from your Gmail account straightaway. PDF Viewing was enabled way back in Dec 2008 and the most recent release from Google in this regard is PPT and TIFF file viewing.

'View as slideshow' option was there for PPTs, but now they have integrated the conversion technology into the same viewer which they are using for PDFs and TIFFs. Moreover, the new viewer supports a richer set of features like zoom in/out, printing PPT to a PDF doc, etc. Additionally, you no longer require a Flash plug-in installed on the machine. Below is the sample screenshot showing you view PPTs in the Gmail Viewer.

Most of the default TIFF viewers show only the first page, but the online viewer will not only show you all pages, but also give you an option to print the TIFF file to a PDF doc. Read the official Gmail blog post on this here.

Google Labs has already provided so much to be used for free and the list is still growing. For more details, visit the official Google Labs page, if not visited already.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.