Search This Blog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, 19 June 2017

Other Modifiers for Members in Java

Other Modifiers for Members in Java

Certain characteristics of fields and/or methods can be specified in their declarations by the following keywords:

static Members: The declaration of static members is prefixed by the keyword static to distinguish them from instance members.
Static variables (also called class variables) only exist in the class they are defined in. They are not instantiated when an instance of the class is created. In other words, the values of these variables are not a part of the state of any object.
Static methods are also known as class methods. A static method in a class can directly access other static members in the class. It cannot access instance (i.e., non-static) members of the class, as there is no notion of an object associated with a static method.

final Members: A final variable is a constant, despite being called a variable. Its value cannot be changed once it has been initialized. This applies to instance, static and local variables, including parameters that are declared final.
A final variable of a primitive data type cannot change its value once it has been initialized.
A final variable of a reference type cannot change its reference value once it has been initialized, but the state of the object it denotes can still be changed.
A final method in a class is complete (i.e., has an implementation) and cannot be overridden in any subclass. Subclasses are then restricted in changing the behavior of the method.

abstract Methods: An abstract method does not have an implementation; that is, no method body is defined for an abstract method, only the method prototype is provided in the class definition. Its class is then abstract (i.e., incomplete) and must be explicitly declared as such. Subclasses of an abstract class must then provide the method implementation; otherwise, they are also abstract.

synchronized Methods: Several threads can be executing in a program. They might try to execute several methods on the same object simultaneously. If it is desired that only one thread at a time can execute a method in the object, the methods can be declared synchronized. Their execution is then mutually exclusive among all threads. At any given time, at the most one thread can be executing a synchronized method on an object. This discussion also applies to static synchronized methods of a class.

native Methods:Native methods are also called foreign methods. Their implementation is not defined in Java but in another programming language, for example, C or C++. Such a method can be declared as a member in a Java class definition. Since its implementation appears elsewhere, only the method prototype is specified in the class definition. The method prototype is prefixed with the keyword native. 

transient Fields: Objects can be stored using serialization. Serialization transforms objects into an output format that is conducive for storing objects. Objects can later be retrieved in the same state as when they were serialized, meaning that all fields included in the serialization will have the same values as at the time of serialization. Such objects are said to be persistent.
A field can be specified as transient in the class declaration, indicating that its value should not be saved when objects of the class are written to persistent storage.

volatile Fields: During execution, compiled code might cache the values of fields for efficiency reasons. Since multiple threads can access the same field, it is vital that caching is not allowed to cause inconsistencies when reading and writing the value in the field. The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads.

Sunday, 26 February 2017

Exceptions in Java

Exceptions in Java

 An exception in Java is an event, which occurs during the execution of a program that disrupts the normal flow of the program.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, contains information about the error, including exception type and the state of the program when the error occurred and is called an exception object. Creating an exception object and handing it to the runtime system is called throwing an exception.
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
  • A user has entered an invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.


The Three Kinds of Exceptions
  • Checked exceptions − Checked exception is an exception that occurs at the compile time, and are also called as compile time exceptions. As these exceptions occur at the time of compilation of code, the programmer should take care to handle these exceptions.
  • Unchecked exceptions − Unchecked exception is an exception that occurs at the time of execution. As they occur at time of execution they are also called as Runtime Exceptions. These type of exception include programming bugs, such as logic errors or improper use of an API.
  • Errors − Errors are not exceptions, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in the code because you can rarely do anything about an error. For example, out of memory error.


Catching and Handling Exceptions
The exception mechanism in Java uses three exception handler components — the trycatch, and finally blocks.

The try Block
The try block is used to enclose the code which might throw an exception.
try {
    code
}
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it.

The Catch Block
We associate exception handlers with a try block by providing one or more catch blocks directly after the try block.
try {
//some code that throws Exception
} catch (ExceptionType name) {
// code that is invoked once the exception is thrown
} catch (ExceptionType name) {
// code that is invoked once the exception is thrown
}
Each catch block is an exception handler that handles the type of exception indicated by its argument.
The catch block contains code that is executed if and when the exception handler is invoked.

The finally Block
The finally block always executes when the try block exits.
This ensures that the finally block is executed even if an unexpected exception occurs.
finally is useful for more than just exception handling — it allows the programmer to write the clean-up code , even if there are no exceptions.
 finally{
 // code for clean up
 }

Advantages of Exceptions

  • Separating Error-Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping and Differentiating Error Types
Exceptions in Java

Exceptions in Java




Monday, 6 February 2017

Default Methods in Java 8

Default Methods in Java 8
With the release of Java 8, it is now possible for an interface method to define a default implementation. This new capability is called the default method.

Default method enables us a means by which interfaces could be expanded without breaking pre-existing code.
In simple terms default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.


When a non-abstract class implements an interface, it must implement all methods defined by that interface. If a new method is to an existing interface, then the addition of that method would break pre-existing code, because no implementation would be found for that new method in pre-existing classes. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause pre-existing code to break. This enables interfaces to be gracefully evolved over time without negative consequences.

