Java for C# Programmers 2: String, Console, Enum

Strings

C# has string, Java has String.

Strings are handled similar in both languages. In both cases, strings are class types and are immutable: String methods which seem at first to change the underlying object do not change this object, but create a new one and return the new one.

Escaping in string literals is the similar as in C#. Java knows

  • "\t, \n" and the like.
  • "\u20ac" for unicode characters.
  • Java understands "\065" as the octal value 065. This is not available in C#.
  • Java has no equivalent to the @ prefix for string constants. But it understands slashes as path separators, also on Windows.
  • Java does not understand "\x123" where 123 is interpreted as hex value.

Both languages have got also mutable string-like classes. C# has StringBuilder (not thread-safe). Java has StringBuilder (not thread-safe) and StringBuffer (thread-safe).

Like in C#, indexOf returns -1 if the searched string is not found.

string s = "abc";
int n = s.IndexOf("c", 7); // n = -1, no exception  

Gotcha: In Java, string comparison with == does not compare the contents. In C# it does. In Java, you have to use the function equals(..) to compare the contents of strings.

String Formatting

Java supports the old and well known C string formatters. C# doesn’t.

System.out.printf("Creating date: %02d.%02d.%04d", 10, 4, 2014); 
        // 10.04.2014

String s = String.format(">%6.2f<", 3.14159265359);  
        // s is  >  3,14< in Germany.
        // Yes, like in C#, the locale is used for formatting.

s = String.format(Locale.ENGLISH, ">%6.2f<", 3.141592);  
        // s is >  3.14<.

String Parsing

// Java
int i = Integer.parseInt("22"); 
int j = Integer.parseInt("ab");  // NumberFormatException

Java does not have TryParse functions.

Console

Output to Stdout

Output to stdout is done via System.out.print*.

System.out.println();           // only newline
System.out.println("abc");      // abc + newline
System.out.print("abc");        // abc without newline
System.out.print("abc\n");      // abc + newline
System.out.print("a" + "bc" + "\n");      // abc + newline

Java does not support C#-like formatted printing with {0} and {1} and so on. Instead, it supports formatted printing with a C-like printf function with some extensions. I'm giving some examples here but won't go into details.

System.out.printf("'%d'", 3);       //  '3'
System.out.printf("'%3x'", 10);     //  '  a'
System.out.printf("'%03d'", 3);     //  '003'
     String[][] z = {
            { "Name", "Anna" },
            { "Age", "27" },
            { "Sex", "Female" },
     };
     for (String[] s : z) 
         System.out.printf("%-5s:%7s", s[0], s[1]);

     // This prints:

    Name :  Anna
    Age  :     19
    Sex  : Female

Find a tutorial of Java's string formatting possibilities with printf and format there: http://docs.oracle.com/javase/tutorial/essential/io/formatting.html. And find the full format string syntax here:
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax.

Input From Stdin

        System.out.print("\nEnter your weight:");
        double weight = sc.nextDouble();
        sc.nextLine(); // needed to consume the enter-key  
                       // left by the input of the double 

        System.out.print("\nEnter your name:");
        String name = sc.nextLine();

        System.out.print("\nEnter your size in cm:");
        int size = sc.nextInt();

        System.out.printf("\nWeight: %g   Name: %s   Size: %d", 
            weight, name, size);

Gotcha: After

Scanner sc = new Scanner(System.in);
sc.close();
sc = new Scanner(System.in);
sc.nextInt();

you'll get an NoSuchElementException in the last line. It is because sc.close() closes not only the Scanner, but also the System.in stream. Which cannot be reopened. So if you want to have a Scanner in your program which is bound to System.in, you can not close it if you may need it any time later in the same program.

Enums

There are enums in both languages, but there are huge differences. In C#, enums are implemented very similar to C and C++, as some special integers. They are derived from type Enum which is derived from one of the integer value types.

In Java, enumerations are also derived from a type called Enum, but this is a class, a reference type. There are no traces of underlying integers like in C#.

Like classes, enums can be defined in an own source file, as a subtype of another class or as a non-public type in a source file with another public type.

public enum Fruit { BANANA, ORANGE, APPLE, LEMON, PEAR };

or

public class A 
{
    enum SortOrder { ASCENDING, DESCENDING };
}

