Java for C# Programmers 7: Binaries

Source Code and Binaries Organization

Source Code

  • Every source code file must contain maximally one public class. There may be more than one non-public classes.
  • The name of the public class – if there is any – must be identical to the first part of the source code file.
  • Source code file: MyLove.java -> public class MyLove
  • Partial classes are not allowed.

Binaries

  • From MyLove.java a MyLove.class is created. The .class file contains the Java bytecode of the associated .java file.
  • From .class files and ressources a XYZ.jar (Java ARchive) can be created. A jar file is mainly a zip file of its contents, maybe with an added metadata file and the file extension .jar instead of .zip.
  • In principle, a jar file is something similar to an assembly or dll in .NET. The term jar hell is well known to Java developers.
  • A jar file can be a runnable jar file or a library.
  • The jar commandline program can be used to create or inspect jar files. It is a zip program with tar like syntax.
  • jar tvf XYZ.jar shows a verbose content listing of XYZ.jar.
  • In Eclipse, use File - Export - Java to create a jar file.

Runnable Jar Files

  • A runnable jar file is a an ordinary jar file with an added manifest file which contains an entry for the main class.
  • The main class must have a public static void main(String[] args) method. This method will be called when the jar is run.
  • The manifest file is an ordinary UTF-8 encoded text file called MANIFEST.MF located in the folder META-INF. It can contain information about signing, version control, package sealing and others.

An entry for a main class may look like this

Main-Class: Gaming.TraceOfDeathEngine

Here, Gaming is the package name and TraceOfDeathEngine is the class name.

Create a Runnable Jar, V1

  • This method will pack all the files of the project into the jar file. There is no way here to select which files shall be included in the jar and which shall not. But as a jar file is an ordinary zip, you can remove superfluous files afterwards. Or see method 2.
  • In Eclipse use File - Export - Java - Runnable JAR file to create an executable jar file.
  • On the the following page, select your main class under Launch configuration and input the file path of the jar file that shall be created.

Create a Runnable Jar, V2

  • This method will pack only selected files of the project into the jar file.
  • In Eclipse in the Package Explorer select the project or package which contains most of the stuff that shall be included in the jar.
  • Use File - Export - Java - JAR file. (Do not select Runnable JAR here. You can create a runnable jar anyway.)
  • On the the following page, select the Java- and resource files you want to have in the jar. Also set the export destination.
  • On the fourth page, select Generate the manifest file at the top and at the bottom select your Main class.

Create a Runnable Jar, V3

If you don’t use Eclipse or want to automate creating a runnable jar file, you can use the jar utility.
An example:

jar -cvfe troz.jar  Gaming.TrodEngine Gaming

The command line above explained:

c: create new jar file
v: be verbose
f: specify archive file name
e: pass entry point, create manifest automatically
troz.jar:          the archive file name
Gaming.TrodEngine: the entry point is class `TrodEngine` 
                   in package `Gaming`
Gaming:            the folder to include in the jar. 

If you have already a created manifest you can pass it to the jar utility with the m option. Jar will then add it to the jar file as META-INF/MANIFEST.MF

jar cvfm trox.jar  mf.txt Gaming

As said, the jar utility program has tar like syntax. So the line above means:

c: create new jar file
v: be verbose
f: specify archive file name
m: include manifest file
trox.jar: the archive file name
mf.txt:   the manifest file name
Gaming:   the folder to include in the jar. 

Some quirks of the jar utility:

  • The archive file and the manifest file (or the entrys point) must be specified in the same order as the f , m and e flags.
  • If any “file” is a directory then it is processed recursively.
  • It is not allowed to split the options up. tar cvf trox.jar m MAN Gaming is not possible.

Start a Java Program On Windows

On Windows, when Java is installed properly, you can doubleclick a runnable jar file from Windows Explorer to start it. Or you can create a shortcut and place it onto the desktop and use the shortcut to start the java program. You cannot attach such a shortcut to the taskbar, though.

To start a runnable abc.jar via commandline and pass parameters param1 and param2 to the main classes main method, just call

java.exe -jar abc.jar param1 param2