Example of Default Method


public interface Account {
default void OpenAccount(){
      System.out.println("This is the Account Interface . . . .");
}
}



public class SavingAccount implements Account{
public void OpenSavingAccount(){
      System.out.println("This is the Saving Account Class . . . .");
}
}


public class Main {
public static void main(String[] args) {
      SavingAccount sa=new SavingAccount();
      sa.OpenAccount(); // Default method of interface is called
      sa.OpenSavingAccount();
}
}


Upon executing the Main class, we get the following output.
This is the Account Interface . . . .
This is the Saving Account Class . . . .

Default Methods and Multiple Inheritance
In case of multiple Inheritance, where both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.
interface InterfaceOne
{
      // Default method
      default void show()
      {
            System.out.println("Default InterfaceOne");
      }
}

interface InterfaceTwo
{
      // Default method
      default void show()
      {
            System.out.println("Default InterfaceTwo");
      }
}

public class MainClass implements InterfaceOne, InterfaceTwo
{
      // Overriding default show method
      public void show()
      {
            // use super keyword to call the show
            // method of InterfaceOne interface
            InterfaceOne.super.show();

            // use super keyword to call the show
            // method of InterfaceTwo interface
            InterfaceTwo.super.show();
      }

      public static void main(String args[])
      {
            MainClass d = new MainClass();
            d.show();
      }
}

Upon executing the MainClass, we get the following output.
Default InterfaceOne
Default InterfaceTwo


Important Points:
1.     Interfaces can have default methods with implementation from java 8 onwards.
2.     Interfaces can have static methods as well similar to static method of classes.
3.     Default methods were introduced to provide backward comparability for old interfaces so that they can have new methods without effecting existing code.


Friday, 3 February 2017

Lambda expressions in Java 8

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection.
A lambda expression can be understood as a concise representation of an anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown.
o    AnonymousAnonymous because it doesn’t have an explicit name like a method would normally have: less to write and think about!
o    FunctionFunction because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.
o    Passed aroundA lambda expression can be passed as argument to a method or stored in a variable.
o    ConciseYou don’t need to write a lot of boilerplate like you do for anonymous classes.

Lambdas technically let you do anything that you could do prior to Java 8. But you no longer have to write clumsy code using anonymous classes.
 The result is that your code will be clearer and more flexible. For example, using a lambda expression you can create a custom Comparator object in a more concise way.

Before:
Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
};


After (with lambda expressions):
Comparator<Apple> byWeight =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

Lambda Expression Syntax
Lambda expressions address the bulkiness of anonymous inner. A lambda expression is composed of three parts.
A lambda expression is composed of parameters, an arrow,
and a body.

Argument List
Arrow Token
Body
(int x, int y)
->
x + y
The body can be either a single expression or a statement block. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.
Take a look at these examples:
(int x, int y) -> x + y

() -> 42

(String s) -> { System.out.println(s); }
 
The first expression takes two integer arguments, named x and y, and uses the expression form to return x+y.
The second expression takes no arguments and uses the expression form to return an integer 42.
The third expression takes a string and uses the block form to print the string to the console, and returns nothing.
Lambda Examples
Runnable Lambda
public class RunnableTest {
  public static void main(String[] args) {
    System.out.println("=== RunnableTest ===");
       // Anonymous Runnable
    Runnable r1 = new Runnable(){
         @Override
      public void run(){
        System.out.println("Hello world one!");
      }
    };
   
    // Lambda Runnable
    Runnable r2 = () -> System.out.println("Hello world two!");
   
    // Run them
    r1.run();
    r2.run();
   
  }
}
Comparator Lambda
In Java, the Comparator class is used for sorting collections. In the following example, an ArrayList consisting of Person objects is sorted based on surName. The following are the fields included in the Person class.
public class Person {
private String givenName;
private String surName;
private int age;
private String eMail;
private String phone;
private String address;
}

The following code applies a Comparator by using an anonymous inner class and a couple lambda expressions.

public class ComparatorTest {
 public static void main(String[] args) {
  
    // Create List of Person
        List<Person> personList1 = null;
   
      // Sort with Inner Class
    Collections.sort(personList1, new Comparator<Person>(){
      public int compare(Person p1, Person p2){
        return p1.getSurName().compareTo(p2.getSurName());
      }
    });
   
    System.out.println("=== Sorted Asc SurName ===");
    for(Person p:personList1){
      System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
    // Use Lambda instead
   
    // Print Asc
    System.out.println("=== Sorted Asc SurName ===");
    Collections.sort(personList1, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()));

    for(Person p:personList1){
System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
    // Print Desc
    System.out.println("=== Sorted Desc SurName ===");
    Collections.sort(personList1, (p1p2) -> p2.getSurName().compareTo(p1.getSurName()));

    for(Person p:personList1){
System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
  }
}