Thursday, September 30, 2010

access specifier for class

1. There can be only one public class per compilation unit (file). The idea is that each compilation unit has a single public interface represented by that public class. It can have as many supporting package-access classes as you want. If you have more than one public class inside a compilation unit, the compiler will give you an error message.

2. The name of the public class must exactly match the name of the file containing the compilation unit, including capitalization. So for Widget, the name of the file must be Widget.java, not widget.java or WIDGET.java. Again, you’ll get a compile-time error if they don’t agree.

3. It is possible, though not typical, to have a compilation unit with no public class at all. In this case, you can name the file whatever you like (although naming it arbitrarily will be confusing to people reading and maintaining the code).

Note that a class cannot be private (that would make it inaccessible to anyone but the class) or protected So you have only two choices for class access: package access or public. If you don’t want anyone else to have access to that class, you can make all the constructors private, thereby preventing anyone but you, inside a static member of the class, from creating an object of that class.

import static single class declaration

SingleStaticImportDeclaration:
import static TypeName . Identifier;

The TypeName must be the canonical name of a class or interface type. The Identifier must name at least one static member of the named type.

StaticImportOnDemandDeclaration:
import static TypeName . * ;

Wednesday, September 29, 2010

Integer compare with ''

There is a tricky bug if you compare a number with empty string and if the number = 0:
                                                                                                    
#!/usr/bin/perl
#use warnings;
use strict;

my $v;

undef $v;

if (!defined($v)) {
print "Oops! \$v is not defined\n";
}

$v = 0;

if ($v == '') {
print "Oops! \$v == \'\'\n";
}

__END__

Result:
Oops! $v is not defined
Oops! $v == ''


You can see that if $v = 0, the condition:

$v == ''

will get TRUE!

Of course if you turn on warnings, you will not ignore this bug because compiler will give you this:

Argument "" isn't numeric in numeric eq (==) at ...

SUM(A + B) vs SUM(A) + SUM(B)

In PostgreSQL, a integer plus a null get null, so these two expressions is different not only in result but also in logic:

SELECT SUM(A + B) FROM youtable;
SELECT SUM(A) + SUM(B) FROM youtable;

You can verify this if your A or B has null value.

Compilation unit

When you create a source-code file for Java, it’s commonly called a compilation unit (sometimes a translation unit). Each compilation unit must have a name ending in .java, and inside the compilation unit there can be a public class that must have the same name as the file (including capitalization, but excluding the .java file name extension). There can be only one public class in each compilation unit; otherwise, the compiler will complain. If there are additional classes in that compilation unit, they are hidden from the world outside that package because they’re not public, and they comprise "support" classes for the main public class.

Monday, September 27, 2010

How an object is created

To summarize the process of creating an object, consider a class called Dog:
1. Even though it doesn’t explicitly use the static keyword, the constructor is actually a static method. So the first time an object of type Dog is created, or the first time a static method or static field of class Dog is accessed, the Java interpreter must locate Dog.class, which it does by searching through the classpath.
2. As Dog.class is loaded (creating a Class object, which you’ll learn about later), all of its static initializers are run. Thus, static initialization takes place only once, as the Class object is loaded for the first time.
3. When you create a new Dog( ), the construction process for a Dog object first allocates enough storage for a Dog object on the heap.
4. This storage is wiped to zero, automatically setting all the primitives in that Dog object to their default values (zero for numbers and the equivalent for boolean and char) and the references to null.
5. Any initializations that occur at the point of field definition are executed.
6. Constructors are executed. this might actually involve a fair amount of activity, especially when inheritance is involved.

Order of initialization

Within a class, the order of initialization is determined by the order that the variables are defined within the class. The variable definitions may be scattered throughout and in between method definitions, but the variables are initialized before any methods can be called—even the constructor.

Sunday, September 26, 2010

Cleanup: finalization and garbage collection

The garbage collector only knows how to release memory allocated with new.
To handle this case, Java provides a method called finalize( ) that you can define for your class. Here’s how it’s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object’s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection.

1.Your objects might not get garbage collected.
2.Garbage collection is not destruction.

What it means is that if there is some activity that must be performed before you no longer need an object, you must perform that activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup.

3.Garbage collection is only about memory.

The meaning of static