You can also start a Java program if you don’t have a jar file, but only the needed .class files. To do this Java.exe must be called from the bin directory one level above the package name. When the class to start is called MyLove and resides in the package Xcv and the parameters param1 and param2 shall be passed, the command line shall look like this:

java.exe Xcv.MyLove param1 param2

Create a Windows .exe File

To create an executable Windows exe file, you can use launch4j. More details about launch4j are given there (scroll down to method 3 of 3): http://www.wikihow.com/Create-an-Executable-File-from-Eclipse

There are several other possibilities to create a Windows .exe file, namely using Java Web Start technology or an Ahead Of Time compiler or …
A good overview about the available technologies is given here:
http://www.excelsior-usa.com/articles/java-to-exe.html

Libraries

Jar files may be used as libraries and there are zillions of publicly available jar libraries.

This example shows you how to add a MySQL connector library to your Java project.

  1. Download the zipped Java connector for MySQL from there:
    http://dev.mysql.com/downloads/connector/j. Select Platform Independent and ZIP Archive.
  2. Extract the package and copy just the mysql-connector*.jar file to somwhere below your workspace. I’d recommend a directory called lib which is a sibling of your bin directory.
  3. In Eclipse, add the jar file to your lib path via Project - Properties - Java Build Path - Libraries - Add External Jars...
  4. This will add the library to your project. Afterwards, you’ll see the library in the Package Explorer under Referenced Libraries.

Java for C# Programmers 6: Extended Technologies

In job advertisements for Java developers, the following acronyms and technologies are mentioned often.
For a C# developer, all of these are unknown at first. So what do they stand for?
I am providing short explanations, often copied from Wikipedia or Stackoverflow. Copied explanations are marked as quotations. The number of mentionings of a technology in job openings is in parentheses added to the end of the acronym, if it is bigger than one. Of course, I did no representative research. I just counted the words I noticed in some of the Java job ads I scanned.

ActiveMQ

Apache ActiveMQ is an open source message broker written in Java together with a full Java Message Service (JMS) client. It provides “Enterprise Features” which in this case means fostering the communication from more than one client or server. Supported clients include Java via JMS 1.1 as well as several other “cross language” clients.

Ajax (2)

Ajax is short for Asynchronous JavaScript and XML.

It is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously without interfering with the display and behavior of the existing page.

Ant (2)

Apache Ant is a software tool for automating software build processes. It is similar to Make but is implemented using the Java language, requires the Java platform, and is best suited to building Java projects.

Eclipse (2)

Eclipse is an open source multi-platform IDE written in Java. Its size and ambition are similar to Microsoft’s VisualStudio. Where VisualStudio is the standard to develop for .NET, Eclipse is the standard IDE to develop in Java.

EJB

Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications.

The EJB specification is one of several Java APIs in the Java EE specification. EJB is a server-side model that encapsulates the business logic of an application. …

The EJB specification intends to provide a standard way to implement the back-end ‘business’ code typically found in enterprise applications (as opposed to ‘front-end’ interface code). Such code addresses the same types of problems, and solutions to these problems are often repeatedly re-implemented by programmers. Enterprise JavaBeans are intended to handle such common concerns as persistence, transactional integrity, and security in a standard way, leaving programmers free to concentrate on the particular problem at hand.

Not to be confused with JavaBeans.

ExtJS

Ext JS is a pure JavaScript application framework for building interactive web applications[1] using techniques such as Ajax, DHTML and DOM scripting.

Ext JS includes a set of GUI-based form controls (or “widgets”) for use within web applications:

  • text field and textarea input controls
  • date fields with a pop-up date-picker
  • numeric fields
  • list box and combo boxes
  • radio and checkbox controls
  • html editor control
  • grid control (with both read-only and edit modes, sortable data, lockable and draggable columns, and a variety of other features)
  • tree control
  • tab panels
  • toolbars
  • desktop application-style menus
  • region panels to allow a form to be divided into multiple sub-sections
  • sliders
  • vector graphics charts

Many of these controls can communicate with a web server using Ajax.

Hibernate (5)

is a Java-OR-Mapper. Ref: http://en.wikipedia.org/wiki/Hibernate_%28Java%29 NHibernate is a .NET port of Hibernate.
Here you can see a comparison of NHibernate and Entity Framework. http://weblogs.asp.net/ricardoperes/archive/2012/06/07/differences-between-nhibernate-and-entity-framework.aspx

