Wednesday, October 31, 2012

What is that crazy Java ^ character?


Operators in Java – Basic Language Symbology for Beginners
Or… What does that crazy ‘^’ symbol mean anyway?

Java has (as of this writing in Java 1.7) 37 tokens that are designated as operators. (See the Java Language Specification http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.12”>here.
Non-assignment tokens are always evaluated left to right, with a set of precedence rules applied. Assignment tokens evaluate right to left. Order of precedence tells us that a complex statement with lots of operators will be guaranteed to be evaluated in a reliable order. I won’t cover the specifics of order in this entry… they’re very nicely charted in the Oracle Java Tutorial link at the end of this post.

An oft-asked question I receive from “future Java gurus” (beginners J) is, “What is that char and what does it mean?” Or “what is the difference between ‘&’ and ‘&&’?”

I know computer science training helps a lot, but if you’re like me, you might have bootstrapped yourself into software engineering without an official BS/CS degree completion. 

I thought I would encapsulate a few of the most common things that beginners tend to ask, and put them in human-readable form. This isn’t intended to be a be-all and define-all, just a quick post to get your head wrapped around a few less-commonly-used operators.

Remember: if your statement gets long and hairy, you can always break it down into smaller parts, or you can use parentheses to “force” precedence.

& The bitwise AND operator (applies to integral/primitive types) also works with booleans
int resultingInt = 12 & 15;
//resultingInt is now assigned with the integer 12
//it helps to understand the binary representations of the operands to see how this works
//homework: why 12?
| The bitwise inclusive OR operator (applies to integral/primitive types) also works with booleans
int resultingInt = 12 | 15;
//resultingInt is now assigned with the integer 15
//it helps to understand the binary representations of the operands to see how this works
//homework: why 15
^ the bitwise exclusive OR operator (applies to integral/primitive types) also works with booleans
int resultingInt = 12 ^ 15;
//resultingInt is now assigned with the integer 3
//it helps to understand the binary representations of the operands to see how this works
//homework: why 3?

&& the logical AND operator
boolean isTrue = boolean1 && boolean2;
//in English: “if boolean1 is true AND boolean2 is true, assign true to isTrue,
//else, assign false to isTrue”
//This operator is”fail fast.” If the first operand is false, the second isn’t evaluated.

|| the logical OR operator
boolean isTrue = boolean1 || boolean2;
//in English: “if boolean1 is true OR boolean2 is true, assign true to isTrue,
//else, assign false to isTrue”
variable = ? : ; The ternary operator
int firstYear = 0;
int lastYear = 12;
boolean isLastYearLater = lastYear < firstYear ? false : true;
//in English: “if last year is less than firstYear,
//assign false to isLastYearLater, else assign true to isLastYearLater”


Want to know more? Ask the source! The Java Tutorials have a nice concise up-to-date page here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html”> http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Want to see a glimpse of how the bitwise operators work? http://www.leepoint.net/notes-java/data/expressions/bitops.html">This is a good starting point.

Thursday, October 27, 2011

FedEx days - Time well spent

I recently participated in FedEx days development with my employer. It was an excellent opportunity to unwind my working mind and take a leap into creativity (my job is to fix and enhance existing technologies).

I truly enjoyed the opportunity to build some interesting handheld software. When the FedEx days project review was done, I had a small, if buggy :-), application to demonstrate. Everyone in the review took time to play with the application...

So what's so great about FedEx days? How can employers possibly benefit from having blocks of employees "go invisible" for a day or three (read: zero short-term standard tasks are expected from the employees, "regular" work is suspended and employees are insulated from daily work and responsibility)? Is it beneficial in the end analysis?


The short answer: "yes." Without question. A corporately-sponsored, well-organized, open-minded FedEx days experiment benefits companies' bottom lines and employees' work satisfaction.

To be more specific, I would strongly suggest that key ideas underlying corporate success include employee satisfaction, non-revenue-based R&D, and innovation. To that end, I would also strongly suggest that a successful company also (sometimes) needs to slow down in order to speed up.

