Pages

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

Tuesday, 10 May 2016

NPE while assign the Null value to primitive at runtime

public class TestOutput {

     public static void main(String[] args) {
           int value = solution();
           System.out.println(value);
     }

     private static int solution() {
           return true?0:null;
     }
}

Output: 0

When we assign the null value to primitive at runtime, it will throw NullPointerException.


public classTestOutput {

     public static voidmain(String[] args) {
           int value = solution();
           System.out.println(value);
     }

     private static intsolution() {
           return true?null:0;
     }
}
Output:
Exception in thread "main" java.lang.NullPointerException at TestOutput.solution(TestOutput.java:10) at TestOutput.main(TestOutput.java:5)

Monday, 2 May 2016

How do I get MAC address of a host?

In JDK 1.6 a new method is added in the java.net.NetworkInterface class, this method is getHardwareAddress().


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class PrintMacAdress {
   public static void main(String[] args){
      try {
          InetAddress address = InetAddress.getLocalHost();
          //InetAddress address = InetAddress.getByName("www.google.co.in");
                 
          System.out.println("Current IP address : "+address.getHostAddress());
          NetworkInterface network = NetworkInterface.getByInetAddress(address);

          byte[] mac = network.getHardwareAddress();

          System.out.print("Current MAC address : ");

          StringBuilder sb = new StringBuilder();
          for (int i = 0; i < mac.length; i++) {
              sb.append(String.format("%02X%s",mac[i],(i<mac.length-1)?"-":""));
          }
          System.out.println(sb.toString());
    } catch(UnknownHostException e) {
    } catch(SocketException e){
    }
  }
}

Output:
      Current IP address : 192.168.230.215
      Current MAC address : D8-CB-8A-67-8B-3F