Connected to Hibernate is HQL, the Hibernate Query Language.

GWT

Google Web Toolkit, or GWT Web Toolkit, is an open source set of tools that allows web developers to create and maintain complex JavaScript front-end applications in Java. Other than a few native libraries, everything is Java source that can be built on any supported platform with the included GWT Ant build files. It is licensed under the Apache License version 2.0.

GWT emphasizes reusable approaches to common web development tasks, namely asynchronous remote procedure calls, history management, bookmarking, UI abstraction, internationalization, and cross-browser portability.

Jasper Reports

JasperReports is an open source Java reporting tool that can write to a variety of targets, such as: screen, a printer, into PDF, HTML, Microsoft Excel, RTF, ODT, Comma-separated values or XML files.

It can be used in Java-enabled applications, including Java EE or web applications, to generate dynamic content.

JavaBeans

JavaBeans are reusable software components for Java. They are classes that encapsulate many objects into a single object (the bean). They are serializable, have a 0-argument constructor, and allow access to properties using getter and setter methods.

Not to be confused with Enterprise JavaBeans.

Java EE, J2EE (5)

Java EE stands for Java Enterprise Edition. Beofre Java 5, it was called Java 2 Platform, Enterprise Edition, with the abbreviation J2EE.

J2EE is actually a collection of technologies and APIs for the Java platform designed to support “Enterprise” Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements.

In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over he last 5 years. It really is about the class of problems that are being solved more than anything else. Transactions and distribution are key.

It is important to understand that Java EE is a set of specifications and there do exist several implementations.

The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols. In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.

The 13 core technologies that make up J2EE are:

  1. JDBC
  2. JNDI
  3. EJBs
  4. RMI
  5. JSP
  6. Java servlets
  7. XML
  8. JMS
  9. Java IDL
  10. JTS
  11. JTA
  12. JavaMail
  13. JAF

JBoss (2)

WildFly, formerly known as JBoss AS, or simply JBoss, is an application server authored by JBoss, now developed by Red Hat. WildFly is written in Java, and implements the Java Platform, Enterprise Edition (Java EE) specification. It runs on multiple platforms.

And about Java application servers:

In the case of Java application servers, the server behaves like an extended virtual machine for running applications, transparently handling connections to the database on one side, and, often, connections to the Web client on the other.

JDBC (2)

JDBC means Java DataBase Connectivity.

JDBC is a Java-based data access technology (Java SE platform). This technology is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.

Some examples using JDBC and a MySql database are given in chapter…

Jenkins

Jenkins is an open source continuous integration tool written in Java. The project was forked from Hudson after a dispute with Oracle.

JHat, JMap, JStack

JHat: Java Heap Analysis Tool; The jhat command parses a java heap dump file and launches a webserver. jhat enables you to browse heap dumps using your favorite webbrowser.

JMap: Java Memory Map; jmap prints shared object memory maps or heap memory details.

Jstack: Jstack prints Java stack traces of Java threads for a given Java process or core file or a remote debug server.

JPA

The Java Persistence API, sometimes referred to as JPA, is a Java programming language application programming interface specification which describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition.

Hibernate is an implementation of the Java Persistence API. JPA only supports RDBMS as underlying system.
JPQL: Java Persistence Query Language

JSF, JSFUnit (2)

JavaServer Faces (JSF) is a Java specification for building component-based user interfaces for web applications. It … is part of the Java Platform, Enterprise Edition.

JSFUnit is a test framework for JSF applications. It is designed to allow complete integration testing and unit testing of JSF applications using a simplified API.

JSP

JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types. Released in 1999 by Sun Microsystems,[1] JSP is similar to PHP, but it uses the Java programming language.

JUnit (4)

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit

Maven (3)

Maven is a build automation tool used primarily for Java projects. Maven addresses two aspects of building software: First, it describes how software is built, and second, it describes its dependencies. Contrary to preceding tools like Apache Ant it uses conventions for the build procedure, and only exceptions need to be written down.

Play

Play is an open source web application framework, written in Scala and Java, which follows the model–view–controller (MVC) architectural pattern. It aims to optimize developer productivity by using convention over configuration, hot code reloading and display of errors in the browser.

