Program Check even or odd without using modulus and division operators

write a progrma to check number is even or odd without using modulus or divition

  • Checking the number even or odd program is very easy. Anybody can solve this but there is a condition we need to see.
  • When we get this question in interview "write a program to check given number is even or odd" always continues with "without using modulus and division operators".
  • Before going to actual program lets see how to check a number is even or odd by using modulus and division operators.

 

 

Program to check number is even or odd by using modulus "%" operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if((number % 2)==0){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }

Output:

  1. Enter a number to check even or odd
  2. 37
  3. 37 is Odd Number


Program to check number is even or odd by using division "/" operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if((number / 2)*2==number){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }

Output:

  1. Enter a number to check even or odd
  2. 46
  3. 46 is Even Number


Without using modulus and division operators:

  • The above two programs will check number is even or odd and displays result. 
  • Now we need to write a program to check even or odd without using modulus and division operators.
  • It is very simple if you know about operators including "BIT WISE".
  • Yes using Bit Wise AND "&" operator we can check a number is even or odd.
  • Before starting our program lets see how this bit wise AND "&" operator will work.

Bitwise Operators :

  • Bit wise operators will work on bits at a time.
  • AND : 1 & 1=1
  • OR :     0 | 1= 1 , 1 | 0=1 , 1| 1= 1
  • XOR:   0 ^ 1= 1 , 1^ 0=1
  • NOT : !0=1
  • Take two number 2 and 3
  • 010 : 2
    011 : 3
    ------
    010 : 2
  • ------
  • Take two numbers 2 and 1
  • 010  :2
    001  :1
    -----
    000  :0
    -----
  • From above example we can say that on every even number & 1 gives 0.
  • So this is our logic to be implemented in our program  if "Number & 1==0" then its even number.

Program to check number is even or odd by using  "&" operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if((number & 1)==0){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }


Output:

  1. Enter a number to check even or odd
  2. 9
  3. 9 is Odd Number


Using Shift Operators:

  • We can check even or odd by using shift operators also may be it is not a better solution but  trying to cover alternative.
  • Lets see how shift operators will work
  • Lets do this 2 >> 1
  • 2 means 010 so now we need to shift right side by 1 place
  • 010
    -----
    001
  • Here we added one "0" to the left side to shift right 
  • So the value became 1
  • Now will try left shift  001 >> 1
    001
    ----
    010
  • 010<<1=001(1) and 001 >> 001=010(2)
  • By this we can say if a (number >>1)<<1 gives same then that is even number. result=input
  • Lets check for odd number 3
  • 011>>1=001 which is 1 and 001<<1=010 which is 2 so (3>>1)>>1=2 so result!=input

Program to check number is even or odd by using Shift operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if( ( number >> 1) <<1==number){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }

Output:

  1. Enter a number to check even or odd
  2. 64
  3. 64 is Even Number