FedEx days are R&D at its most productive and enjoyable. The vast majority of participants grow and learn to innovate during FedEx days. Employees and lower management have opportunities to take the stress-uniform off for a moment. The company gets potential ideas, services, or products that are as diverse as the employee base. Employees and lower management are encouraged to step out of the box and do projects that are not necessarily in their work domains: developers might work on a support project, support might work on a marketing project, or management may take the time to work on the producer level... Diversity and ideas are king and queen of successful long-term growth and sustainability.

Since FedEx days are not intended to boost the short term bottom line, some corporations may not take the brief expenditure for this kind of effort and activity. I think that short-term thinking is important at times, but must not be the driving force behind how work is always performed on every kind of project. Great things and services have come from the freedom to innovate. Many of the products we take for granted have their roots in projects that weren't begun with short-term profit in mind: rather, they were begun for the sake of growth, invention, and innovation.

FedEx days give the community of employees and management an opportunity to grow in an organic and fulfilling way.

Would I be more inclined to work well and to stay with my employer if they provided unfettered one-day (or more) breaks so that I could build a handheld application?

You bet.

Tuesday, September 27, 2011

IGYWWICYATT?

IGYWWICYATT?

What is that?

It's what you say at a meeting of developers when no one will speak: break the ice.

Like my dad used to do, walk into the crowded room (and not the one who called the meeting)...

"I guess you're wondering why I called you all together today?"

Wednesday, February 9, 2011

Object equality in Java - A view of a == b vs a.equals(b)

What's faster, object = = object or object.equals(object)?
Which one applies to my code?
Why do they return the same result sometimes and not others?
Are there systemic exceptions?

Some quick things:

* The "= = " operator returns true if the variables on each side of the operator point to the exact same exact object in memory.
* Some objects are kept in pools for optimization and the system skirts some "rules" to make things go better/faster - example, String objects


At the java.lang.Object level, .equals(Object) simply does this type of activity in its code (pseudo-code):
return this == someObjectPassedIn;
Also, at its elemental level, the = = operator is fundamental and very fast. And, if one's class hierarchy does not override .equals(Object), then .equals(Object) is also very fast.

If any object in the hierarchy of a given variable reference overrides .equals(Object), then it is possible that the .equals(Object) may be some amount slower, depending on what the override does.

For example:
Here’s something (pseudo-code!!!!) that causes a more expensive .equals(Object) method execution:
---snip---
public class SlowEquals extends Object {
    //here, we declare 13 different instance variables to make up
    //the state of this object… they’re Strings, Vectors, whatever is required for the design…
    private Vector someEmployeesOrSomething = new Vector();
    private String title = null;
    //…etc, lots more declarations
    //here we would have accessor behavior, like getSomeEmployeesOrSomething() here…
    public Vector getSomeEmployeesOrSomething(){
        return someEmployeesOrSomething;
    }

    //now, we override .equals(Object) because we want to see if the
    //objects are virtually the same data, for example
    public boolean equals(Object anObject){
        //here we go out fast when any of the state is diff than the same as us
        //plus we check to do some basic logic

        //if it is me, don’t waste cycles comparing my state, fall out
        if(this == anObject){
            return true;
        }
        //is it even the same class as me?
        //If it isn’t - fall out, if it is, then compute my state
        if( anObject instance of getClass()){ //remember, pseudo-code hee!
            //if it’s not the same object in memory, then compare state
            //here’s where things slow down from == a lot!
            //compare each of this object’s state to the passed in object’s state
            SlowEquals comparisonObject = (ComparisonObject)anObject;
            if(! comparisonObject.getSomeEmployeesOrSomething()).equals(getSomeEmployeesOrSomething()){
                return false;
            }
            //… repeat for every memember of my state, return false on any difference
        }
        //if we hit here, return false as a last and default case
        return false;
    }
}
---snip---


In many cases, developers do not override .equals(Object) in their object specializations, and in those cases, it is safe and fast to do .equals(Object). On the same side of the coin, if the developer has overridden .equals(Object), it is sometimes likely they meant for it to be used, regardless of cost: the object is saying that it wants to be compared in a very specific way.