RESTEasy

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications.

Spring (7)

The Spring Framework is an open source application framework and inversion of control container for the Java platform. The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Although the framework does not impose any specific programming model, it has become popular in the Java community as an alternative to, replacement for, or even addition to the Enterprise JavaBean (EJB) model.

The Spring Framework includes these modules:

  • Inversion of control container: configuration of application components and lifecycle management of Java objects, done mainly via dependency injection
  • Aspect-oriented programming: enables implementing cross-cutting concerns.
  • Data access: working with relational database management systems on the Java platform using JDBC and object-relational mapping tools and with NoSQL databases
  • Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects
  • Model–view–controller: an HTTP- and servlet-based framework providing hooks for extension and customization for web applications and RESTful web services.
  • Remote access framework: configurative RPC-style marshalling of Java objects over networks supporting RMI, CORBA and HTTP-based protocols including web services (SOAP)
  • Convention over configuration: a rapid application development solution for Spring-based enterprise applications is offered in the Spring Roo module
  • Authentication and authorization: configurable security processes that support a range of standards, protocols, tools and practices via the Spring Security sub-project (formerly Acegi Security System for Spring).
    Remote management: configurative exposure and management of Java objects for local or remote configuration via JMX
  • Messaging: configurative registration of message listener objects for transparent message-consumption from message queues via JMS, improvement of message sending over standard JMS APIs
  • Testing: support classes for writing unit tests and integration tests

Struts (2)

Apache Struts was an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture.

Swing (2)

Swing is the primary Java GUI widget toolkit. It is part of Oracle’s Java Foundation Classes (JFC) — an API for providing a graphical user interface (GUI) for Java programs.

Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists.

Swing is written in Java and built on top of AWT and Java 2D.

SWT

SWT is short for Standard Widget Toolkit. It is a graphics toolkit competing with Swing and AWT. Like AWT and unlike Swing, SWT uses elements and widgets which are native on the underlying OS.

Tomcat (2)

Apache Tomcat (or simply Tomcat, formerly also Jakarta Tomcat) is an open source web server and servlet container developed by the Apache Software Foundation (ASF). Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a “pure Java” HTTP web server environment for Java code to run in.

Wicket

Apache Wicket, commonly referred to as Wicket, is a lightweight component-based web application framework for the Java programming language conceptually similar to JavaServer Faces and Tapestry.

Java for C# Programmers 5: Date & Time

Date, Calendar And Joda-Time

Very early developers found out that Java’s Date class is bad and it is not possible to improve it. Because of this, most methods of Java’s Date class are deprecated now and early the class Calendar has been added.

But soon after adding Calendar, people realized that Calendar is not very good as well. Then development of the successor API Joda-Time started.

Joda-Time is available from Java SE 8 on. It is located in the namespace java.time and contains the main classes LocalDate, LocalTime and LocalDateTime. Joda-Time contains full support of timezones with classes ZoneId, ZonedDateTime, OffsetTime, OffsetDateTime and ZoneOffset. The older class java.util.TimeZone is deprecated.

Joda-Time supports periods of time with the classes Period and Duration. Both are similar to C#’s TimeSpan. Period and Duration deal with different precisions.

// 3 years, 2 months, 1 day
Period period = Period.of(3, 2, 1);

// You can modify the values of dates using periods
LocalDate newDate = oldDate.plus(period);

// Components of a Period are represented by ChronoUnit values
assertEquals(1, period.get(ChronoUnit.DAYS)); 

// A duration of 3 seconds and 5 nanoseconds
Duration duration = Duration.ofSeconds(3, 5);

As expected, you can add and subtract durations and you can modify date values with durations.

Joda-Time also contains

  • Chronolgy and associated classes to represent calendars different from the Gregorian calendar.
  • MonthDay to represent a birthday.
  • YearMonth to represent a credit card expiration date.

From Java SE 8 on all three date-time systems (Date, Calendar and Joda-Time) exist in Java in parallel.

Date Formatting

Locale Specific

It is easy to format a Date in a localized way.

DateFormat daf = DateFormat.getDateInstance(DateFormat.SHORT, 
        Locale.German);