Here is the another solution for this.

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. class EvenOrOddDemo
  5. {
  6.  
  7. public static void main(String[] args)
  8. {
  9.  
  10. Scanner sc=new Scanner(System.in);
  11.  
  12. System.out.println("Enter a number to check whether it is even or odd without using Modulus
  13. and Division: ");
  14.  
  15. int n=Integer.parseInt(sc.next());
  16. float f=(float)n/(float)2;
  17. int d=(int)f*2;
  18.  
  19. if(d==n)
  20. System.out.println(n+" is a even number");
  21. else
  22. System.out.println(n+" is a odd number");
  23. }

  24. }

Output:

  1. Enter a number to check whether it is even or odd without using Modulus and Division
  2. 4
  3. 4 is Even Number



You might like:

ObjectInputStream and ObjectOutputStream

  • ObjectInputStream and ObjectOutputStream classes are used to store objects state permanently in files or to send to remote computer via network.
  • ObjectOutputStream class is subclass of ObjectOutput interface. It implements below method to write object to underline output stream.

  1. public void writeObject(Object ob)throws IOException

  • ObjectInputStream class is a subclass of ObjectInput interface. It implements below method to read object to underline output stream.
  1. public Object readObject() throws IOException

Rule:

  • To write or send object to external world it must be java.io.Serializable interface type.
  • It means this objects class must be a sub class of java.io.Serializable interface, else write() method throws java.io.NotSerializableException.

Constructors to create above two classes objects:

  • Like DataInputStream and DataOutputStream , ObjectInputStream and  ObjectOutputStream are also can not connect to source and destination directly. So their constructors take other input and output stream class objects.
  1. public ObjectInputStream(InputStream in)
  2. public ObjectOutputStream(OutputStream out)

  1. package instanceofjava;
  2.  
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectOutputStream;
  5. import java.io.Serializable;
  6.  
  7. public class SerDemo implements Serializable {
  8.  
  9.     String name;
  10.     String phonum;
  11.     String address;
  12.     int pin;
  13.  
  14.    public String getName() {
  15.        return name;
  16.     }
  17.  
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.  
  22.     public String getPhonum() {
  23.         return phonum;
  24.    }
  25.  
  26.     public void setPhonum(String phonum) {
  27.         this.phonum = phonum;
  28.     }
  29.  
  30.    public String getAddress() {
  31.         return address;
  32.     }
  33.  
  34.     public void setAddress(String address) {
  35.         this.address = address;
  36.     }
  37.  
  38.    public int getPin() {
  39.         return pin;
  40.     }

  41.   public void setPin(int pin) {
  42.         this.pin = pin;
  43.     }
  44.  
  45. public static void main(String[] args)throws Exception{
  46.  
  47.     SerDemo empobj= new SerDemo();
  48.     empobj.setName("sai");
  49.     empobj.setAddress("xxx, xxxstreet ");
  50.     empobj.setPhonum("040-9999999");
  51.     empobj.setPin(500072);
  52.  
  53.     ObjectOutputStream oos= new ObjectOutputStream(new
  54.     FileOutputStream("E:\\employee.ser"));
  55.  
  56.     oos.writeObject(empobj);
  57.  
  58. }
  59. }




  1. package instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.ObjectInputStream;
  5.  
  6. public class DeserDemo {
  7.  
  8. public static void main(String[] args)throws Exception{   
  9.  
  10.    ObjectInputStream ois= new ObjectInputStream(new FileInputStream("E:\\employee.ser"));
  11.       SerDemo obj= (SerDemo)ois.readObject();
  12.       System.out.println(obj.getAddress()):
  13.  
  14.     }
  15. }

Output:

  1. sai
  2. xxx, xxxstreet 
  3. 500072
  4. 040-9999999

  • This is the actual functionality of ObjectOutputStream and ObjectInputStream: Serialization and deserialization

Serialization:

  • Serialization is the process of converting objects into stream of  bytes and sending them to underlying output stream.
  • Using serialization we can store object state permanently in a destination , for example on remote computer.
  • Serialization operation performed by the writeObject() method of ObjectOutputStream.

Deserialization:

  • Deserialization is the process of converting stream of bytes into original object.
  • Deserialization operation is performed by readObject() of ObjectInputStream.

Rule:

  • Only java.io.serializable type objects are serialized. Serializable is a marker interface, it does not have any methods.  
  • It provides special permission or identity to JVM to serialize Object.
  • If the given object is not of type serializable interface then writeObject() will throw an unchecked exception called java.io.NotSerializableException.

DataInputStream and DataOutPutStream

  • These classes are used to read and write data as primitive type from the underlying InputStreams and Output Streams.
  • DataInputStream and DataOutputStream classes have special methods to perform reading and writing operations as primitive data.

DataInputStream:

  • DataInputStream is a sub class of FilterInputStream and DataInput Interface.
  • It implements  below methods from the DataInput interface for reading bytes from a binary stream and convert them in to corresponding java primitive type.

 DataInputStream methods:

  • public byte readByte()
  • public short readShort()
  • public int readInt()
  • public long readLong()
  • public float readFloat()
  • public double readDouble()
  • public char readChar()
  • public boolean readBoolean()
  • public String readUTF()
  • public String readLine()

DataOutPutStream:

  • DataOutputStream class is a subclass of FilterOutputStream and DataOutput interface.
  • It implements below methods from DataOutput interface for converting data of any java primitive types to a stream of bytes and writing these bytes to a binary stream.


DataOutPutStream Methods:

  • public void writeByte(byte b)
  • public void writeShort(short s)
  • public void writeInt(int i)
  • public void writeLong(long l)
  • public void writeFloat(float f)
  • public void writeDouble(double d)
  • public void writeChar(char ch)
  • public void writeBoolean(boolean b)
  • public void writeUTF(String s)
  • public void writeBytes(String s)

  • To read data as primitive types using above readXxx() methods , the data must be written to the file as primitive types using writeXxx() methods.
  • readXxx() methods must be called in the same order in which the writeXxx() methods are called otherwise wrong value will be returned or EOFException will occur.

Program to Write data as primitive type using DataInputStream


  1. package instanceofjava;
  2.  
  3. import java.io.DataOutputStream;
  4. import java.io.FileOutputStream;
  5.  
  6. public class DOSDemo {
  7.  
  8. public static void main(String [] args) throws Exception{
  9.  
  10.   FileOutputStream fos= new FileOutputStream("data.txt");
  11.   DataOutputStream dos = new DataOutputStream(fos);
  12.  
  13.     dos.writeInt(37);
  14.     dos.writeFloat(2.15f);
  15.     dos.writeChar('c');
  16.     dos.writeBoolean(true);
  17.     dos.writeUTF("instance of java");
  18.  
  19.   }
  20. }



  • After compilation and execution in current working directory you can find the "data.txt".
  • Check data.txt file size.
  • To check file size "right click on the file"-> click on properties
  • You will get size = size of all primitive data types mentioned in program check it.
  • From this program we can prove boolean takes 1 byte, the minimum memory location size in java is 1 byte. 
  • For string data including double quotes JVM provides 1 byte for each character.

Program to Read data as primitive type using DataOutputStream

  1. package instanceofjava;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.FileInputStream;
  5.  
  6. public class DISDemo {
  7.  
  8. public static void main(String [] args) throws Exception{
  9.  
  10.     FileInputStream fis= new FileInputStream("D:\\data.txt");
  11.    DataInputStream dis = new DataInputStream(fis);
  12.  
  13.     int i=    dis.readInt();
  14.    float f=dis.readFloat();
  15.    char ch=dis.readChar();
  16.    boolean b=dis.readBoolean();
  17.    String str= dis.readUTF();
  18.  
  19.     System.out.println(i);
  20.     System.out.println(f);
  21.     System.out.println(ch);
  22.     System.out.println(b);
  23.     System.out.println(str);
  24.  
  25.     }
  26. }

  • Execute the above application by changing readXxx() methods calling order.
  • Then check you will get right value or not.
  • Actually readXxx() method read number of bytes from the file based on the data type.
  • For example if we call readInt() method it read 4 bytes from file.
  • So if our bytes are available in file program executed fine, execution terminates with EOFException.

Limitations in DataInputStream and DataOutputStream:

  • Using DataInputStream and DataOutputstream we can not read and write objects from persistence media.
  • They have only capability to read data up to only primitive data types.

Solution:

  • To read and write objects we must use ObjectInputStream and ObjectOutputStream.

JSP Implicit Objects

  • Implicit objects in jsp are the objects that are created by the container automatically and the container makes all these 9 implicit objects to the developer.
  • We do not need to create them explicitly, since these objects are created and automatically by container and are accessed using standard variables(objects) are called implicit objects.
  • The following are of implicit variables available in the JSP.  

9 Jsp implicit Objects

1.out
2.request
3.response
4.config
5.application
6.session
7.pagecontext
8.page
9.exception



1.out:

  •  out is one the implicit object to write the data to the buffer and send output to the client in response.
  • out object allows us to access the servlets output stream and has a pagescope.
  • out.print("");
  • out is the object of javax.servlet.jsp.JspWriter class.
  • While working with servlet we need printWriter object
  • PrintWriter out=response.getWriter();   
  • In servlet we are used PrintWriter to send the output to the client. In JSP we use JSPWriter. 

Difference between JspWriter and PrintWriter:

  • Every JSPWriter is associated with 8KB of internal Buffer. Where as PrintWriter doesn’t associated with any Buffer.
  • The methods of the JspWriter class are designed to throw java.io.IOException where as the methods of PrintWriter class are not throw Exception.
  • JspWriter is an abstract class present in javax.servlet package.
  • PrintWriter is a class defined in java.io package.
  1. public class PrintWriter extends Writer { 
  2. // .....
  3. }
  4.  
  5. public abstract class JspWriter extends Writer {
  6. //....
  7. }

JspWriter out object in jsp:

  1. <html> 
  2. <body> 
  3. <%
  4.     int a = 10;
  5.     int b = 20;
  6.     out.print(“A value is:”+a);
  7.     out.write(“B value is:”+b);
  8. %>
  9. </body> 
  10. </html> 



Printwriter object in servlet:

  1. PrintWriter out=response.getWriter();  

2.request:

  • request implicit object is the object of  type  HttpServletRequest.
  • request object will be created by the container for every request.
  • It will be used to get request information like parameter , header information ,server name server port etc.
  • By using request object we can able to set ,get and remove attributes from request scope.
  • It uses the getPareameter() method to access request parameter.
  • The container passes this object to the _jspService() method.


  1. <form action="welcome.jsp">  
  2. <input type="text" name="username">  
  3. <input type="submit" value="submit"><br/>  
  4. </form> 

  1. <%   
  2. String name=request.getParameter("userid");  
  3. out.print("welcome "+name);  
  4. %> 

  1. out.println(request.getMethod()+”<br>”);
  2. out.println(request.getRequestURI()+”<br>”);
  3. out.println(request.getProtocol()+”<br>”);
  4. out.println(request.getHeader(“User Agent”)+”<br>”);
  5. out.println(request.getHeader(“Accept-language”)+”<br>”);

3.response:

  • response is an instance of class which implements the HttpServletResponse interface.
  • Container generates this object and passes to the _jspService() method as parameter.
  • response object will be created by the container for each request.
  • It represents the response that to be given to the client. 
  • The response implicit object is  used to content type, add cookie and redirect the response to another resource.

1.set content type.

  1. response.setContextType(“text/xml”);
  2. out.println(“<employee>”);
  3. out.println(“<eno>|</eno>”);
  4. out.println(“</employee>”);

2.Redirect response:

  1. <%  
  2.     response.sendRedirect("http://www.instanceofjava.com"); 
  3. %>

3. To send the error message directly to the client:

  1. <%  response.sendError(537,”xyz”); %>

4.config

  • config is one of the implicit object of type javax.servlet.ServletConfig.
  • config object is created by the web container for each jsp page.
  • config object used to get initialization parameters from web.xml file.


  1. <web-app>
  2.  
  3. <servlet>  
  4. <servlet-name>instanceofjava</servlet-name>  
  5. <jsp-file>/welcome.jsp</jsp-file>  
  6. <init-param>  
  7. <param-name>dname</param-name>  
  8. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
  9. </init-param>  
  10. </servlet>  
  11.  
  12. <servlet-mapping>  
  13. <servlet-name>instanceofjava</servlet-name>  
  14. <url-pattern>/welcome</url-pattern>  
  15. </servlet-mapping>  
  16.  
  17. </web-app> 

  1. <%   
  2. String driver=config.getInitParameter("dname");  
  3. out.print("driver name="+driver);  
  4. %> 

  • servletConfig is an object used by servlet container to pass the information during initialization.
  • Once if we get the ServletConfig object, we can find the name of the servlet which is configured in web.xml file by using a method getServletName() method.

  1. <%
  2. String name = config.getServletName();
  3. oput.println(name);
  4. %>


5.application:

  • application is one of the implicit object of type javax.servlet.ServletContext.
  • application object is created by the web container one per application when the application gets deployed.
  • application object used to get context parameters from web.xml file.
  • ServletContext object contains set of methods which are used to interact with ServletContainer. By using these methods we can find the information about ServletContainer.
  • When ever sun micro system releases a new version of API. It is the responsibility of server vender to provide the implementation to the latest API. 
  • For example when servlet 2.5 is released Tomcat guys has provided the implementation and integrated it in Tomcat 6.0 the latest version of servlet API is 3.0 this version is integrated in Tomcat 7.0.
     

  1. <web-app>
  2.  
  3. <servlet>  
  4. <servlet-name>instanceofjava</servlet-name>  
  5. <jsp-file>/index.jsp</servlet-class>  
  6. </servlet>  
  7.  
  8. <servlet-mapping>  
  9. <servlet-name>instanceofjava</servlet-name>  
  10. <url-pattern>/index</url-pattern>  
  11. </servlet-mapping> 
  12.  
  13. <context-param>  
  14. <param-name>dname</param-name>  
  15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
  16. </context-param>  
  17.  
  18. </web-app>

  1. <%   
  2. String driver=application.getInitParameter("dname");  
  3. out.print("driver name="+driver);  
  4. %> 

6.session

  • session implicit object is holding HttpSession object.
  • session object used to set, get, and remove attributes to the session scope and also used to get session information.

index.html

  1. <html>  
  2. <body>  
  3. <form action="/welcome">  
  4. <input type="text" name="uname">  
  5. <input type="submit" value="submit"><br/>  
  6. </form>  
  7. </body>  
  8. </html>   

welcome.jsp

  1. <html>  
  2. <body>  
  3. <%   
  4. String name=request.getParameter("uname");  
  5. out.print("Welcome "+name);  
  6. session.setAttribute("user",name);  
  7. <a href="showuserinfo.jsp">showuser details</a>  
  8. %>  
  9. </body>  
  10. </html>   

showuserinfo.jsp

  1. <html>  
  2. <body>  
  3.  
  4. <%   
  5. String name=(String)session.getAttribute("user");  
  6. out.print("Hello "+name);  
  7. %>  
  8.  
  9. </body>  
  10. </html> 
  11. %> 

7.pagecontext:

  • pagecontext implicit object is type of  PageContext.
  • pagecontext object used to set , get and remove attributes in particular scope
  1. page scope
  2. request scope
  3. session scope
  4. application scope

  1. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
  2.  String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE); 

