Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, 9 February 2018

Book Review: The Well-Grounded Java Developer, by Benjamin J Evans and Martin Verburg

Although Java 9 is now out and this book was written way back when Java 7 was new I still found this to be a very useful and educational read. The book explains the fundamentals of the Java platform (e.g. bytecode, garbage collection) and programming principles in general (e.g. concurrency, dependency injection, functional programming) in a way that I've not seen in any other book. The introduction and contrast of the Groovy, Scala and Clojure JVM languages I also thought was done well. Some aspects of the book are now dated but it's still worthwhile skimming over for a historical context of how the platform has developed. If you're new to programming and new to Java development however this probably isn't the right book to start with.

Saturday, 29 April 2017

IntelliJ: Live Template for generating an empty JUnit test method

Here's an IntelliJ / Android Studio Live Template for generating an empty JUnit test method:

@org.junit.Test
public void $testMethodName$() {
    // Given.
    
    // When.
    
    // Then.
}

Set the "Applicability" of the Live Template to be "Java declarations" and set the "Expression" associated to the $testMethodName$ variable to be methodName().

Set the "Abbreviation" and "Description" for the Live Template as you wish and that's it... you're good to go!

Saturday, 10 December 2016

IntelliJ: Live Template for generating a single parameter constructor

Here's an IntelliJ / Android Studio Live Template for generating a constructor that takes in a single parameter and sets that parameter into a class field:

@android.support.annotation.NonNull
private final $dependencyClass$ $dependency$;

private $constructorClass$(@NonNull $dependencyClass$ $dependency$){
    this.$dependency$ = $dependency$;
}

Set the "Applicability" of the Live Template to be "Java declarations" and set the "Expression" associated to each of the variables as follows:
  • $dependencyClass$ -> completeSmart()
  • $dependency$ -> suggestVariableName()
  • $constructorClass$ -> className()
Tick the "Skip if defined" option for the $constructorClass$ variable and set the "Abbreviation" and "Description" for the Live Template as you wish and that's it... you're good to go!

Thursday, 8 December 2016

IntelliJ: Live Template for generating static nested Factory class

If you find yourself having to create a static nested Factory class time and time again then you'll find the following IntelliJ / Android Studio Live Template handy:

public static class Factory {

    @android.support.annotation.NonNull
    private final $dependencyClass$ $dependency$;

    Factory(@NonNull $dependencyClass$ $dependency$){
        this.$dependency$ = $dependency$;
    }

    @NonNull
    public $createdClass$ create(){
        return new $createdClass$($dependency$);
    }
}

Set the "Applicability" of the Live Template to be "Java declarations" and set the "Expression" associated to each of the variables as follows:
  • $dependencyClass$ -> completeSmart()
  • $dependency$ -> suggestVariableName()
  • $createdClass$ -> className()
Tick the "Skip if defined" option for the $createdClass$ variable and set the "Abbreviation" and "Description" for the Live Template as you wish and that's it... you're good to go!

Saturday, 5 April 2014

Java - convert an integer to a binary (bits/bytes) String

So! You want to convert an integer to its binary (bits and bytes) representation. There is an existing method which does this:

Integer.toBinaryString(int);

But! This will not include the leading 0s (i.e. the 0s before the most-significant 1). If you want a String with all 32 bits that make up the integer, here's an alternative method:

/**
 * @param value
 * @return the binary representation of {@code value}, including leading 0s.
 */
String toBinaryString(int value) {
  final byte[] bytes = ByteBuffer
      .allocate(4)
      .order(ByteOrder.BIG_ENDIAN)
      .putInt(value)
      .array();

  return toBinaryString(bytes);
}

/**
 * @param bytes is non-null.
 * @return the binary representation of the bytes in {@code bytes}.
 */
String toBinaryString(byte[] bytes) {
  final StringBuilder sb = new StringBuilder();

  for (int i = 0; i < bytes.length; i++) {
    sb.append(toBinaryString(bytes[i]));
    sb.append(" ");
  }

  return sb.toString();
}

/**
 * @param value
 * @return the binary representation of {@code value}.
 */