Date now = new Date();         // new Date() is now. 
String s = daf.format(now);    // "15.05.14"  for 15th of May 2014

DateFormat tif = DateFormat.getTimeInstance(DateFormat.SHORT, 
        Locale.German);
String z = tif.format(now);    // "09:54"     for 9:54 AM

// uses the current locale
DateFormat.getDateInstance(DateFormat.SHORT); 

// long date and short time combined
DateFormat dtf = DateFormat.getDateTimeInstance(DateFormat.LONG,
        DateFormat.SHORT, Locale.GERMAN);
String a = dtf.format(now);   // "15. Mai 2014 09:54"

These are the available style constants and the resulting output for 15th of May 2014, 09:51:17 o’clock with locale ENGLISH.

Style Date Time
DateFormat.SHORT 5/15/14 9:51 AM
DateFormat.MEDIUM May 15, 2014 9:51:17 AM
DateFormat.LONG May 15, 2014 9:51:17 AM CEST
DateFormat.FULL Thursday, May 15, 2014 9:51:17 AM CEST

Extended Date Formatting

You have full control over your date format with the class SimpleDateFormat and format placeholder strings.

    now = new Date(114, 0, 17, 14, 15, 16);  

    daf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(daf.format(now));        // 2014-01-17 14:15:16

    daf = new SimpleDateFormat("dd. MMM yy HH:mm");
    System.out.println(daf.format(now));        // 17. Jan 14 14:15

Gotcha: The format strings in Java are quite similar to those used in C#, but not identical. Look there for details:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html.

Date Oddities

If you are using Java’s Date, be aware of its oddities.

  • getMonth() is zero-based.
  • getDay() returns the day of week, not the day of month.
  • getDate() returns the day of month, 1-based.
  • getYear() returns the gregorian year minus 1900.

If today was Tuesday, 13th of May 2014…

Date d = new Date();
String z = String.format("%04d-%02d-%02d", 
        d.getYear(), d.getMonth(), d.getDay());
System.out.println(z);

Gotcha: this would print 0114-04-02. Not one of the three numbers is what I would have expected before having studied the intricacies of Date.

Stopwatch

There’s nothing like C#’s Stopwatch in plain Java. There are stopwatches available in org.apache.commons.lang.time.StopWatch and one in com.google.common.base.Stopwatch.

If you don’t want to pull in these packages, you can use
System.currentTimeMillis() or System.nanoTime() to imitate a simple stopwatch.

Function Returns
System.currentTimeMillis() Returns the current time in milliseconds. Date d = new Date(System.currentTimeMillis()) will represent the current time.
System.nanoTime() Returns nanoseconds since some fixed but arbitrary origin time which even may vary between different instances of Java VMs. Only use nanoTime() for profiling.

Java for C# Programmers 4: Exceptions & Arrays

Exceptions

Java has exceptions with try/catch/finally. They work roughly the same way as in C#.

  • Gotcha: In C#, the stack trace is put into the exception when the exception is thrown. In Java, the stack trace is calculated, when the exception is created. Re-read the previous sentence, please.
  • Rethrowing an exception in Java works like this:
    catch (Exception e) { throw e; }
    This works in Java only because throwing an exception does not recalculate its stack.
  • The ex.getMessage() may be null, even with standard system exceptions. This is never the case in C#. At least I’ve never seen it there.
  • On the other hand, you can call System.out.println(ex.getMessage()); without problems in Java. It writes null to the screen. In C#, this will throw, if ex.getMessage() is null.
  • Gotcha: In Java return is allowed in a finally block, which is not in C#. This may lead to unexpected behaviour.
  • You can catch multiple types of exceptions in one clause.
    catch ( IOException | SQLException ex ) { ... }

Checked Exceptions

In Java, there are two types of exceptions. Checked and unchecked exceptions. Unchecked exceptions are those which derive from RuntimeException, checked exceptions extend Exception. In C#, there are only unchecked exceptions.

Checked exceptions are an interesting feature.

If a method X can throw one or several checked exceptions, it must announce this in its declaration with the throws keyword like this:
void ReadMyFile(String filename) throws IOException