8.page

  • Page implicit variable hold the currently executes Servlet object for the corresponding JSP.
  • Acts as this object for current jsp page
  1.  <%=page.getClass().getName() %>
  2.   <%=page.getServlestInfo()%> 

9.exception

  • The implicit variable can be used only in Error pages. When we try to use this variable in a JSP which is not an Error page we get an Error message.

  1.  <%@ page isErrorPage="true" %>  
  2. <html>  
  3. <body>   
  4.  
  5. <%= exception %>  
  6.  
  7. </body>  
  8. </html> 


Java 8 Interface Static and Default Methods


Java 8 interface static and default methods

  • Java 8 introduced two new methods in interface they are
    1.default methods
    2.static methods
  • By this interfaces and abstract class are same but still having lot differences like abstract class can have a constructor etc will discuss more before that we need to know about these Java 8 features of interfaces.
  • Defaults methods are also called as defender methods can be implemented inside the interface
  • Like normal class now with java 8 we can declare static methods in side a interface.
  • Lets jump deep into Java 8 default and static methods 

  

1.Interface Default Methods in Java 8


  • Before Java 8 in interfaces we can and able to declare only abstract methods only.
  • If we declare a method without abstract that will be treated as abstract by default.
  • As we know all methods in interfaces are by default abstract methods.
  • These methods wont have body means implementations
  • The class which is implementing this interface need to provide body / implementation for this abstract methods.
  • Now with java 8 default methods we can add methods to interface without disturbing existing functionality.
  • So instead of overriding now we can inherit these default methods from interfaces

  • Defaults methods are also  known as defender methods or virtual extension methods
  • Default methods will help us to avoid utility classes.
  • We can define utility methods inside the interface and use it in all classes which is implementing.
  • One of the major reason to introduce this default methods in java 8 is to support lambda expressions in collections API and to enhance.


  1. package com.instanceofjava;
  2. interface Java8Interface{
  3.  
  4. abstract void show();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. }

  1. package com.instanceofjava;
  2. class Sample implements Java8Interface {
  3.  
  4. void show(){
  5. System.out.print("overridden method ")
  6.  }
  7. public static void main(String[] args){
  8.   
  9. Sample obj= new Sample();
  10.  
  11. obj.show(); // calling implemented method
  12. obj.display(); // calling inherited method
  13. Java8Interface.display(); calling using interface name
  14.  
  15. }
  16.  
  17. }