With the this keyword in mind, you can more fully understand what it means to make a method static. It means that there is no this for that particular method. You cannot call non-static methods from inside static methods (although the reverse is possible), and you can call a static method for the class itself, without any object. In fact, that’s primarily what a static method is for. It's as if you're creating the equivalent of a global method. However, global methods are not permitted in Java, and putting the static method inside a class allows it access to other static methods and to static fields.
Some people argue that static methods are not object-oriented, since they do have the semantics of a global method; with a static method, you don’t send a message to an object, since there’s no this. This is probably a fair argument, and if you find yourself using a lot of static methods, you should probably rethink your strategy. However, statics are pragmatic, and there are times when you genuinely need them, so whether or not they are "proper OOP" should be left to the theoreticians.

The use of "this"

The this keyword is used only for those special cases in which you need to explicitly use the reference to the current object.

  • It’s often used in return statements when you want to return the reference to the current object.

  • It is also useful for passing the current object to another method.

  • When you write several constructors for a class, there are times when you’d like to call one constructor from another to avoid duplicating code. You can make such a call by using the this keyword.
    While you can call one constructor using this, you cannot call two. In addition, the constructor call must be the first thing you do, or you’ll get a compiler error message.

  • Avoid conflict with member variable from method auto variable
    this.s = s;

    Where the first s is member, the second is a auto variable in a method.

Saturday, September 25, 2010

Default constructor

A default constructor (a.k.a. a "no-arg" constructor) is one without arguments that is used to create a "default object." If you create a class that has no constructors, the compiler will automatically create a default constructor for you.

However, if you define any constructors (with or without arguments), the compiler will not synthesize one for you!

When you don’t put in any constructors, it’s as if the compiler says, "You are bound to need some constructor, so let me make one for you." But if you write a constructor, the compiler says, "You’ve written a constructor so you know what you’re doing; if you didn’t put in a default it’s because you meant to leave it out."

Friday, September 24, 2010

"goto" in Java

The only place a label is useful in Java is right before an iteration statement. And that means right before — it does no good to put any other statement between the label and the iteration. And the sole reason to put a label before an iteration is if you’re going to nest another iteration or a switch inside it. That’s because the break and continue keywords will normally interrupt only the current loop, but when used with a label, they’ll interrupt the loops up to where the label exists:

label1:
outer-iteration {
inner-iteration {
//...
break; // (1)
//...
continue; // (2)
//...
continue label1; // (3)
//...
break label1; // (4)
}
}

In (1), the break breaks out of the inner iteration and you end up in the outer iteration. In (2), the continue moves back to the beginning of the inner iteration. But in (3), the continue label1 breaks out of the inner iteration and the outer iteration, all the way back to label1. Then it does in fact continue the iteration, but starting at the outer iteration. In (4), the break label1 also breaks all the way out to label1, but it does not reenter the iteration. It actually does break out of both iterations.

Foreach Syntax

Java SE5 introduces a new and more succinct for syntax, for use with arrays and containers. This is often called the foreach syntax, and it means that you don’t have to create an int to count through a sequence of items—the foreach produces each item for you, automatically.

foreach will also work with any object that is Iterable

The foreach syntax not only saves time when typing in code. More importantly, it is far easier to read and says what you are trying to do (get each element of the array) rather than giving the details of how you are doing it ("I’m creating this index so I can use it to select each of the array elements.").
Example:

control/ForEachFloat.java

The comma operator

Earlier in this chapter I stated that the comma operator (not the comma separator, which is used to separate definitions and method arguments) has only one use in Java: in the control expression of a for loop. In both the initialization and step portions of the control expression, you can have a number of statements separated by commas, and those statements will be evaluated sequentially.

Using the comma operator, you can define multiple variables within a for statement, but they must be of the same type.

Thursday, September 23, 2010

Casting

Java allows you to cast any primitive type to any other primitive type, except for boolean, which doesn’t allow any casting at all. Class types do not allow casting. To convert one to the other, there must be special methods.

Casting from a float or double to an integral value always truncates the number. If instead you want the result to be rounded, use the round( ) methods in java.lang.Math

Wednesday, September 22, 2010

Unsigned right shift operator

The signed right shift >> uses sign extension: If the value is positive, zeroes are inserted at the higher-order bits; if the value is negative, ones are inserted at the higher-order bits. Java has also added the unsigned right shift >>>, which uses zero extension: Regardless of the sign, zeroes are inserted at the higher-order bits. This operator does not exist in C or C++.

If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used, so you can’t shift more than the number of bits in a long.

For example:

int i = -1;
i >>>= 123; // For int, only low-order 5 bits of 123 will be used: 27
// So it is actually i >>>= 27
// Result is 31
System.out.println(i);