What follows: if a method M calls a method X which may throw a checked exception Ex,

  • M itself must catch Ex or
  • M itself declares that it may throw Ex via throws Ex

This is enforced by the compiler.
At first glance, it seems that checked exceptions make things easier for library developers and library users… But at second glance, it seems checked exceptions are deprecated in the Java community. Probably the main point of this interesting post about checked exceptions is:

When you choose to use checked exception for errors that you think are recoverable, you try to decide for the client of your API, whereas only he may know what’s recoverable and what isn’t in his own context.

Hejlsberg, the main developer of C#, doesn’t like checked exceptions too much also. In an interview about checked exceptions he stated:

The exception handling should be centralized, and you should just protect yourself as the exceptions propagate out to the handler.

Arrays

There are constant length arrays in Java, which are very similar to those in C#. Access is by index starting at zero.

Gotcha: In Java, the array is not connected in any way to the Iterable interface or the collection types. You cannot pass an array where an Iterable is required.

Exception: you can use an array in a for loop.

int[] h4 = {4, 5, 11, 46};
for(int i: h4)
    System.out.printf(" %d", i);  // 4 5 11 46

Creating an Array

Some examples of how to create an array in Java are:

Abc[] a = new Abc[6]; 
  // All members of a are initialized to null, as 
  // Abc is a reference type.

int b[] = new int[4]; 
for(int i = 0; i < a.length; ++i)
    System.out.print(a[i] + " ");   // 0 0 0 0 

b[6] = 67;   // ArrayIndexOutOfBoundsException: 6   

int[] c = new int[] {4, 5, 11};
int[] d = {4, 5, 11, 46};

String[] e = {"a", "b"};

int[] g = new int[5];

Copying an Array or a Part

There are at least three different system methods to copy an array. I am not really sure what are the differences. Probably there are none or none worth to mention.

int[] d = {4, 5, 11, 46};
int[] g = new int[5];
int[] f = d.clone();    // copies d completely

// Copies 3 elements starting at f[0] to g, 
// starting at g[1].
System.arraycopy(f, 0, g, 1, 3);
System.out.println(Arrays.toString(g)); // [0, 4, 5, 11, 0]

int[] h = Arrays.copyOf(d, 3);
System.out.println(h);                  // [I@1b778d0c      
System.out.println(Arrays.toString(h)); // [4, 5, 6]

Class Arrays

The static system class Arrays contains some functions - even some parallel ones - that are helpful when dealing with arrays. The functions are overloaded for all the primitive types and for Object.

Function Purpose
asList creates a List from an array
binarySearch searches an item
copyOf copies, truncating or padding
copyOfRange copies a part
deepEquals checks if 2 arrays are deeply equal
deepToString returns a deep string representation
fill fills an array or a part of an array
parallelPrefix cumulates in parallel all elements
parallelSetAll fills in parallel with generated values
parallelSort sorts an array using a parallel algorithm
setAll fills with generated values
sort sorts completely or sort a range
stream creates a Stream from array
spliterator creates a Spliterator from array

Multi-Dimensional Arrays

An array of arrays (jagged array) is possible and the only type in Java. Real multi-dimensional arrays like in C, C++ and C# do not exist in Java.

int[][] h21 = new int[2][4]; 
int[][][] h3 = new int[2][5][4];

System.out.println(h3.length);          // 2 
System.out.println(h3[0].length);       // 5 
System.out.println(h3[0][0].length);    // 4 

You should always remember that jagged arrays are just arrays of arrays (of arrays, ...) and the length of the second (third, ...) level arrays may be different for every entry.

int[][] h22 = { {11, 12, 13, 14}, {5} };

System.out.println(h22[0].length);      // 4 
System.out.println(h22[1].length);      // 1 

System.out.println(h22[0][3]); // 14 
System.out.println(h22[1][3]); // throws ArrayIndexOutOfBoundsException

It seems the best way to find out the number of dimensions of a multi-dimensional array is to go via the class name.

int[][][][] a = {{{{1},{71}}}};

String className = a.getClass().getName();
System.out.println(className);              // [[[[I
int numberOfDimensions = className.lastIndexOf('[') + 1;
System.out.println(numberOfDimensions);     // 4

Java for C# Programmers 3: Operators & Flow Control

Operators