or

public class A 
{
   ...
}
enum Erinyes { Alecto, Megaera, Tisiphone };

The main methods of Enum are shown here.

Fruit a = Fruit.BANANA;
System.out.println(a.name());       
    // -> BANANA    name()  is not overridable
System.out.println(a.toString());   
    // -> BANANA    toString() is overridable

Fruit b = Fruit.valueOf("APPLE");   // Create an enum from its name  
System.out.println(b.name());       // APPLE    

// Create an enum from its name, 2nd possibility:

Fruit c = Enum.valueOf(Fruit.class, "ORANGE");  

// The ordinal() value is used to sort enums. 
// You cannot change the ordinal value
// aside of by changing the order in the definition. 
System.out.printf("%s:%d\n", c, c.ordinal());   // ORANGE:1
System.out.println(a.compareTo(b));             // -2     

for(Fruit i: Fruit.values())        
    System.out.printf("%s:%d ", i.name(), i.ordinal());  
    // -> BANANA:0 ORANGE:1 APPLE:2 LEMON:3 PEAR:4

// In contrast to Java's behaviour for strings, 
// the == operator for enums does what you expect.         

Fruit d = Fruit.ORANGE, e = Fruit.ORANGE;
if(d == e)
    System.out.println("==");       // ==
if(d.equals(e))
    System.out.println("equal");    // equal

Fruit k = Fruit.valueOf("Grapple"); // IllegalArgumentException    

Flags

In C#, you can define and use a set of flags like this:

[Flags]
enum Spices { None, Salt=1, Pepper=2, Chili=4, Paprika=8 };

void Main() 
{
    Spices x = Spices.Salt | Spices.Pepper;
    Console.WriteLine(x);               // Salt, Pepper
}

This is not possible in Java. In Java, you have to use a set of enums to represent flags. The type EnumSet is designed for that.

enum Spices { SALT, PEPPER, CHILI };

EnumSet s = EnumSet.noneOf(Spices.class);   // s is empty. 
s = EnumSet.allOf(Spices.class);  // s is (SALT | PEPPER | CHILI)

s = EnumSet.of(Spices.PAPRIKA, Spices.CHILI);   // s is (PEPPER | CHILI)

s = EnumSet.complementOf(s);                    // s is (SALT)

EnumSet z = EnumSet.copyOf(s);          // z is (SALT) 
System.out.println(z);                          // [SALT]

Enum With Methods, Properties And Constructors

You can add methods and properties to an enum like to any ordinary class. You can override virtual methods and you can add constructors. You cannot create an enum that is derived from another enum.

public enum Flavors { SWEET, SOUR, SPICY };

public enum Fruit 
{ 
    BANANA(EnumSet.of(Flavors.SWEET)),
    ORANGE(EnumSet.of(Flavors.SWEET, Flavors.SOUR)),
    LEMON(EnumSet.of(Flavors.SOUR));

    private Fruit(EnumSet flavors)
    {
        this.flavors = flavors;
    }

    @Override
    public String toString()
    {
        return name().toLowerCase() + flavors.toString();
    }

    public String toGerman()
    {
        switch(name())
        {
            case "BANANA":
                return "Banane";
            case "ORANGE":
                return "Orange";
            case "LEMON":
                return "Zitrone";
        }
        return null;
    }

    private EnumSet flavors;
};

System.out.println(Fruit.BANANA.toString());   // banana[SWEET]    

System.out.println(Fruit.ORANGE);              // orange[SWEET, SOUR]

System.out.println(Fruit.LEMON.toGerman());    // Zitrone

Java for C# Programmers, Part 1: Primitives

This is part 1 of a series of articles about Java for C# Programmers.

  • I strive to present a terse but complete depiction of the differences between Java and C#, from the point of view of an experienced C# programmer.
  • I do not strive to present a a complete reference of the Java language here. A complete reference for Java can be found on http://docs.oracle.com/javase/tutorial/java/.
  • Gotcha: Facts that are really unexpected for a C# guy are labeled Gotcha.

How Came?

  • Currently, I’m doing a Java course. While learning, I’m writing down what I’ve learned, as a reference for other C# guys and myself.
  • Java is a programming language. As such, it is a developer tool. It is public since 1995. A time-tested one, too 😉