Output:

 

  1. overridden method
  2. default method of interface
  3. default method of interface


How to call default methods:

 

  • We can all these default methods by using interface name and also by using object of the class which is implementing.
  • From above example
  • obj.show(); // calling implemented method
  • obj.display(); // calling inherited method
  • Java8Interface.display(); calling using interface name

Can we override java 8 default method

  • As we discussed above default methods in interfaces are implemented methods with bodies
  • Yes we can override same method in class which is implementing this interface.
  • Lets see one sample program how to override and what happens if we override


  1. package com.instanceofjava;
  2. interface InterfaceWithDefault{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. class Demo implements InterfaceWithDefault{
  3.  
  4. void defMethod(){
  5.  
  6. System.out.print("overridden method in class Demo ") 
  7.  
  8.  }
  9. public static void main(String[] args){
  10.   
  11. Demo obj= new Demo();
  12.  
  13. obj.defMethod(); // calling overridden method
  14. Java8Interface.defMethod(); calling using interface name : interface defMethod will be called
  15.  
  16. }
  17.  
  18. }

Output:


  1. overridden method in class Demo
  2. default method of interface

What happens if we implement two interfaces having same default methods

  • Now lets see if a class implementing two interfaces which are having same default methods
  • Whatever the implementation in the two interfaces defined if we implementing two interfaces which are having a default method in both then compilation error will come if two methods have same signature. works fine if two methods have same name with different arguments.
  • Check the below example programs to understand more.


  1. package com.instanceofjava;
  2. interface A{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface: A");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. interface B{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface: B");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. class Demo implements A, B{ // compilation error will come
  3.  
  4. public static void main(String[] args){
  5.   
  6. Demo obj= new Demo();
  7.  
  8.  
  9. }
  10.  
  11. }


  • If we implement two interfaces which are having same method with same parameters then compilation error will occur.
  • Duplicate default methods named "defMethod" with the parameters () and () are inherited from the types A and B.
  • If we define two methods with different type of parameters then we can work with both interfaces.



  1. package com.instanceofjava;
  2. interface A{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("Default method of interface: A");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. interface B{
  3.  
  4. default void defMethod(String str){
  5.  
  6. System.out.println("Default method of interface: B");
  7. System.out.println(str);
  8.  
  9.  
  10. }
  11.  
  12. }

  1. package com.instanceofjava;
  2. class Demo implements A, B{ // compilation error will come
  3.  
  4. public static void main(String[] args){
  5.   
  6. Demo obj= new Demo();
  7. obj.defMethod();
  8. obj.defMethod("Java 8")
  9.  
  10.  
  11. }
  12.  
  13. }

Output:

  1. Default method of interface: A
  2. Default method of interface: B 
  3. Java 8


1.Interface Static Methods in Java 8

  • Another Java 8 interface method is static method.
  • Now we can define static methods inside interface but we can not override these static methods.
  • These static method will act as helper methods.
  • These methods are the parts of interface not belongs to implementation class objects.

  1. package com.instanceofjava;
  2. interface StaticInterface{
  3.  
  4. Static void print(String str){
  5.  
  6. System.out.println("Static method of interface:"+str);
  7.  
  8. }
  9. }

  1. package com.instanceofjava;
  2. class Demo implements StaticInterface{
  3.  
  4. public static void main(String[] args){
  5.   
  6.  StaticInterface.print("Java 8")
  7.  
  8. }
  9.  
  10. }

Output:

  1. Static method of interface: Java 8


8 New Java 8 Features



Java 8 features

  1. Default and Static methods in Interface
  2. Lambda Expressions
  3. Optional
  4. Streams
  5. Method References
  6. Data Time API
  7. Nashorn Javascript Engine
  8. Parallel Arrays

 

 

 

1.Default and Static methods in Interface :

  • Java 8 introduces new features to interfaces.
  • Before java 8 interface having only abstract methods but now java 8 added two more type of methods to interface !.
  • First one is default method. A method which is having a default keyword with method body.
  • Actually interfaces wont have any implemented methods  but now with java 8 default method we can add a method with default implementation by using "default " keyword.
  • The classes which are implementing this interface can use these default method and same time it can override the existing method. But its not mandatory to override.

  1. package com.instanceofjava;
  2. interface Java8InterfaceDemo{
  3.  
  4. abstract void add();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. }


  • The second new method introduced in java 8 is static method.
  • Yes like in classes now we can define a static methods inside interface by using "static".
  • Basically static methods which are defined in interface are interface level only. if we want to call these static methods which are defined in interfaces we need to use interface name so that we can access these methods.

  1. package com.instanceofjava;
  2. interface Java8InterfaceDemo{
  3.  
  4. abstract void add();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. public static void show(){
  13.  
  14. System.out.println("static method of interface");
  15.  
  16. }
  17.  
  18. }

2.Lambda Expressions 

  • One of the most awaited and biggest release in java 8 is lamda expressions.
  • Ability to pass functionality/ behavior  to methods as arguments.
  • Allows us to write a method in the same place we are going to use it.

  1. package com.instanceofjava;
  2. interface JavalamdaExpression{
  3.  
  4. public static void main(String[] args){
  5.  
  6.  Arrays.asList( "j", "a", "v" ,"a","8").forEach( e -> System.out.print( e ) );
  7.  // java8
  8. }
  9.  
  10. }



3.java.util.Optional:

  • One of the best and cool feature of java 8 is Optional class. Which is a final calls from java.util package.
  • The major repeating statement in every project is checking "NullPointerException". Before using any object we need to check whether it is null or not if its not null then only we need to proceed.
  • Optional is just like a container which holds a value of type <T> or "null". By using isPresent() method of Optional class we can check particular object is null not not.


  1. package com.instanceofjava;
  2. import java.util.Optional:
  3. class Java8OptionalDemo{
  4.  

  5.  
  6. public static void main(String[] args ){
  7.  
  8.  Optional< String > str = Optional.ofNullable( null );
  9.  System.out.println( "str having value ? " + str.isPresent() ); // output : str having value ? false
  10.  
  11. }
  12.  
  13. }



4.Streams:

  • One of the excellent feature from java 8 as java.util.stream.
  • Stream API  introduces real-world functional-style programming into the Java.
  • Provides functional operations on stream of elements such as list , set and map 
  • Supports filtering, mapping and removal of duplicates of elements in collections, are implemented lazily.
  • Now we can get Streams from collections, arrays and bufferedReaders etc.


  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3. class Java8StreamsDemo{
  4.  
  5. public static void main(String[] args ){
  6.  
  7.   Arrays.stream(new int[] {1, 2, 3,4,5})
  8.     .map(n -> 2 * n + 1) 
  9.    .average()
  10.     .ifPresent(System.out::println); // output: 7.0
  11.  
  12.  
  13. }
  14.  
  15. }

5.Method Reference:

  • We can use lambda expressions to create anonymous methods. 
  • Sometimes, however, a lambda expression does nothing but call an existing method.
    In those cases, it's often clearer to refer to the existing method by name.
  • Using Method references refer to the existing method by name, they are compact, easy-to-read lambda expressions for methods that already have a name


  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3.  
  4. class Java8MethodRef{
  5.  
  6.   public  void show(String str){
  7.  
  8.         System.out.println(str);
  9.  
  10.    }
  11.  
  12. public static void main(String[] args ){
  13.  
  14.    Arrays.asList("a", "b", "c").forEach(new A()::show); // a b c

  15.  
  16. }
  17.  
  18. }

6.Data Time API  

  • The next cool feature from java 8 is new date time API(jsr 310) added within java.time package.
  • Before java 8 if we want to format dates we use SimpleDateFormatter class in java 8 while declaring date itself it has constructor to pass format of date.
  •  Some of the new classes introduced in java 8 date time are as follows.
  1. LocalTime
  2. LocalDate 
  3. LocalDateTime
  4. OffsetDate
  5. OffsetTime
  6. OffsetDateTime




  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3.  
  4. class Java8DateTimeAPI{
  5.  
  6. public static void main(String[] args ){
  7.          
  8.     LocalDate currentDate = LocalDate.now();
  9.     System.out.println(currentDate);
  10.     
  11.     LocalDate twentyMarch2015 = LocalDate.of(2015, Month.MARCH, 06);
  12.     System.out.println(twentyMarch2015);  //2015-03-06
  13.  
  14.      LocalDate firstApril2015 = LocalDate.of(2015, 4, 1);
  15.      System.out.println(firstApril2015);//2015-04-01

  16.  
  17. }
  18.  
  19. }

 

7.Nashorn Javascript Engine


  •  Java 8 come with new Nashorn Javascript Engine which is allowing us to develop and run JavaScript applications.


  1. package com.instanceofjava;
  2.  
  3. import javax.script.ScriptEngine;
  4. import javax.script.ScriptEngineManager;
  5. import javax.script.ScriptException;
  6.  
  7. import java.util.Arrays;
  8.  
  9. class Java8JavaScript{
  10.  
  11. public static void main(String[] args ){
  12.          
  13.   ScriptEngineManager manager = new ScriptEngineManager();
  14.   ScriptEngine engine = manager.getEngineByName( "JavaScript" );
  15.   System.out.println( engine.getClass().getName() );
  16.   System.out.println( "output:" + engine.eval( "function show() { return 10; }; show();" ) );
  17.  
  18. }
  19.  
  20. }

  1. jdk.nashorn.api.scripting.NashornScriptEngine
  2. output:10


8.Parallel Array Sorting

  • As of now java 7 we already having Arrays.sort() method to sort objects now java 8 introduced parallel sorting which has more speed than arrays.sort() and follows Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads that are available in the thread pool.
  • Java 8 added parallel sorting functionalities to java.util.Arrays to take advantage of multithread machines 


  1. package com.instanceofjava;
  2. import java.util.Arrays;

  3. class Java8JavaScript{
  4.  
  5. public static void main(String[] args ){
  6.          
  7.          int arr[]={1,4,2,8,5};
  8.          Arrays.parallelSort(arr);
  9.  
  10.          for(int i:arr){  
  11.              System.out.println(i);  
  12.            } 
  13.  
  14. }
  15.  
  16. }



You might like:
Select Menu