Features of revolutionary release -Java 8 for Android

Foram Shah
AndroidPub
Published in
6 min readApr 4, 2017

--

Java8 for android

Java 8 is a mountainous step for the Java language. The ratification of Java 8 is a big deal for Android on the whole and will no doubt make it easier for developers to create new applications and clean up existing code.

In short, java 8 is

“Fabricating cleaner code & streamlining the whole process”

To be specific, the change from Java 7 to 8 brings a whole lot more to the board where Java developers are perturbed, and marks a big update to the foundation that Android and many of its applications are built upon.

Lollipop 5.0 was one of the initial versions of Android that launched requiring applications built using Java 7, and now Android N is modernising things to Java 8.

Now let’s have a look over java 8 features that are supported in android.

1 . Default and static interface method

Before java 8 we could have only method declaration in interface, but after java 8 came in picture, we can define methods by using Default and Static keywords.

Although these new restructuring will only work on Android N devices.

Prior to java 8 interface is tough to revamp, if we need some additional method in interface then it will require changes in all implementing classes.

After inclusion of java 8 we can easily revamp interface and also add methods with definition with default and static keyword.

Default Methods

Java interface default methods will help us extending interfaces without having the fear of breaking implementation classes.

In order to create a default method in interface, we need to use “default” keyword with the method signature.

Here’s an example which shows default method in interface.

public interface MyInterface {    void interfaceMethod();default void defaultMethod(){
Log.v(TAG,"Default Method");
}
}

public class MyClass extends AppCompatActivity implements MyInterface {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
interfaceMethod("Hello World")
Log.v(TAG+ defaultMethod());
}
@Override
public void interfaceMethod(String str) {
Log.v(TAG + str);
}
}

The class which implement this interface is free from implementing this default method.

This will help in extending interface with add-on methods, all we need to provide is a default implementation.

Static Methods

Static methods are same as default methods, the only difference is you can not override them in implementation classes.

Static method provides security by not allowing implementation classes to override them.

Check this static method in interface.

public interface MyInterface {
default void defaultMethod(){
System.out.println("Default");
}

static void staticMethod(){
System.out.println("Static");
}
}

public class MyClass extends AppCompatActivity implements MyInterface {

public static void main(String[] args) {
MyInterface.staticMethod(); //valid
}
}

2. Lambda Expression

One of the powerful introduction in java 8 is Lambda Expression, it allows to keep syntax more clear and less inflated.

previously it was not available without extra tool, but now after this revolutionary release Lambda Expression will work on previous versions of android back to 2.3(Gingerbread) .

In a nutshell, lambda expression is a substitute of anonymous inner class when providing event listeners.

For instance, consider the standard basic click listener :

btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Log.v(TAG, "Button clicked");
Toast.makeText(MyActivity.this, "Main Activity", Toast.LENGTH_LONG).show();
}
});

With Lambda expression :

btnSave.setOnClickListener(v -> { 
Log.v(TAG, "Button clicked");
Toast.makeText(MyActivity.this, "Main Activity", Toast.LENGTH_LONG).show();
});

3. Enhancing Null Safety

Being developer how can we forgot “The NullPointerExceptions”, and that’s what some java pundits thought about and introduced Optional.

Optional is a container object that may or may not contain a non-null value. Optional object is used to represent null with absent value.

To interact with the value, Optional offers a set of useful methods that abstract away the null checks.

This leaves us with more concise and declarative code that is focused on the details we care about.

Student student= new Student();
String firstName= null;
String lastName= new String();

//Optional.ofNullable - allows passed parameter to be null.
Optional<String> strFirstName= Optional.ofNullable(firstName);

//Optional.of - throws NullPointerException if passed parameter is null
Optional<String> strLastName= Optional.of(value2);
Log.v(TAG,Student.display(strFirstName,strLastName));

4. Repeating Annotations

Had java 8 not been introduced, its not that easy to declare more than one annotation of the same type to the same location. And to do that we will have to group them in a container annotation.

The repeating annotation is introduced in java 8 which means same annotations can be repeated as much time you want at same locations.

Unfortunately, you can not use repeating annotation below SDK 24.

// Declaring repeatable annotation type
@Repeatable(Student.class)
@interfaceStudent
{
String name();
String marks();
}
// Declaring container for repeatable annotation type@Retention(RetentionPolicy.RUNTIME)
@interfaceStudent
{
Student[] value();
}
// Repeating annotation
@Student(name = “ABC”, marks= “50”)
@Student(name = “XYZ”, marks = “30”)
public class RepeatingAnnotationsDemo extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

5. Stream Api

Stream is a new abstract layer introduced in Java 8. Stream allows us to process data in declarative manner or say in a more managing way.

Using stream, developer don’t have to worry about concurrency and thread management as it process huge data very efficiently.

Here is the example of stream api which display words those starting with letter ‘a’.

List<String> strList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("a"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

Not so happy thing to hear is, Stream api is also not available below SDK 24.

Prerequisite to use JAVA 8 in android studio

  1. JDK 8 (When developing apps for Android, using Java 8 language features is optional. You can keep your project’s source and target compatibility values set to Java 7, but you still need to compile using JDK 8.)
  2. Compiler JACK
  3. Android studio 2.1 and higher (Because Jack is supported only on Android Studio 2.1 and higher. So if you want to use Java 8 language features, you need to use Android Studio 2.1 and higher to build your app.)

See how one can use java 8 in android studio

In order to use the new Java 8 language features, you need to also use the Jack toolchain. As per this announcement jack toolchain is deprecated but still one can continue using Jack to build their Java 8 code until some new release happen. Migrating from Jack should require little or no work.

Another option is developer can try latest preview version of Android Studio to use improved support for java 8 language features built into the default toolchain.

Configure Gradle

To enable Java 8 language features and Jack for your project, enter the following in your application level build.gradle file:

android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

These were certain points from java 8 that makes it even more robust language than it ever was.

This was a little efforts from me to illuminate the strong points that java 8 comes up with android.

Hope this will help you to kick start your learning and R&D about java 8.!!

--

--

Foram Shah
AndroidPub

Android developer @IndiaNIC| Always be the hardest worker in the room.