Identifiers

In both languages, indentifiers must not start with a number and must not contain spaces. Aside of these rules, most characters are allowed. Including german umlauts ÄÖÜ and currency symbols. Äöüß$$€ is an allowed indentifier.

Naming Conventions

  • Classes and interfaces: First letter uppercase. Rest camel cased.
  • Packages: lowercased, no _ separators. package bananaboat;. When you have a lot of packages, subdivide names by dots. app.boats.bananaboat
  • Use pascal cased nouns for class names. Banana, BookDocument
  • Use adjectives for interface names, without leading I. Eatable, Printable
  • Methods: First letter lowercase. Rest camel cased. Verbs. getPrinter()
  • Variables: Like methods. myFruit. Use short names for short lived variables. int i.
  • Constants: All uppercased, _ as separator. MAX_WIDTH

Primitive Data Types

It is all the same as in C#, aside of the following differences.

  • The unsigned integer types do not exist in Java.
  • Gotcha: This means byte is signed in Java.
  • The high precision floating point type decimal does not exist in Java.
  • bool is called boolean.
  • C#’s nullable bool? type supports ternary logic with the & and | operators. There is no equivalent in Java.
  • Pointers and tuples do not exist in Java.
  • In Java, the primitive types are not derived from object. (In C# they are, via Object -> ValueType -> primitive type.)
  • Gotcha: Java’s Date is a reference type but C#’s DateTime a value type.
  • There is no TimeSpan in Java.

Literals

Mostly the same as in C#.

Gotcha: In Java, integer literals starting with a zero are interpreted as octal values. Not so in C#.
int i = 077; // Java: i is 63 decimal

Gotcha: In the following piece of code, the longWithoutL constant is calculated as int and then just assigned to the long. In C#, you’ll get a compile error when making such a mistake.

long longWithL = 1000*60*60*24*365L;
long longWithoutL = 1000*60*60*24*365;
System.out.println(longWithL);    // 31536000000
System.out.println(longWithoutL); // 1471228928

Additionally, binary notation for integer type values
is allowed.

int eleven = 0b1011;        // 11 decimal
int minuseleven= -0b1011;   // -11 decimal
byte minusone =         // Compile error. Byte is signed.  
         0b11111111;    //  You can use only 7 bits in 0b notation. 
byte b = -0b1;          // -1 decimal

Wrapper Classes / Boxing / Unboxing

In Java, the primitve types are not derived from Object. Probably because of this, you cannot use them in generics, cannot pass them by reference and they have no methods.
But for every primitive data type, there is a wrapper class which you can use in generics and has generally the same behaviour as the primitive type.

  • They are called Byte, Short, Integer, Long. Float, Double, Boolean. Character, ….
  • Automatic conversion to and from the primitive types works well.
  • You cannot use these wrapper classes to do a pass by reference for primitive types.
  • Some standard functions are implemented on these wrapper classes, e.g. toString().

Java’s Atomic Wrapper Classes

There is another type of wrapper classes available in Java. They are called Atomic Wrapper Classes.

  • AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference.
  • There is no automatic conversion to and from these types.
  • You can change their value and so they can be used for pass by reference of primitive types.
  • They are thread safe.
  • They implement a lot of functions in an atomic way, like incrementAndGet(), getAndAdd(int delta) and the like.

Pass By Ref of Primitive Data Types

static void Test()
{
    AtomicInteger i = new AtomicInteger();
    i.set(3);
    passByRef1(i);
    System.out.println("i: " + i);      // i: 4

    int[] j = { 3 };
    passByRef2(j);
    System.out.println("j[0]: " + j[0]);    // j[0]: 4

    Integer k = 3;
    passByRefNotGood(k);
    System.out.println("k: " + k);      // k: 3   **GOTCHA**
}

static void passByRef1(AtomicInteger i)
{
    i.incrementAndGet();
}

static void passByRef2(int[] i)
{
    i[0]++;
}

static void passByRefNotGood(Integer i)
{
        i += 1;     // **GOTCHA** This does NOT increment the 
                    // outer Integer, but there's no compile error.
}

Unboxing of Numbers in Calculations

// C#:
int? a = null, c = 3;
int? b = c * a;        // b becomes null.

bool? d = false, e = null;
bool? f = d & e;       // f becomes false. Ternary logic.   
bool? g = d | e;       // g becomes null. Ternary logic.  

// Java: 
Integer a = null, c = 3;   
Integer b = c * a;      // NullPointerException happens. 

Boolean d = false, e = null;
Boolean f = d & e;      // NullPointerException.

Notepad++: How to Make the Function List work with Tcl and Bash

In another post about Notepad++ I critisized that its function list feature does not work for Tcl and Bash scripts. Now I’ve got a solution. Here is it.

How to Make the Function List Work for Tcl

Open functionList.xml in an editor.  FunctionList.xml is in %APPDATA%\notepad++ or in the installation directory of Notepad++.
Add this line to the section with all the other association-entries.

 

Add this to the section


    
        
            
        
    

Restart Notepad++. Credits for the solution go to Detlef of compgroups.net/comp.lang.tcl. I’ve copied his’ and shortened it a bit. And added support for bash.

How to Make the Function List Work for Bash

In functionList.xml add this line to the section with all the other association-entries.

 

Add this to the section


    
        
            
        
    

Restart Notepad++.

Download

Or just download my functionList.xml with Tcl and Bash support and replace yours.

Update: As Olivier from comp.lang.tcl pointed out, my version does not work with Npp 6.4.3. I’ve rechecked this, he is right. My version does work at least with versions 6.4.5, 6.5 and 6.5.5, though.

Update 2: Thanks to Rasha Matt Blais for his improved version of the mainExpr for bash functions. Though that one still misses some types of function definition. Here my latest mainExpr string:

mainExpr="^[\t ]*((function)[\s]+)[^\n]+|[\w_]+[\s]*(\([\s]*\))"

I’ve also adapted the downloadable functionList.xml. And I’ve added the testfunc.bsh file which contains some bash functions with which I’ve tested the my mainExpr string.

Why Zip Is a Better Archive Format than 7z

Scott Hanselmann declared 7z to be a much better format than zip and zip to be dying.
Or at least, this is how I understand his writing:

The 7z format is fast becoming the compression format that choosey hardcore users choose.

Though I’ve got a lot of respect for Scott, I have to add some facts.

Zip is Much Faster Than 7z

zip-7z-comparison.1 In my humble opinion, Scott has overseen that zip is much faster than 7z… I’ve done  tests with both formats and with both formats I’ve used compression methods 1 and 5. Some of the results are staggering.

 

Discussion of the Results

compressFullzip-7z-comparison.3

In the compressFull tests, a data set is compressed and added to a new archive.  As you can see above, compressing with zip-1 is around 4 times faster than compressing with 7z-1 and seven times faster than compressing with 7z-5. The resulting archive is only 6% bigger than the 7z-1 archive and 40% bigger than the 7z-5 archive. In my opinion, the much greater speed speaks clearly for zip.

extractFull

In the extractFull tests, all the files in the archive created by fullCompress are extracted locally. Here, the speeds are not too different, e.g. extracting from a zip-1 is only around 30% faster than from a 7z-5 archive. As the 7z archives are smaller, I rate this as a draw.

extractSome

zip-7z-comparison.2

In the extractSome tests, only a small number of all the files are extracted from the archive. Extracting from a zip-1 archive is 50% faster than from a 7z-1 archive and an astonishing twenty times faster than from a 7z-5 archive. As this is unbelievable, I have repeated the tests a lot of times. But it stays true. Victory by knockout for zip.

Test Details

  • I’ve done the tests on my oldish Fujitsu Siemens Lifebook S with a Dual Core Processor, running Win 7.
  • For both archive formats I’ve used the commandline version of 7-zip 9.20, controlled by tclkitsh.exe and the tcl script given below. It is the current and stable release of 7-zip. Unchanged since 2010.
  • The compression method 5 is in 7-zip the default value for both formats. Compression method 1 is the fastest compression method for both formats.
  • I’ve repeated each test several times. The standard deviation of the results have mostly been very small.
  • My data set has been a set of 2800 files with 192 MB uncompressed.
  • The files which are extracted in the extractSome test are 72 files with 68 kB uncompressed.

Reproduction of the Tests

You can reproduce the tests easily:

  1. Download my script zip-test.zip and tclkitsh.zip and extract both into the same directory.
  2. Open the file zip-test.tcl with a text editor and adapt the first three lines. In the first line, adapt the path to the 7z.exe file on your PC. In the second line, adapt the path to the directory you want to compress.
  3. Open a command window, cd to the directory where you’ve put zip-test.tcl and type in     tclkitsh zip-test.tcl
  4. Wait and don’t use the computer until the tests are finished.
  5. The results will be written on screen and at the same time appended to the file zip-test-results.txt.
  6. You should discard the first test, because for the first one, the speed is highly determined by the time you need to read data from the hard drive. In later runs, much of the data is in the OS’s drive buffer. So the first test is not comparable to the following ones. It does not measure compression speed, but hard drive speed. You’ll see that the first run (with zip-1) takes much longer than the following ones, even those with zip-5 or 7z-5.

Summary

  1. All operations on zip archives are much faster or as fast as the same operation on 7z archives.
  2. 7z archives are somewhat smaller than zip archives – but not much.
  3. My recommendation is:
    Use zip as archive type. If you are using the software 7-zip, do not use the default settings. Always use compressing method 1.

What is your opinion? I’d love to hear from you.

Personal Kanban and Kanbanpad: Two Top Productivity Tools For Everybody

What are “Personal Kanban” and “Kanban”?

A Kanban is a special type of a to-do list. It has been invented by the japanese car-maker Toyota in the nineteen-forties to steer its production lines. It is truly time-tested.

0401-203731-Personal Kanban 101 _ Personal KanbanOver the years, the Kanban principle has trickled into the software development industry. And not long ago people found out that what they use in their bureaus or factory buildings could be used for their private tasks, too.

Hence Personal Kanban has been born. In its simplest form, a Personal Kanban looks like the image above. The image is from Jim Benson’s famous Personal Kanban site. Jim has probably written the first book about Personal Kanban and has held a talk about the system at Øredev.

What you see above is a to-do list with some special features.

  • Tasks are noted on Post-Its.
  • Every column denotes a certain state of the tasks in it.
  • The tasks or Post-Its travel from left to right.
  • You should be working only on tasks in the column Doing. This column is also often called Work in Progress.
  • The number of tasks in the column Doing or Work in Progress is limited. The limit number usually is well below ten.

That’s all.

Why Does Personal Kanban Help You?

Yeah, I know, this system looks very simple. It looks too simple. It looks like a to-do list and not much more. But great traits emanate from the easy rules.

  • By having a limit on Work in Progress, you need to think about prioritization automatically.
  • By limiting the number of your Work in Progress tasks, you are automatically focusing on finishing tasks before starting new ones.
  • Because many tasks are visible on the board, you are automatically identifying problematic spots. And you get a good overview of your workload in total.
  • In a strange way it is motivating to be able to move the tasks from left to right. The Done column helps you to feel good about having accomplished something.

All this will happen when you are using a Personal Kanban. You don’t even need to put special effort into it.

Kanbanpad

For three years now, I am doing my own Personal Kanban with a free web-based tool called Kanbanpad instead of a whiteboard and stickers. Some say that a web based kanban is lacking the visibility, touchability and realness of a whiteboard kanban.

Kanbanpad

Kanbanpad


Update:
Kanbanpad is shutting down in March 2015 ;-( For the moment, I am using Portable Kanban.

But there are these

Seven Advantages of a Web Based Personal Kanban Over a Whiteboard Kanban

  1.  You do not need to uglify some precious wall space in your flat with a whiteboard.
  2.  You can put stuff there that shall not be seen by everybody who enters your flat.
  3.  You can add as many notes as you need to a task.
  4.  When tasks are done, they are still available later. It is sometimes quite useful to re-check the notes of a task that’s already done.
  5. You can create as many tasks as you want.
  6. No blizzard of flying Post-Its after opening a window.
  7. And, obviously, you can access the board from every place where you have got a web connection.

Remark

This post has been on my list for a long time. Martin’s blog parade about My Best Hints for Productivity has triggered me to finally write it. Thank you, Martin.

Discussion

What do you think of using a Personal Kanban? If you are already using a Personal Kanban, which type of tool do you use for it? I’d love to hear from you. Uuuund ich lese Kommentare auch gern in deutsch. 😉