Mathematical Operators

Increment and decrement operators ++, -- work as in C#, including pre- and postfix notation.

The mathematical operators +, -, , /, %, +=, -=, =, /=, %= and the bitwise operators ~, &, |, ^, <<, >>, &=, |=, ^=, <<=, >>= work as expected.

In Java, there are two additional bitwise operators: >>> and >>>=.
>>> moves the bits to the right and fills all up with zeroes. In contrast, the >> operator fills all up with the sign bit.

// Java
int a = -128;
System.out.println(a >> 1);     // -64
System.out.println(a >>> 1);    // 2147483584

System.out.println(a >> 4);     // -8
System.out.println(a >>> 4);    // 268435448

a = -1;
System.out.println(a >> 1);     // -1
System.out.println(a >>> 1);    // 2147483647

a = 4;
System.out.println(a >> 1);     // 2
System.out.println(a >>> 1);    // 2

The effect of >>> is reachable in C# by using unsigned integers. Or put differently: The >>> is needed in Java because it doesn’t have unsigned integers.

// C#
int a = -128;
uint b = unchecked((uint) -128);
Console.WriteLine(a >> 1);  // -64
Console.WriteLine(b >> 1);  // 2147483584

Console.WriteLine(a >> 4);  // -8
Console.WriteLine(b >> 4);  // 268435448

a = -1;
b = unchecked((uint) -1);
Console.WriteLine(a >> 1);  // -1
Console.WriteLine(b >> 1);  // 2147483647

a = 4;
b = 4;
Console.WriteLine(a >> 1);  // 2
Console.WriteLine(b >> 1);  // 2

Logical Operators

The comparison operators >, >=, ==, <, <=, != are all the same.

Gotcha: In Java, string comparison with == does not compare the contents of the string. In C# it does.

String a = "abc";
String b = "ab";
b += "c";
if (a == b)     // false in Java, true in C#

The logical operators &&, ||, ^, ! work as expected.
In Java like in C# there are also available the boolean operators & and | which do not do short-circuit evaluation.

System.out.println(true | f());  // f will be calculated.  

Flow Control

If, Else And Switch

If, else, switch/case, ?:-operator are the same in Java as in C#, with these differences:

  • switch/case allows fallthrough in Java generally. In C#, fallthrough is allowed only when the label where fallthrough happens does not contain any code.
  • You can't switch on long variables in Java.
  • switch/case allows strings in C#, in Java strings in switch/case are allowed only from Java 7 on.

Gotcha: Java treats the null-String in a switch/case in two completely different ways from C#.

string s = null;
switch(s)
{
    case null: Console.WriteLine("null"); break; 
    default: Console.WriteLine("default"); break;
}

The C# code above will print null. Without the case null part, it will print default.

In Java, the corresponding code including the case null statement will result in a case expressions must be constant expressions compiler error.

Without the case null statement, the code will compile. But at runtime, you'll get a NullPointerException at the switch(s).

Loops And Goto

for, while, do while are all the same. Goto is not available in Java.

The foreach keyword does not exist in Java. Iterating over all of a collection is implemented with a special syntax in for.

// C#
foreach(Type k in array)
// Java
for(Type k: array) 

Java has break and continue with label, these features do not exist in C#.

Break With Label

OuterLoop: // Labels the following loop with 'OuterLoop'
for(int i = 0; i < 3; ++i)
{ 
    for(int j = 0; j < 5; ++j)
    {
        System.out.println("i: " + i + "   j: " + j);
        if(j == 1) 
            break OuterLoop;  // Breaks out of the scope with the 
                       // label OuterLoop. Or put differently: 
                       // jumps behind the end of the statement 
                       // labeled OuterLoop. 
    }
}

The output of the code above is

i: 0  j: 0

Continue With Label

AAA: // Labels the following loop with 'AAA'
for (int i = 0; i < 3; ++i) 
{
    for (int j = 0; j < 5; ++j)
    {
        System.out.println("i: " + i + "   j: " + j);
        if (j == 0)
            continue AAA; // Breaks all inner loops and 
                          // continues the loop labeled AAA.
    }
}

The output of the code above is

i: 0   j: 0
i: 1   j: 0
i: 2   j: 0