String toBinaryString(byte value) {
  final StringBuilder sb = new StringBuilder();

  for (int i = 7; i >= 0; i--) {
    boolean bitSet = (value & (1 << i)) > 0;
    sb.append(bitSet ? "1" : "0");
  }

  return sb.toString();
}

Monday, 10 March 2014

Android/Java - formatting a String containing both English and Arabic

I ran across a problem today where I needed to compose a String containing both English (left-to-right text) and Arabic (right-to-left text) parts. In particular, what I needed to do was format a String containing three blocks to display as follows:

[1. English left-to-right text] [2. Arabic right-to-left text] [3. English left-to-right text]

The problem I found was that some of the English in the third block was displayed to the left of the Arabic in the second block, i.e. the implicit text ordering algorithm wasn't able to correctly determine where the Arabic right-to-left block had completed and the next English left-to-right block had started.

To get around this problem I had to explicitly specify directional formatting characters (\u202A, \u202B, \u202C, \u202D, \u202E etc) something as follows:

[1. English left-to-right text] \u202B [2. Arabic right-to-left text] \u202C [3. English left-to-right text]

To get the text to render exactly as you intend you might need to play around a little with the directional formatting characters. For example, you might have to surround the English block with directional formatting characters as well as the Arabic text, as follows:

\u202D [1. English left-to-right text] \u202B [2. Arabic right-to-left text] \u202C [3. English left-to-right text] \u202C

Here's the Stack Overflow thread which led me to the solution:
http://stackoverflow.com/questions/6177294/string-concatenation-containing-arabic-and-western-characters

For a deeper understanding of directional formatting characters and the Unicode Bidirectional Algorithm, check out the following document:
https://unicode.org/reports/tr9

Saturday, 23 November 2013

Java/Android - Method for getting a url's domain name

Below is a method which extracts a url's domain name and which uses simple String matching. What it actually does is extract the bit between the first "://" (or index 0 if there's no "://" contained) and the first subsequent "/" (or index String.length() if there's no subsequent "/"). The remaining, preceding "www(_)*." bit is chopped off. I'm sure there'll be cases where this won't be good enough but it should be good enough in most cases!

I read on forums that the java.net.URI class could do this (and was preferred to the java.net.URL class) but I encountered problems with the URI class. Notably, URI.getHost() gives a null value if the url does not include the scheme, i.e. the "http(s)" bit.


/**
* Extracts the domain name from {@code url}
* by means of String manipulation
* rather than using the {@link URI} or {@link URL} class.
*
* @param url is non-null.
* @return the domain name within {@code url}.
*/
public String getUrlDomainName(String url) {
  String domainName = new String(url);

  int index = domainName.indexOf("://");

  if (index != -1) {
    // keep everything after the "://"
    domainName = domainName.substring(index + 3);
  }

  index = domainName.indexOf('/');

  if (index != -1) {
    // keep everything before the '/'
    domainName = domainName.substring(0, index);
  }

  // check for and remove a preceding 'www'
  // followed by any sequence of characters (non-greedy)
  // followed by a '.'
  // from the beginning of the string
  domainName = domainName.replaceFirst("^www.*?\\.", "");

  return domainName;
}

Monday, 25 October 2010

Java (High Level Concurrency) tutorial

Just worked through the last part of the online Java Concurrency tutorial. Understood the java.util.concurrent.locks package (i.e. Lock, Reentrant etc classes including trylock(), unlock() etc methods) and java.util.concurrent.atomic package (i.e. AtomicInteger etc classes including incrementAndGet(), decrementAndGet() etc methods). Didn't quite get the stuff about Executors and Thread Pools! Also, couldn't do the Questions at the end of the tutorial so there's a clear sign I need more practice!!

Saturday, 23 October 2010

Java Concurrency (Synchronization, Liveness, Guarded Blocks) tutorial

Just continued with the second third of the online Java Concurrency tutorial playing in particular with the 'synchronized' keyword and the wait()/notify() methods of the Object class.

Friday, 22 October 2010

Java Concurrency (Processes and Threads) tutorial

Just worked through the first two parts of the online Java Concurrency Tutorial ('Processes and Threads', 'Thread Objects'). Learnt about the Thread class versus the Runnable interface (including the run()/start() methods) as well as the sleep(), interrupt(), join() methods and the InterruptedException class.