What about String objects, you say? Strings are largely (sometimes entirely) pooled for performance and memory conservation
If the JVM supports it (MOST of the time, they do), String pooling is a technique whereby strings created during a program's execution are stored and used as actual object in memory for many variable references.
For example, if String pooling is supported (again, MOST of the time):
String myName1 = "TigrisDevelopus";
String myName2 = "TigrisDevelopus";
In this snippet of code, both of the following return true:
myName1 = = myName2; //true
and
myName1.equals(myName2); //true
This is true, even though there is no myName1 = myName2 line of code.

Inversely, the following would not work like String pooling: the code would make reference to two different object in memory:
Employee myEmployee1 = new Employee("Doe", "Jane");
Employee myEmployee1 = new Employee("Doe", "Jane");
myEmployee1 = = myEmployee1; //returns false
Whether or not .equals(Object) would return true would depend on whether or not Employee (or any of its parent classes) overrides .equals(Object) and looks at the value of the String passed in to the constructor.

Tuesday, January 25, 2011

JRat Profiling. Not just another JCool JName in the Java JUniverse

A colleague of mine recently asked about profiling and bottleneck-troubleshooting in his Java project.

It has been quite a while since I'd used a profiler or similar analysis tool. The landscape of profiling tools, particularly those that are free or nearly free, has changed dramatically over the past decade. If one uses Auntie Google to look for tools, one finds many sites with reviews, aggregations, and lots of sell-some-ads-while-we-regurgitate-the-work-of-others hits... It took a good bit of work to filter through to find a few good resources on the subject - particularly resources that are easy to understand and actually work.

I read about several of the low/no cost profilers and performance tools and found a couple that worked OK. But, as luck would have it, I happened upon JRat. The project hasn't been updated for  a while on SourceForge, but the 1 Beta 1 jar works great in my current (OSX 10.6, JDK 1.6.x) dev command environment, as well as direct use and embedded at runtime in Eclipse Ganymede. NOTE: the bleeding edge/latest jar does not work on any machine I tried... use the 1 Beta 1 jar!

JRat works for what I need. It's not a comprehensive soup-to-nuts solution, but it works reliably, repeatably, is nicely performant, and is quite easy to use. Five minutes of download and hookup, then I'm profilin'.

So, how do we use it? Well, the Quick Start guide at the JRat SourceForge site is pretty much what you need. Skip the spammy regurgitation aggregation make-money-on-everyone-elses-writing pages and go here first. Let's repeat a bit: Skip the interweb tubes junk that's designed to smarm other people's work and go to the quick start on the JRat SourceForge page.

Now, with that said: You've got Ganymede running, you've got a runnable project, and you've read the instructions on SourceForge... here's a little bit of an example: with your project selected, choose to edit your run/debug configuration(s), and put in the following:
java -javaagent:shiftone-jrat.jar [if your program needs options, put them here, separated by spaces] [put the name of your main class here... remember: don't use the .class extension. For example: com.tigris.developus.JimsKewlApp]

The important takeaway is that the -javaagent argument is passed to the Java Virtual Machine and says, "hey, use this tool for a java agent", and the :shiftone-jrat.jar part says, "use this particular jar as the bytecode to run when agent callbacks are made.

Something of note for n00bs: the :shiftone-jrat.jar part means this - the shiftone-jrat.jar file is in the current directory. If your JRat jar is elsewhere, you'll need to use the full path...

How do you look at the results, anyway? It's really kind of easy. The quickstart guide gives us the syntax... just make sure you have a working command prompt (where you can type in java and it will run a JVM), CD to the directory where your shiftone-jrat.jar file is and:
java -Xmx256M -jar shiftone-jrat.jar

If all is well with your environment, a small window will open, and you can use it to open a JRat output file and browse it for all kinds of great runtime profile information.

Questions? Drop me a note.

jimp

Let's blog about software engineering

Welcome to the Tigris Developus blog!

I'll be musing about developing in Java (and other fun stuff, too.

Altough I am lucky enough to be employed by a Very Cool Company, I'm writing this blog as a function of my own desire to write. Thank you, Margaret, for encouraging me to write and to be creative.

jimp