Refer to Page 43 for primitive type in Java

Tuesday, September 21, 2010

Shell Tips - Would be growing continuously

Every time looking for a small useful but seldom used tips all over the internet I hate it.


How to output backslash escapes useing echo?


From echo(1):

-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes (default)

So by default there is no backslash escapes! If you want, you have to do like this:

echo -e "\b\c"


What does exec do?


From bash(1):

exec [-cl] [-a name] [command [arguments]]
If command is specified, it replaces the shell. No new process is created. The
arguments become the arguments to command. If the -l option is supplied, the
shell places a dash at the beginning of the zeroth arg passed to command.
This is what login(1) does. The -c option causes command to be executed with
an empty environment. If -a is supplied, the shell passes name as the zeroth
argument to the executed command. If command cannot be executed for some reason,
a non-interactive shell exits, unless the shell option execfail is en-
abled, in which case it returns failure. An interactive shell returns failure
if the file can not be executed. If command is not specified, any redirections
take effect in the current shell, and the return status is 0. If there is a
redirection error, the return status is 1.

exec is useful when you want to set script redirection for all your scripts in current shell, otherwise you will have to set redirection for each.

exec 1>STDOUT_GOES_TO_HERE 2>STDERR_GOES_TO_THERE

After this, all following scripts running from this shell will redirect their STDOUT to STDOUT_GOES_TO_HERE and STDERR to STDERR_GOES_TO_THERE


Where to find ASCII?



man ascii


Using a Control Character in a Script


From UNIX POWER TOOLS
There are times when you need to use non-printing control characters in a script file. If you type them directly into the file, they can be invisible to printers and on your screen - or, worse, they can cause trouble when you print or display the file.

One time you might need to store control characters in a script is when you're writing sed substitution commands; you don't know what delimiters to use because the strings you're substituting could contain almost any text:

sed "s/$something/$whoknows/"

Because sed can use almost any character as the delimiter, you can use a control character like CTRL-A instead of the slash (/). Another time you might also need to use non-printable strings of characters is for controlling a terminal; you won't want to type an Escape character directly into the file.

The answer is to use a command that will create the control characters as the script runs - and store them in shell variables.

If your version of echo interprets an octal number in a string like \001 as its ASCII value, the job is easy. An octal-to-ASCII chart shows you that 001 is CTRL-A. You can store the output of echo in a shell variable, and use the variable wherever you need a CTRL-A character:

ca=`echo '\001'` # control-A character
...
sed "s${ca}$something${ca}$whoknows${ca}"


Remove ^M characters at end of lines in vi


UNIX treats the end of line differently than other operating systems. Sometimes when editing files in both Windows and UNIX environments, a CTRL-M character is visibly displayed at the end of each line as ^M in vi.

To remove the ^M characters at the end of all lines in vi, use:

:%s/^V^M//g


The ^v is a CONTROL-V character and ^m is a CONTROL-M. When you type this, it will look like this:

:%s/^M//g


In UNIX, you can escape a control character by preceeding it with a CONTROL-V. The :%s is a basic search and replace command in vi. It tells vi to replace the regular expression between the first and second slashes (^M) with the text between the second and third slashes (nothing in this case). The g at the end directs vi to search and replace globally (all occurrences).

__CONTINUED__

Wednesday, September 15, 2010

COPY support of PostgreSQL

For details refer to DBD::Pg document and

http://www.postgresql.org/docs/current/static/sql-copy.html


$dbh->do("COPY mytable FROM STDIN");
$dbh->pg_putline("123\tPepperoni\t3\n");
$dbh->pg_putline("314\tMushroom\t8\n");
$dbh->pg_putline("6\tAnchovies\t100\n");
$dbh->pg_endcopy;

Thursday, September 2, 2010

DBIx::Class primary key if underlying RDBMS table lack one

The Significance and Importance of Primary Keys

The concept of a primary key in DBIx::Class warrants special discussion. The formal definition (which somewhat resembles that of a classic RDBMS) is a unique constraint that is least likely to change after initial row creation. However this is where the similarity ends. Any time you call a CRUD operation on a row (e.g. delete, update, discard_changes, etc.) DBIx::Class will use the values of of the primary key columns to populate the WHERE clause necessary to accomplish the operation. This is why it is important to declare a primary key on all your result sources even if the underlying RDBMS does not have one. In a pinch one can always declare each row identifiable by all its columns:


__PACKAGE__->set_primary_keys (__PACKAGE__->columns);