When I re-pick-up Java, after having dealt with really different programming languages in the months before, I encounter these moments of “damn-you-know-this”. So when I came back to java this time, I recorded my top five missing Java pieces:
- Conversion from String to Integer
String example=“1”; int value = Integer.parseInt( example );
It is NOT:
Integer.getInteger( example );
The getInteger method trys to
Determines the integer value of the system property with the specified name.
- The ? – Operator The Java ternary operator (sometimes referred to as the “questionmark operator”) is an elegeant way to deal with boolean (TRUE / FALSE) decisions or assignments in the programming world. The ternary operator differs from an if-else statement due to the fact that it is an expression that returns a value. While the if-else structure executes a statement. The following Example assigns the maximum Value of two ints to a new variable:
int a = 5; int b = 10; int max = (a > b ? a : b);
- instanceof and isInstance The binary operator instanceof checks if an object is a member of a class:
SampleObject sample = new SampleObject(); if(sample instanceof SampleObject) { ... }Unfortunately though it is not possible to set the type (which the object is tested against) at runtime and use for example a string at the leftside of the instanceof operator:
SampleObject sample = new SampleObject(); String sampleStr = "sampleObject";
if(sample instanceof sampleStr) {... }
At runtime it is possible though to check the type of an object with the isInstance method:
// the object where we know what kind of type it is SampleObject sampleold = new SampleObject(); // our "unknown" type object Object samplenew = new SampleObject(); if(sampleold.getClass().isInstance(samplenew)) { ... }Attention to the switch of the arguments between instanceof and isInstance !
- Comparator
If I write a Comparator Object I usually implement Comparator<T> and then override int compare(T t1, T t2). To implement a proper working compare method the following “handrules” apply:- (t1 < t2) -> return a negative value
- (t1 == t2) -> return zero
- (t1 > t2) -> return a positive value
The <, ==, > do NOT have to refer to the standard smaller, greater, etc operators !