添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Pre-requisite : Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “ java.util.InputMismatchException ” because using scanner.next(regex) but some words in test data  not matching regex “\W” for word as in “Sr. project Lead” in given example.

Test data in file

Saurabh Gupta 36 "Sr project Lead" Noida Sailesh Nagar 34 "Project Lead"

Example

package scanner; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerToReadInputFromFile { public static void main(String[] args) { try { // Decalare Scanner and intialize with File input object Scanner sc = new Scanner( new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt")); while (sc.hasNextLine()) { //System.out.println(sc.next(Pattern.compile("\\w+"))); } catch (FileNotFoundException ex) { ex.printStackTrace();

Output

Saurabh Gupta Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:17)

Solution
Always handle exception while using regular expressions. In this example pattern is not matching for ‘Sr Project Lead’ because word pattern allow on [A-Za-z0-1] char only.

More on JDBC

Follow below links to learn more posts on JDBC and solving JDBC related issues :

  • JDBC Tutorial
  • JDBC Sample Code
  • JDBC Issues and Solutions
  • JDBC Interview Questions And Answers
  • JDBC Coding Best Practices
  • Java , JDBC , Vs

    JDBC: Difference between Statement, PreparedStatement and CallableSatement

    Leave a comment

    JDBC API introduced statement , PreparedStatement and CallableStatemnet to execute different types of queries:

  • Statement : Used to execute Normal SQL Queries.
  • PreparedStatement : Used to execute dynamic or parameterized queries.
  • CallableStatement: Used to execute StoredProcedure.
  • Statement Vs PreparedStatement Vs CallableStatement

    Statement Prepared Statement Callable Statement It is used to execute normal SQL queries. It is used to execute dynamic or parameterized SQL queries. It is used to execute Stored procedure or function . It is proffered when particular query to be executed only once. It is proffered when particular query to be executed multiple times. It is proffered when stored procedure or functions to be executed. You can no pass parameter to query by using this interface. You can pass parameter to query at run time by using this interface. You can pass three types of parameters by using this interface IN, OUT and IN OUT This interface mainly used for DDL statements like CREATE, ALTER , DROP etc. This is used to be any kind of SQL queries which are used multiple times It is used with Stored Procedure and functions . The performance of this interface is very low. The performance of this interface is better than query while using with multiple queries. Performance of this interface is very high because stored procedure execute on database end. For More: Statement For More: Prepared Statement For More: Callable Interface

    Learn More on JDBC

    Follow below links to know more on JDBC and solving JDBC issues :

  • JDBC Tutorial
  • JDBC Sample Code
  • JDBC Issues and Solutions
  • JDBC Interview Questions And Answers
  • JDBC Coding Best Practices
  • //Here database exists in the current directory String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=" + database + ";DriverID=22;READONLY=true"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection(url); Statement st=c.createStatement(); ResultSet rs=st.executeQuery("select * from login"); while(rs.next()){ System.out.println(rs.getString(1)); }catch(Exception ee){System.out.println(ee);}


    Example to Connect Java Application with access with DSN
    Connectivity with type-1 driver is not considered good. To connect java application with type-1 driver, create DSN first, here we are assuming your dsn name is mydsn.

    import java.sql.*; class Test{ public static void main(String ar[]){ String url="jdbc:odbc:mydsn"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection(url); Statement st=c.createStatement(); ResultSet rs=st.executeQuery("select * from login"); while(rs.next()){ System.out.println(rs.getString(1)); }catch(Exception ee){System.out.println(ee);}

    Here you have learned both the ways to access with or without DSN (Data Source Name).

    See Also:

    Learn More on JDBC

    Follow below links to learn more on JDBC and solving JDBC related issues :

    For connecting with the Oracle database from JAVA application, you need to follow 5 steps to perform database connectivity . Below are connection information specific to oracle database:

    1. Driver class: The driver class for the oracle database is oracle.jdbc.driver . OracleDriver.
    2. Connection URL: The connection URL for the oracle database is jdbc:oracle:thin:@localhost:1521:FacingIssuesOnITDB here jdbc is the API, oracle is the database, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and FacingIssuesOnITDB is the database name. We may use any database, in such case, you need to replace the FacingIssuesOnITDB with your database name.
    3. Username: The default username for the oracle database is root.
    4. Password: Password is given by the user at the time of installing the oracle database. In this example, we are going to use root as the password.
    import java.sql.*; class OracleConnection{ public static void main(String args[]){ //Step 1: Register the driver class Class.forName("oracle.jdbc.driver.OracleDriver"); //Step 2: Create connection with database Connection con=DriverManager.getConnection( "jdbc:oracle:thin@localhost:1521:FacingIssuesOnITDB","root","root"); //here FacingIssuesOnITDB is database name, root is username and password //Step 3: Create statement Statement stmt=con.createStatement(); //Step 4: Execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); //Step 5: close connection con.close(); catch(ClassNotFoundException e){ System.out.println(e); catch(SQLException e){ System.out.println(e);

    Here you learn about steps to connect database with application and specific configuration information for Oracle.

    See also :

    Learn More on JDBC

    Follow below links to learn more on JDBC and solving JDBC related issues :

    For connecting with the MySQL database from JAVA application, you need to follow 5 steps to perform database connectivity . Below are connection information specific to MySQL database:

  • Driver class: The driver class for the MySQL database is com.mysql.jdbc.Driver .
  • Connection URL: The connection URL for the MySQL database is jdbc:mysql://localhost:3306/FacingIssuesOnITDB where jdbc is the API, MySQL is the database, localhost is the server name on which MySQL is running, we may also use IP address, 3306 is the port number and FacingIssuesOnITDB is the database name. We may use any database, in such case, you need to replace the FacingIssuesOnITDB with your database name.
  • Username: The default username for the MySQL database is root.
  • Password: Password is given by the user at the time of installing the MySQL database. In this example, we are going to use root as the password.
  • import java.sql.*; class MySQLConnection{ public static void main(String args[]){ //Step 1: Register the driver class Class.forName("com.mysql.jdbc.Driver"); //Step 2: Create connection with database Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/FacingIssuesOnITDB","root","root"); //here FacingIssuesOnITDB is database name, root is username and password //Step 3: Create statement Statement stmt=con.createStatement(); //Step 4: Execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); //Step 5: close connection con.close(); catch(ClassNotFoundException e){ System.out.println(e); catch(SQLException e){ System.out.println(e);

    Here you learn about steps to connect database with application and specific configuration information for MySQL.

    See also :

  • JDBC Connection with Oracle Database
  • JDBC Connectivity with access without DSN (Data Source Name)
  • More on JDBC

    Follow below links to know more on JDBC and solving JDBC issues :

    JDBC Tutorial

    JDBC Sample Code

    JDBC Issues and Solutions

    JDBC Interview Questions And Answers

    There are 5 steps to connect any java application with the database by using JDBC. They are as follows:

  • Register the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection
  • Register the driver class

    The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

    public static void forName(String className)throws Class.forName("oracle.jdbc.driver.OracleDriver");

    Create the connection object

    The getConnection() method of DriverManager class is used to establish connection with the database.

    1) public static Connection getConnection(String url)throws SQLException 2) public static Connection getConnection(String url,String name,String password) throws SQLException

    Ex: Connect with Oracle

    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");

    Create the Statement object

    The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.

    public Statement createStatement()throws SQLException Statement stmt=con.createStatement();

    Execute the query

    The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.

    public ResultSet executeQuery(String sql)throws SQLException ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2));

    Close the connection object

    By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

    public void close()throws SQLException

    See Also :

  • JDBC Connection with MySQL Database
  • JDBC Connection with Oracle Database
  • JDBC Connectivity with access without DSN (Data Source Name)
  • More on JDBC

    Follow below links to learn more on JDBC and solving JDBC related issues :

  • JDBC Tutorial
  • JDBC Sample Code
  • JDBC Issues and Solutions
  • JDBC Interview Questions And Answers
  • public static void main(String[] args) { try { // Decalare Scanner and intialize with File input object Scanner sc = new Scanner( new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt")); while (sc.hasNextLine()) { System.out.println(sc.nextLine()); System.out.println(sc.next()); //System.out.println(sc.next(Pattern.compile("\\w+"))); } catch (FileNotFoundException ex) { ex.printStackTrace();

    Output

    Saurabh Gupta 36 "Sr project Lead" Noida Sailesh Nagar 34 "Project Lead" Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:15)

    Solution
    Always use scanner.next() after checking scanner.hasNext()condition. If scanner.hasNext() returning true then only call scanner.next().

    Pre-requisite : Java: Enumeration Handling

    This exception EnumConstantNotPresentException thrown when an application tries to access an enum constant by name and the enum type contains no constant with  the specified name. This exception can be thrown by the API used to read annotations reflectively.

    Example :

    In this below example trying to read annotation by using reflection APIs. Here if api attempt to read an enum-valued member will result in a EnumConstantNotPresentException if the enum constant in the annotation is no longer present in the enum type. Compile everything and run ReadAnnotation. You will got C.

    // TestEnum.java public enum TestEnum { A, B, C; // TestAnnotation.java import java.lang.annotation.*; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TestAnnotation { TestEnum value(); // TestClass.java @TestAnnotation(TestEnum.C) public class TestClass { // ReadAnnotation.java public class ReadAnnotation { public static void main(String[] args) { System.out.println(TestClass.class.getAnnotation(TestAnnotation.class).value());

    To generate this exception, now remove the C from the TestEnum and recompile only TestEnum class preserving other classes as is. If you launch ReadAnnotation now, you will get:

    Exception in thread "main" java.lang.EnumConstantNotPresentException: TestEnum.C at sun.reflect.annotation.EnumConstantNotPresentExceptionProxy.generateException(Unknown Source) at sun.reflect.annotation.AnnotationInvocationHandler.invoke(Unknown Source) at com.sun.proxy.$Proxy1.value(Unknown Source) at ReadAnnotation.main(ReadAnnotation.java:4)

    References :

    https://stackoverflow.com/questions/31261960/when-does-java-lang-enumconstantnotpresentexception-gets-thrown

    • The enum added in java  5.
    • The enum keyword is used to define enum type.
    • Each enum constant are by default public static final instance variable.
    • Two enumeration constants can be compared for equality by using == relational operators.
    • The name of enum type’s fields should be in UPPERCASE because they are constant.
    • Use enum types any time when you need to represent a fixed set of constants.
    • Semi colon is optional in side enum type if no any other member.
    • If constructor and methods used inside enum then semi colon required.
    • All enum implicitly extends java.lang.Enum class. Because java doesn’t allow extends of more than one parent class, so an enum can not extend anything else.
    • enum can implement many interfaces.
    • toString() method is overridden inside java.lang.Enum class which returns enum constant name.
    • enum constant can also use in switch case statement.

    Implicit methods of java.lang.Enum

    Below are implicit methods of enum class.

    • values() method can be used to return all values present inside enum .
    • ordinal() method return index of each enum constant, same as array index.
    • valuesOf() method returns the enum constant of specified string value, if exists.

    In the below examples, you will see the use of these methods.

    enum Month{ JANNUARY, FEBRUARY, MARCH, APRIL, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER

    enum with constructor and method definition.

    enum MonthDetail{ JANNUARY("January",1), FEBRUARY("February",2), MARCH("March",3), APRIL("April",4), MAY("May",5), JUNE("June",6), JULY("July",7), AUGUST("August",8), SEPTEMBER("September",9), OCTOBER("October",10), NOVEMBER("November",11), DECEMBER("December",12); public String monthName=""; public int index; //Constructor will always private private MonthDetail(String monthName,int index) this.monthName=monthName; this.index=index; //Method public void showMonthDetail() System.out.println(this.index +" : "+this.monthName); public static void main(String[] args) { //values method return array of constants of type MonthDetail for(MonthDetail monthDetail:MonthDetail.values()) monthDetail.showMonthDetail(); MonthDetail month=MonthDetail.DECEMBER; //two enumeration can be compared by == relational operators if(month==MonthDetail.DECEMBER) //call method of enum to getName of enumerated month month.showMonthName(); PLUS, MINUS, MULTIPLY, DIVIDE public static double Calculate(int left, int right, Operator op) throws Exception { double result = 0.0; switch (op) { case PLUS: result = left + right; break; case MINUS: result = left - right; break; case MULTIPLY: result = left * right; break; case DIVIDE: result = (double) left / right; break; default: throw new Exception("Couldn't process operation: " + op); return result; public static void main(String[] args) { try { System.out.println(Operator.PLUS + " : " + Calculate(20, 10, Operator.PLUS)); System.out.println(Operator.MINUS + " : " + Calculate(20, 10, Operator.MINUS)); System.out.println(Operator.MULTIPLY + " : " + Calculate(20, 10, Operator.MULTIPLY)); System.out.println(Operator.DIVIDE + " : " + Calculate(20, 10, Operator.DIVIDE)); } catch (Exception ex) { ex.printStackTrace();

    Output

    public class EnumTest { enum Month{JANNUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER}; enum MonthDetail{ JANNUARY("January",1), FEBRUARY("February",2), MARCH("March",3), APRIL("April",4), MAY("May",5), JUNE("June",6), JULY("July",7), AUGUST("August",8), SEPTEMBER("September",9), OCTOBER("October",10), NOVEMBER("November",11), DECEMBER("December",12); public String monthName=""; public int index; //Constructor will always private private MonthDetail(String monthName,int index) this.monthName=monthName; this.index=index; //Method public void showMonthDetail() System.out.println(this.index +" : "+this.monthName); public static void main(String[] args) { for(Month month:Month.values()) //Add one because by default enum indexing start from 0 System.out.println((month.ordinal()+1) +" : "+month.name()); //Every enum Class provide values method to get list of enums for(MonthDetail monthDetail:MonthDetail.values()) monthDetail.showMonthDetail(); MonthDetail mnth=MonthDetail.valueOf("Saturday"); catch(Exception ex) ex.printStackTrace(); 11 : November 12 : December Exception in thread "main" java.lang.IllegalArgumentException: No enum constant enm.EnumTest.MonthDetail.Saturday at java.lang.Enum.valueOf(Enum.java:238) at enm.EnumTest$MonthDetail.valueOf(EnumTest.java:1) at enm.EnumTest.main(EnumTest.java:49) MonthDetail mnth=MonthDetail.valueOf("August"); } catch(Exception ex) { ex.printStackTrace();

    To learn more on Enumeration follow below link: Java : Enumeration Handling

    In this blog you will learn way to convert a stack trace to a String which includes all the Stack Trace message of an exception or error.

    Why this conversion is required?

    This conversion is required if you want to save the message in custom log file for further analysis of log message. The e.getMessage() in Java program only returns small portion of the error, but if you want to see the detailed error then StackTrace will give you complete detail about the error in the program.

    Example

    To convert stackTrace to a string using printWriter as input for stackTrace to convert in String.

    import java.io.PrintWriter; import java.io.StringWriter; public class TestExample { public static void main(String[] args) { int y=5/0; catch(Exception ex) System.out.println(convertStackTraceToString(ex)); * method to convert stack trace to String * @param ex * @return private static String convertStackTraceToString(Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); String sStackTrace = sw.toString(); return sStackTrace;

    Output

    java.lang.ArithmeticException: / by zero at com.exceptions.errors.TestExample.main(TestExample.java:11)

    In this blog, you will learn to convert seconds to time. An hour has 60*60=3600 seconds and a minute has 60 seconds.

    Example
    In this example helps you to convert total seconds to time as (hour, minute an d second). To show as text String convert these these values to String.

    public class ConvertSecondToTime { public static void main(String[] args) { long time = 180500700; ConvertSecondToTime ts = new ConvertSecondToTime(); System.out.println("Inserted Total Seconds :"+time); System.out.println(ts.secondsToTimeString(time)); public static String secondsToTimeString(long time) { int seconds = (int) (time % 60); int minutes = (int) ((time / 60) % 60); int hours = (int) ((time / 3600) % 24); String secondsTxt = (seconds < 10 ? "0" : "") + seconds; String minutesTxt = (minutes < 10 ? "0" : "") + minutes; String hoursTxt = (hours < 10 ? "0" : "") + hours; return new String("Converted Time :"+ hoursTxt + " Hour : " + minutesTxt + " Minute :" + secondsTxt + " Second");

    Output

    Inserted Total Seconds :180500700 Converted Time :03 Hour : 05 Minute :00 Second

    In this blog, you will learn to convert decimal number into binary string. The java.lang package provides api’s to convert a decimal number into a binary number.

    Example
    This program takes a decimal number from user as string and convert it to decimal number. toBinaryString() method takes an integer type value and returns its string representation of integer values which represents the data in binary. The base of binary number is 2.

    import java.util.Scanner; public class ConvertDecimalToBinary { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter the decimal value:"); String hex = scan.nextLine(); // convert String to Int int i = Integer.parseInt(hex); // convert integer to binary String by = Integer.toBinaryString(i); // print binary String System.out.println("Binary: " + by);

    Output

    Enter the decimal value: Binary: 1100 Enter the decimal value: Binary: 11001000

    In this article, you will learn to convert a date to GMT, CST, EST and PST format.

  • GMT : Greenwich Mean Time
  • CST : Central Standard Time= GMT-5
  • EST : Eastern Standard Time = GMT-6
  • PST : Pacific Standard Time=GMT-7
  • Example
    This example helps you in converting a date to GMT, CST, EST and PST time on the console. The SimpleDateFormat() constructor uses the given pattern and date format symbols. Here we use the date format as gmtFormat for date format in GMT timezone same way can convert for CST, EST and PST. Then we have used getTimeZone() method to get the time of both the zones to be converted.

    import java.util.*; import java.text.*; public class ConvertTimeZoneFromGMT { public static void main(String[] args) { //Current Date and Time Date date = new Date(); //GMT Format DateFormat gmtFormat = new SimpleDateFormat(); TimeZone gmtTime = TimeZone.getTimeZone("GMT"); gmtFormat.setTimeZone(gmtTime); System.out.println("GMT Time: " + gmtFormat.format(date)); //CST Time DateFormat cstFormat = new SimpleDateFormat(); TimeZone cstTime = TimeZone.getTimeZone("CST"); cstFormat.setTimeZone(cstTime); System.out.println("CST Time: " + cstFormat.format(date)); //EST Time DateFormat istFormat = new SimpleDateFormat(); TimeZone estTime = TimeZone.getTimeZone("EST"); estFormat.setTimeZone(estTime); System.out.println("EST Time: " + estFormat.format(date)); // PST Time DateFormat pstFormat = new SimpleDateFormat(); TimeZone pstTime = TimeZone.getTimeZone("PST"); pstFormat.setTimeZone(pstTime); System.out.println("PST Time: " + pstFormat.format(date));

    Output

    GMT Time: 3/22/19 8:39 AM CST Time: 3/22/19 3:39 AM EST Time: 3/22/19 2:09 PM PST Time: 3/22/19 1:39 AM

    In this program converting one time unit value to hour, minute and second. Generally such type of questions asked in interview to check programming logic.

    See Also: Java Program : How to convert units?

    import java.util.Scanner; public class TimeConversion { static int SECOND = 60*60; static int MINUTE = 60; static int HOUR = 1; public static void main(String[] args) { System.out.println("Please enter :\nh for hour\nm for minute \ns for second"); Scanner in = new Scanner(System.in); System.out.println("Convert from:"); String fromUnit = in.nextLine(); System.out.println("Value:"); int val = in.nextInt(); String convertedTime = convertTime(fromUnit,val); System.out.println("Converted Time :"+convertedTime); private static String convertTime(String unit, int value) int h=0,m=0,s=0,seconds=0; //Convert to seconds switch(unit) case "h": seconds=value*SECOND; break; case "m": seconds=value*MINUTE; break; case "s": seconds=value; break; h=seconds/SECOND; value=seconds%SECOND; m=value/MINUTE; value=value%MINUTE; s=value/SECOND; return h+" Hour "+m+" Minute "+s+" Second";

    Output

    Please enter : h for hour m for minute s for second Convert from: Value: Converted Time :1 Hour 0 Minute 0 Second

    In this program you will see, way to convert one length measuring unit to another unit.Generally such type of questions asked to check programming logics.

    See Also : Java Program : Convert time hour minute and seconds

    Example

    import java.util.Scanner; public class UnitConversionCalculator { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Convert from:"); String fromUnit = in.nextLine(); UnitConverter from = new UnitConverter(fromUnit); System.out.println("Convert to: "); String toUnit = in.nextLine(); UnitConverter to = new UnitConverter(toUnit); System.out.println("Value:"); double val = in.nextDouble(); //convert to meter double meters = from.toMeters(val); //convert meter to required unit double converted = to.fromMeters(meters); System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);

    That is main class for unit conversion for length measurement.

    public class UnitConverter { static double INCHES = 39.37; static double FEET = 3.28; static double MILES = 0.00062; static double MILLIMETERS = 1000; static double CENTIMETERS = 100; static double METERS = 1; static double KILOMETERS = 0.001; private double meters, converted; String fromUnit, toUnit; public UnitConverter(String afromUnit) { fromUnit = afromUnit; toUnit = afromUnit; // method to convert given value to meter public double toMeters(double val) { if (toUnit.equals("in")) { meters = (val / INCHES); } else if (toUnit.equals("ft")) { meters = (val / FEET); } else if (toUnit.equals("mi")) { meters = (val / MILES); } else if (toUnit.equals("mm")) { meters = (val / MILLIMETERS); } else if (toUnit.equals("cm")) { meters = (val/ CENTIMETERS); } else if (toUnit.equals("m")) { meters = (val / METERS); } else { meters = (val / KILOMETERS); return meters; // method to convert meter to required unit public double fromMeters(double meters) { if (fromUnit.equals("in")) { converted = Math.round(INCHES * 100 * meters); } else if (fromUnit.equals("ft")) { converted = Math.round(FEET * 100 * meters); } else if (fromUnit.equals("mi")) { converted = Math.round(MILES * 100 * meters); } else if (fromUnit.equals("mm")) { converted = Math.round(MILLIMETERS * 100 * meters); } else if (fromUnit.equals("cm")) { converted = Math.round(CENTIMETERS * meters); } else if (fromUnit.equals("m")) { converted = Math.round(METERS * meters); } else { converted = Math.round(KILOMETERS * meters); return converted;

    Output

    Convert from: Convert to: Value: 1.0 m = 100.0 cm

    Here you will see way to remove duplicate from ArrayList. I am using HashSet because it keeps unique values only.

    See Also : Java : How to remove duplicate objects from List

    Example

    import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RemoveDuplicateElements { public static void main(String[] args) { ListstrList=new ArrayList(); strList.add("Facing"); strList.add("Issues"); strList.add("On"); strList.add("IT"); //duplicate strList.add("Facing"); strList.add("IT"); System.out.println("==========Before Duplicate Remove :"+strList.size()); for(String str:strList) System.out.println(str); //Convert ArrayList to HashSet Set set=new HashSet(strList); //Convert HashSet to ArrayList strList=new ArrayList(set); System.out.println("==========After Duplicate Remove :"+strList.size()); for(String str:strList) System.out.println(str);

    Output

    ==========Before Duplicate Remove :6 Facing Issues Facing ==========After Duplicate Remove :4 Facing Issues

    Why eclipse shortcuts?

    To make developer more productive eclipse provides keyboard shortcuts to perform faster for more common actions.

    “The less you touch the mouse, the more code you can write”

    Eclipse also supports most common shortcuts used with all common editors like , Ctrl+C for copy, Ctrl+S for saving, Ctrl+V for paste etc.

    How to get complete list of eclipse shortcuts?

    You can get complete list of eclipse shortcuts after following below steps:

  • Open Eclipse IDE
  • Got to help. (Screen 1)
  • Click on “Show active key bindings” or “Key Assist” depend on IDE. (Screen 2)
  • On eclipse bottom right corner you will see complete list of eclipse shortcuts.
  • For getting these shortcuts also have one shortcut as Ctrl + Shift + L . (Screen 2)

    Screen 1

    Screen 2

    From above screen you can gets list of all eclipse shortcuts but here we will focus on most common used by developers in day to day development activity.

    What are most commonly used shortcuts by developers to make more productive?

    Here is list of most frequently used shortcuts by developers and corresponding description.

  • Ctrl+Shift+R : Search dialog for resources,  java files,  xml files and properties etc. based on name and matches. as in screen below.
  • same way you can also try others as below.

  • Ctrl+Shift+T : Search dialog for finding files from jar.
  • Ctrl+F8 : Shortcut for switching perspectives
  • Ctrl + Sift +F : for auto formatting
  • Ctrl + Shift + P : find closing braces
  • Ctrl+O : Shows quick outline for going to class method.
  • Ctrl + /  : for commenting, uncommenting lines and blocks
  • Shortcuts to navigation between editors

  • Ctrl+E : Search dialog to select an editor from the currently open editors
  • Alt+← :Go to previous opened editor. Cursor is placed where it was before you opened the next editor
  • Alt+→ : Similar Alt + ← but opens the next editor
  • Ctrl+Q : Go to editor and the position in this editor where the last edit was done
  • Ctrl+PageUp : Switch to previous opened editor
  • Ctrl+PageDown : Switch to next opened editor
  • Shortcuts to navigation between views

  • Ctrl + F7 : Shortcut for switching views. Choose the view to switch to with your mouse or cycle through the entries with repeating the keystroke
  • Shift+Alt+Q : Open menu for switch view keybindings
  • Shift+Alt+Q+P, Shift +Alt +W : Show package explorer
  • Shift+Alt+Q+C : Show console
  • Shortcuts to start Java programs

  • Ctrl+F11 : Run last launched
  • F11 : Run last launched in debug mode
  • Ctrl+Alt+B : Skip all breakpoints. Let’s you use debug mode for code reloading
  • Alt+Shift+X, J : Run current selected class as Java application
  • Alt+Shift+X, T : Run JUnit test
  • Alt+Shift+X, P : Run JUnit Plug-in test
  • Shortcuts to editing in the Java editor

  • Shift+Alt+↑ : Selects enclosing elements.,result depending on cursor position
  • Ctrl+1 : Quickfix; result depending on cursor position
  • Ctrl+Space : Content assist/ code completion
  • Ctrl+T : Show the inheritance tree of the current Java class or method.
  • Ctrl+O : Show all methods of the current class, press Ctrl + O again to show the inherited methods.
  • Ctrl+M : Maximize active editor or view
  • Ctrl+Shift+F : Format source code
  • Ctrl+I : Correct indentation, e.g., format tabs/whitespaces in code
  • Ctrl+F : Opens the find dialog
  • Shift+Enter : Adds a link break at the end of the line
  • Ctrl+Shift+O : Organize the imports; adds missing import statements and removes unused ones
  • Alt+Shift+Z : Wrap the select block of code into a block, e.g. try/catch.
  • Ctrl + /  : for commenting, uncommenting lines and blocks
  • Ctrl + Shift + /  : for commenting, uncommenting lines with block comment
  • Selecting class and pressing F4 to see its Type hierarchy
  • Ctrl + F4 , Ctrl + w : for closing current file
  • Ctrl+Shift+W : for closing all files.
  • Ctrl + l : go to line
  • Select text and press Ctrl + Shift + F for formatting.
  • Ctrl + F :  for find, find/replace
  • Ctrl + D :  to delete a line
  • Ctrl + Q :  for going to last edited place
  • Shortcuts to cursor navigation and text selection

  • Ctrl+← or Ctrl+→ : Move one text element in the editor to the left or right
  • Ctrl+↑ or Ctrl+↓ : Scroll up / down a line in the editor
  • Ctrl+Shift+P : Go to the matching bracket
  • Shift+Cursor movement : Select text from the starting position of the cursor
  • Alt+Shift ↑ / ↓ : Select the previous / next syntactical element
  • Alt+Shift ↑ / ↓ / ← / → : Extending / reducing the selection of the previous / next syntactical element
  • Shortcuts to copy and move lines

  • Ctrl+Alt+↓ : Copy current line below the line in which the cursor is placed
  • Ctrl+Alt+↑ : Copy current line above the line in which the cursor is placed
  • Alt+Up : Move line one line up
  • Alt+Down : Move line one line down
  • Shortcuts to delete lines

  • Ctrl+D : Deletes line
  • Ctrl+Shift+DEL : Delete until end of line
  • Ctrl+DEL : Delete next element
  • Ctrl+BACKSPACE : Delete previous element
  • Shortcuts to create new lines

  • Shift+Enter : Adds a blank line below the current line and moves the cursor to the new line. The difference between a regular enter is that the currently line is unchanged, independently of the position of the cursor.
  • Ctrl+Shift+Enter : Same as Shift + Enter but above
  • Shortcuts to variable assignment

  • Ctrl+2, L : Assign statement to new local variable
  • Ctrl+2, F : Assign statement to new field
  • Shortcuts to coding

  • Shift+F2 : Show the Java doc for the selected type / class / method
  • Alt+Shift+N : Shortcut for the menu to create new objects
  • Alt+Shift+Z : Surround block with try and catch
  • Shortcuts to refactoring

  • Alt+Shift+R : Rename
  • Ctrl+2, R : Rename locally (in file), faster than Alt + Shift + R
  • Alt+Shift+T : Opens the context-sensitive refactoring menu, e.g., displays
  • Shortcuts must known by every developer

    The following shortcuts are the absolute minimum a developer should be familiar with to work efficient in Eclipse.

  • Ctrl+S : Saves current editor
  • Ctrl+1 : Quick fix; shows potential fixes for warnings, errors or shows possible actions
  • Ctrl+Space : Content assist/ code completion
  • Ctrl+Q : Goes to the last edited position
  • Ctrl+D : Deletes current line in the editor
  • Ctrl+Shift+O : Adjusts the imports statements in the current Java source file
  • Ctrl+2, L or F : Assign statement to new local variable or field
  • Ctrl+Shift+T : Open Type Dialog
  • Ctrl+F11 : Run last launched application
  • Shift+F10 : Opens context menu. Keyboard equivalent to Mouse2
  • Ctrl+F10 : Opens view menu for current view.
  • If you are using some more useful Eclipse keyboard shortcuts which are not included then please post as comments, I will include them in this list. Let me know if you face any issues while using these eclipse shortcuts in any particular version of Eclipse IDE.

    java.lang.Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. It’s also called as Object Class .

    Methods of Object Class

    Below are methods of Object Class for different purpose  as below:

  • protected Object clone() : Creates and return copy of this object.
  • boolean equals(Object obj) : Indicate weather other object is equal or not.
  • protected void finalize() : To make object finalize for garbage collection.
  • Class getClass() : Returns the runtime class of this Object.
  • int hashCode() : Returns a hash code value of Object.
  • void notify() : Wakes up a single thread that is waiting on this object’s monitor. It works in multithread env with tow thread only.
  • void notifyAll() : Wakes up all threads that are waiting on this object’s monitor. if more than one thread running.
  • String toString() : Returns string representation of object.
  • void wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  • void wait(long timeout) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or specified time has elapsed.
  • void wait(long timeout, int nanos) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
  • In this below examples you can see how to override and utilize these methods in different ways.

    Example of clone() method

    Object class clone() method, create and return copy of a object(). For implementing a clone method class have implements Cloneable interface which is a Marker Interface . There are two ways of cloning of object Shallow Cloning and Deep Cloning. For more detail follow below link.

    Java : Shallow and Deep Object Cloning

    Eample of finalize() method

    Garbage collector calls Object class finalize() method before clean object. We can override this method for code clean-up activity like closing files, database connection and socket. Follow below link to know more about finalize() method example and uses:

    Java : Garbage Collection finalize() method example and uses

    Example of hashCode(), equals() and toString() method

    Override toString() method to print object values. Same way we can override hash() code and equals() method also. hashcode and equals() method have contract as:

    “If two objects are equal according to the equals (Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals () and not hashCode () your class violates this contract

    For example of toString(), hashcode() and equals() follow below link:

    Java : How to remove duplicate objects from list?

    Example of getClass() method

    The getClass() method returns the run time class of an object.  As in below examples returning class name of objects.

    import java.util.Calendar; public class GetClassExample { public static void main(String[] args) { GetClassExample test=new GetClassExample(); System.out.println("Class Name :"+test.getClass().getName()); Calendar calendar=Calendar.getInstance(); System.out.println("Calendar Class Name :"+calendar.getClass().getName()); Integer integer=new Integer(10); System.out.println("Integer Class Name :"+integer.getClass().getName());

    Output

    Class Name :com.Object.GetClassExample Calendar Class Name :java.util.GregorianCalendar Integer Class Name :java.lang.Integer

    Example of wait(), notify() and notifyAll() method

    Below is example of restaurant using method wait(), notify() and notifyAll(). Where Two waiter thread are running and waiting for  order message when they got order notify will pass the order message and based on available waiter will process order.

    public class Order { private String msg; public Order(String msg){ this.msg=msg; public String getMsg() { return msg; public void setMsg(String str) { this.msg=str;

    Waiter class that will wait for other threads to invoke notify methods to complete it’s processing. Notice that Waiter thread is owning monitor on Order object using synchronized block.

    public class Waiter implements Runnable{ private Order msg; public Waiter(Order msg){ this.msg=msg; @Override public void run() { String name = Thread.currentThread().getName(); synchronized (msg) { System.out.println(name+" waiting to get notification at time:"+System.currentTimeMillis()); msg.wait(); }catch(InterruptedException e){ e.printStackTrace(); System.out.println(name+" waiter thread got notification at time:"+System.currentTimeMillis()); //process the order now System.out.println(name+" processed: "+msg.getMsg());

    Here notification thread will call notify() method on order message so that available waiter will pick the order.Notice that synchronized block is used to own the monitor of Order object.

    public class Notification implements Runnable { private Order msg; public Notification(Order msg) { this.msg = msg; @Override public void run() { String name = Thread.currentThread().getName(); System.out.println(name+" started"); try { Thread.sleep(1000); synchronized (msg) { msg.setMsg(name+" Notification work done"); msg.notify(); //use notify all when lots of thread are running // msg.notifyAll(); } catch (InterruptedException e) { e.printStackTrace();

    Below test class having multiple threads of Waiter and notification to execute order.

    public class WaitNotifyExample { public static void main(String[] args) { Order order= new Order("My Order"); Waiter waiter1 = new Waiter(order); new Thread(waiter1,"waiter 1").start(); Waiter waiter2 = new Waiter(order); new Thread(waiter2, "waiter 2").start(); Notification notification = new Notification(msg); new Thread(notification, "notification").start(); System.out.println("All the threads are started");

    When we will execute the above program, we will see below output but program will not complete because there are two waiter threads waiting for Order object and notify() method has wake up only one of them, the other waiter thread is still waiting to get notified.

    Output

    waiter 2 waiting to get notification at time:1552127934935 waiter 1 waiting to get notification at time:1552127934935 notification started All the threads are started waiter 2 waiter thread got notification at time:1552127935946 waiter 2 processed: notification Notification work done waiter 1 waiting to get notification at time:1552127972873 All the threads are started notification started waiter 2 waiting to get notification at time:1552127972873 waiter 1 waiter thread got notification at time:1552127973876 waiter 1 processed: notification Notification work done

    Conclusion

    Here you learn about the Object class and it’s methods. How to use these objects class methods with example and where can we use that.

    References

    https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

    In this below example list having duplicate object of AccountTransaction which need to remove from list. Here I am using HashSet because it always keep unique records. Now question comes how to decide uniqueness of object. As you know contract between hashcode() and equals() method deciding uniqueness and equality of object.

    Here used Comparable interface to sort values based on transaction date.

    hashcode() and equals() contract :

    “If two objects are equal according to the equals (Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals () and not hashCode () your class violates this contract.”

    Example

    import java.math.BigDecimal; import java.util.Date; public class AccountTransaction implements Comparable{ private Date date; String transactionType; private String reference; private BigDecimal amount; public AccountTransaction(Date date, String transactionType, String reference, BigDecimal amount) { super(); this.date = date; this.transactionType = transactionType; this.reference = reference; this.amount = amount; //Overriding toString() method to print object @Override public String toString() { return "AccountTransactions [date=" + date + ", transactionType=" + transactionType + ", reference=" + reference + ", amount=" + amount + "]"; //Overriding hashcode() and equals() method to check equality and uniqueness //of objects @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((amount == null) ? 0 : amount.hashCode()); result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((reference == null) ? 0 : reference.hashCode()); result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode()); return result; @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AccountTransaction other = (AccountTransaction) obj; if (amount == null) { if (other.amount != null) return false; } else if (!amount.equals(other.amount)) return false; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (reference == null) { if (other.reference != null) return false; } else if (!reference.equals(other.reference)) return false; if (transactionType == null) { if (other.transactionType != null) return false; } else if (!transactionType.equals(other.transactionType)) return false; return true; //Sort object by date @Override public int compareTo(AccountTransaction o) { return this.getDate().compareTo(o.getDate()); //use getter and setter of properties

    Here is the class having sample data which is having duplicate objects in list. calling removeDuplicate() method which is converting list to hashSet() to remove duplicate and then again converting to list then sorting by date.

    import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; public class RemoveDuplicateObjects { public static void main(String[] args) { List transactionList = new ArrayList(); try { transactionList.add(new AccountTransaction(getDate("2018-10-15 10:50 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:48 AM"), "Account Debits", "Burger king",new BigDecimal("0.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:55 AM"), "Account Debits", "Papa Johns",new BigDecimal("2.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Debits", "Pizza hut",new BigDecimal("1.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200"))); //Duplicate record transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56"))); transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200"))); System.out.println("Transactions before removing duplicate============="); for(AccountTransaction transaction:transactionList) System.out.println(transaction); System.out.println("Transactions after removing duplicate============="); transactionList=removeDuplicate(transactionList); for(AccountTransaction transaction:transactionList) System.out.println(transaction); } catch (Exception ex) { ex.printStackTrace(); private static List removeDuplicate(List transactionList) //Convert List to Set Set transactionSet=new HashSet(transactionList); //Convert Set to Array List transactionList=new ArrayList(transactionSet); //Sort object by transaction date and time Collections.sort(transactionList); return transactionList; private static Date getDate(String dateStr) throws ParseException { return new SimpleDateFormat("yyyy-MM-dd HH:mm a").parse(dateStr);

    Output

    Transactions before removing duplicate============= AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56] AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56] AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56] AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56] AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56] AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56] AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200] AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56] AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56] AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200] Transactions after removing duplicate============= AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200] AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56] AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56] AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56] AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56] AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56] AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]

    See Also:

  • Java : Sort Date Object and Text Format
  • Java : Comparable Vs Comparator
  • How to sort object by Comparator interface in ascending and descending order : JAVA
  • How to Sort By Comparable Interface in Ascending and Descending Order : Java
  • Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order
  • finalize() is an Object class method that is called by Garbage Collector just before deleting/destroying the object which is eligible for garbage collection before clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation.

    Points to Remember:

  • finalize() is a method not reserved keyword.
  • If finalize() method call manually by object instance then it will treat as normal method;
  • Once finalize() method completes immediately Garbage Collector destroy that object.
  • There is no guarantee about the time when finalizing () method is called. It may be called any time after the object is not being referred anywhere (can be garbage collected).
  • Syntax  of finalize() method:

    protected void finalize throws Throwable{}

    Since Object is the superclass of all the classes and finalize( ) is the Object class method hence finalize() method is available for every java class hence Garbage Collector can call finalize method on any java object. We also override this finalize() method for code clean-up activities.

    finalize() method Example

    In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

    public class FinalizeMethodTest { public static void main(String[] args) { FinalizeMethodTest test=new FinalizeMethodTest(); //manually calling finalize method is call like normal method test.finalize(); //unreferenced object to make eligible for garbage collector test=null; //Requesting JVM to call Garbage Collector method System.gc(); System.out.println("Main Method Completed !!"); @Override public void finalize() System.out.println("finalize method overriden");

    Output

    finalize method overriden Main Method Completed !! finalize method overriden

    Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

    Exception Handling in finalize() method

    If any exception happens in the finalize method then if we calling finalize manually then we have to handle it otherwise program will terminate abnormally. If finalize() method called by Garbage collector and then any unchecked exception happen then JVM will take care of it and the program will not terminate.

    public class FinalizeMethodTest { public static void main(String[] args) { FinalizeMethodTest test=new FinalizeMethodTest(); //manually calling finalize method is call like normal method test.finalize(); catch(Exception ex) ex.printStackTrace(); //unreferenced object to make eligible for garbage collector test=null; //Requesting JVM to call Garbage Collector method System.gc(); System.out.println("Main Method Completed !!"); @Override public void finalize() System.out.println("finalize method overriden"); //Exception occured here System.out.println(10 / 0); }<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

    Output

    finalize method overriden java.lang.ArithmeticException: / by zero at classes.ObjectClass.FinalizeMethodTest.finalize(FinalizeMethodTest.java:30) at classes.ObjectClass.FinalizeMethodTest.main(FinalizeMethodTest.java:10) Main Method Completed !! finalize method overriden

    In this example, we have to handle exception explicitly while calling finalize() method manually while calling by Garbage Collector no exception thrown.

    Conclusion

    In this blog, we learn about finalize() method calling manually and by Garbage Collector. Also, see by example to handle exception for both cases.

    Pr -requisite : Marker Interface in Java and Use , CloneNotSupportedException

    In object oriented programming object copy or copy of object are possible many ways like copy constructor or copy of object. Here we will focus on both the ways for copy of object.

  • Shallow Copy or Shallow Cloning
  • Deep Copy or Deep Cloning
  • See also : Java : Shallow Cloning Vs Deep Cloning

    Example of Shallow Cloning and Deep Cloning
    Java : Shallow Cloning and Deep Cloning

    Shallow Copy or Shallow Cloning

    Whenever we use default implementation of copy of object means it create new instance of object and copies all the fields to the object new fields and if fields are non primitive or reference type variable to copy to new fields as reference of that non-primitive fields.

    clone() method by default support shallow copy of object().  for implementing clone() method you have to implement Cloneable interface which is marker interface .

    Shallow copy example by constructor

    import java.util.Arrays; public class Courses { String[] courseArr; // Shallow copy by constructor because in copy taking reference of object public Courses(String[] courseArr) { super(); this.courseArr = courseArr; @Override public String toString() { return "Courses [courseArr=" + Arrays.toString(courseArr) + "]"; public static void main(String[] str) { String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" }; Courses courses = new Courses(courseArr); System.out.println(courses); courseArr[2] = "Computer";//while changing in passed object will reflect on copy of object System.out.println(courses);

    Output

    Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]] Courses [courseArr=[Math, Physics, Computer, Hindi, English]]

    Shallow copy by clone method

    In this example doing  shallow copy by clone method default way by implementing Cloneable interface and overriding clone() method which will by default make copy of object but here sub object course field in Student object will take reference of copied student object. It means if make any change on course object values will reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

    class Courses { String course1; String course2; String course3; public Courses(String course1, String course2, String course3) { this.course1 = course1; this.course2 = course2; this.course3 = course3; class Student implements Cloneable { int id; String name; Courses courses; public Student(int id, String name, Courses courses) { this.id = id; this.name = name; this.courses = courses; // Default version of clone() method. It creates shallow copy of an object. // CloneNotSuportedException is checked exception always need to handle that protected Object clone() throws CloneNotSupportedException { return super.clone(); public class ShallowCopyInJava { public static void main(String[] args) { Courses science = new Courses("Physics", "Chemistry", "Math"); Student student1 = new Student(1020, "Saurabh", science); Student student2 = null; try { // Creating a clone of student1 and assigning it to student2 student2 = (Student) student1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); // Printing the subject3 of 'student1' System.out.println(student1.courses.course3); // Output : Maths // Changing the course3 of 'student2' student2.courses.course3 = "Biology"; // This change will be reflected in original student 'student1' System.out.println(student1.courses.course3); // Output : Biology

    Output

    Biology

    Note: If class is having only primitive type values or Immutable object there is no difference between Shallow and Deep Cloning of object.

    Deep Copy or Deep Cloning

    Whenever we need own copy not to use default implementation (shallow copy or shallow cloning) of object. Always implement according to our need and make sure all the member of  class also having deep copied of fields.

    If using cloneable interface and overriding clone() method of object class make sure member objects /reference objects also having deep copy of fields.

    Deep copy example by constructor

    import java.util.Arrays; public class Courses { String[] courseArr; // Deep copy object because copy actual fields value not references public Courses(String[] courseArr) { super(); if (courseArr != null) { this.courseArr = new String[courseArr.length]; for (int i = 0; i &lt;courseArr.length; i++) { this.courseArr[i] = courseArr[i]; @Override public String toString() { return "Courses [courseArr=" + Arrays.toString(courseArr) + "]"; public static void main(String[] str) { String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" }; Courses courses = new Courses(courseArr); System.out.println(courses); courseArr[2] = "Computer";// while changing in passed object will reflect on copy of object System.out.println(courses);

    Output

    Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]] Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]

    Deep copy by clone method
    In this example doing  deep copy by clone method but handle copying each individual reference object copy separately as in Student class clone() method. It means if make any change on course object values will not reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

    class Courses implements Cloneable{ String course1; String course2; String course3; public Courses(String course1, String course2, String course3) { this.course1 = course1; this.course2 = course2; this.course3 = course3; protected Object clone() throws CloneNotSupportedException return super.clone(); class Student implements Cloneable int id; String name; Courses courses; public Student(int id, String name, Courses courses) this.id = id; this.name = name; this.courses = courses; //Overriding clone() method to create a deep copy of an object. //CloneNotSuportedException is checked exception always need to handle that protected Object clone() throws CloneNotSupportedException Student student = (Student) super.clone(); student.courses = (Courses) courses.clone(); return student; public class DeepCopyInJava public static void main(String[] args) Courses science = new Courses("Physics", "Chemistry", "Math"); Student student1 = new Student(1020, "Saurabh", science); Student student2 = null; //Creating a clone of student1 and assigning it to student2 student2 = (Student) student1.clone(); catch (CloneNotSupportedException e) e.printStackTrace(); //Printing the subject3 of 'student1' System.out.println(student1.courses.course3); //Output : Math //Changing the subject3 of 'student2' student2.courses.course3 = "Biology"; //This change will not be reflected in original student 'student1' System.out.println(student1.courses.course3); //Output : Math

    Output

    Conclusion

    Here you learn about Shallow and Deep copy  of object by constructor and implementing by clone() method of Cloneable Interface which is marker interface.

  • Learn Shallow and Deep Cloning
  • Below are  the list of differences between shallow cloning and deep cloning in java.

    Example of Shallow Cloning and Deep Cloning
    Java : Shallow Cloning and Deep Cloning

    Shallow Cloning

  • Cloned Object and original object are not 100% disjoint.
  • Any changes made to cloned object will be reflected in original object or vice versa.
  • Default version of clone method creates the shallow copy of an object.
  • Shallow copy is preferred if an object has only primitive fields.
  • Shallow copy is fast and also less expensive.
  • Example: Shallow Cloning Example

    Deep Cloning

  • Cloned Object and original object are 100% disjoint.
  • Any changes made to cloned object will not be reflected in original object or vice versa.
  • To create the deep copy of an object, you have to override clone method.
  • Deep copy is preferred if an object has references to other objects as fields.
  • Deep copy is slow and very expensive.
  • Example: Deep Cloning Example

    What is a Mutable/Immutable Class?

    A class is called an immutable class once the object is created, we can not change it’s field/objects values. If values are changeable then it’s a mutable class.

    Designing Rule

    Classes should be immutable unless there’s a very good reason to make them mutable…
    If a class cannot be made immutable, limit its mutability as much as possible.

    In java all the wrapper classes and String class is immutable. For Ex: immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double, etc.

    How to make a class Immutable Class?

    Below are step by step guide to making a class Immutable:

    Step 1: Don’t provide “setter” methods that modify fields or objects referred to by fields.
    Step 2: Make all fields final and private.
    Step 3: Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
    Step 4: If the instance fields include references to mutable objects, don’t allow those objects to be changed: Don’t provide methods that modify the mutable objects.
    Step 5: Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor.
    If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

    What are the Benefits of Immutable Object?

  • Immutable objects are thread-safe so you will not have any synchronization issues.
  • Immutable objects are good Map keys and Set elements since these typically do not change once created.
  • Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  • Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  • An immutable object’s internal state of your program will be consistent even if you have exceptions.
  • References to immutable objects can be cached as they are not going to change.
  • How to create Immutable Lists, Sets or Maps?

    JAVA 8 added the “unmodifiable” method and JAVA 9 added “of” factory method to make collections like lists, sets, and maps as immutable.  for example :

    JAVA 8

    Unmodifiable List List stringList = Arrays.asList("Facing", "Issues", "On", "IT"); stringList = Collections.unmodifiableList(stringList); Unmodifiable Set Set stringSet = new HashSet<>(Arrays.asList("Facing", "Issues", "On", "IT")); stringSet = Collections.unmodifiableSet(stringSet); Unmodifiable Map Map<String,Integer> stringMap = new HashMap<String, Integer>(); stringMap.put("Facing",1); stringMap.put("Issues",2); stringMap.put("On",3); stringMap.put("IT",4); stringMap = Collections.unmodifiableMap(stringMap);

    JAVA 9

    Unmodifiable List List stringList = List.of("Facing", "Issues", "On", "IT"); Unmodifiable Set Set stringSet = Set.of("Facing", "Issues", "On", "IT"); Unmodifiable Map Map stringMap = Map.of("Facing",1, "Issues",2, "On",3, "IT",4);

    Immutable Class Example

    //make class final so that method not override public final class ImmutableClass { final String pancardNumber; final String aadharNumber; final DOB dob; // Create object public ImmutableClass(String pancardNumber, String aadharNumber, DOB dob) { this.pancardNumber = pancardNumber; this.aadharNumber = aadharNumber; this.dob = dob; //No setter method so that no fields get modifiable public String getPancardNumber() { return pancardNumber; public String getAadharNumber() { return aadharNumber; @Override public String toString() { return "ImmutableClass [pancardNumber=" + pancardNumber + ", aadharNumber=" + aadharNumber + ", dob=" + dob + "]"; public class DOB { private int day; private int month; private int year; public DOB(int day, int month, int year) this.day=day; this.month=month; this.year=year; public int getDay() { return day; public int getMonth() { return month; public int getYear() { return year; @Override public String toString() { return "DOB [day=" + day + ", month=" + month + ", year=" + year + "]"; public class ImmuTableClassTest { public static void main(String[] args) { DOB dob = new DOB(24, 04, 1992); ImmutableClass immutableClass = new ImmutableClass("ABCD12345", "1234567890123456", dob); System.out.println(immutableClass);

    Output

    ImmutableClass [pancardNumber=ABCD12345, aadharNumber=1234567890123456, dob=DOB [day=24, month=4, year=1992]]

    Conclusion

    In this blog you understand below points:

  • What is mutable and Immutable classes?
  • How make a class Immutable?
  • How to make collections like Lists, Sets, and maps  immutable by Java 8 and Java 9?
  • Immutable class example.
  • References

    https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm

    Pre-Requisite: Java: Exception Handling Tutorial

    Java 7 improved multi catch to handle in single block so that reduce the number of lines of code. Here we will discuss about the rules  to handle multi catch block and difference while implementing multi catch with Java 7+.

    Multi Catch Rules

    Java Catch Exception Rules
    5 Rules for Catching Exceptions in Java (7+)

    Here you will know all above multiple catch block rules in details:

    Rule 1 : One try block can associated with multiple catch blocks.

    As per exception handling one try block safe guard can associated with multiple catch block to handle different type of exception depend on code statement on try block. Like below handling ArithmeticException and NumberFormatException in different catch blocks. You can see complete example in end of this blog.

    //some code here catch (ArithmeticException ex) System.out.println("Arithmetic " + ex); catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex);

    Rule 2 : If the exceptions have parent-child relationship, the catch blocks must be sorted by the most specific exceptions first, then by the most general ones.

    In this below example FileNotFoundException is sub class of IOException thats what most specific exception FileNotFoundException will always come before IOException.

    try { File file = new File("ABC.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) System.out.println(st); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace();

    Rule 3 : If the exceptions are not in the same inheritance tree, i.e. they don’t have parent-child relationship, the catch blocks can be sorted any order.

    As exception handling blocks ArithmeticException and NumberFormatException i are not having any relation like parent and child , so order sequence of these two exceptions doesn’t matter. Like in rule 1 we use as order ArithmeticException and NumberFormatException while in this rule using order as NumberFormatException and ArithmeticException .

    //some code here catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex); catch (ArithmeticException ex) System.out.println("Arithmetic " + ex);

    Rule 4 : If we catch the most general exception first, then we also catch other exceptions which are sub-types of the general exception.

    If we are using generic Exception or RuntimeException to handle all type of exception this catch block should always be in last. otherwise compiler will throw exception as  “ Unreachable catch block for ArithmeticException

    Wrong way

    Right Way

    //some code here catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex); catch (Exception ex) //To handle all othertype exception exception NumberFormatException<span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span> System.out.println("Exception" + ex);

    Rule 5 : In java 7 multiple exceptions can be handle throw single block when need to print or throw some generic exception.

    Since Java 7,  we can combine multiple  exceptions in single catch clause by pipe (|) symbol. Below code is equivalent to code as above in legacy way.

    //some code here catch (ArithmeticException|NumberFormatException ex) System.out.println("Exception Encountered " + ex);

    While applying above Java 7+ multi catch .We have to follow below rules:

  • Rule 1: Multi catch is for exceptions with different hierarchy.
  • Rule 2: Can not re-assign value to catch parameter in multi-catch.
  • Rule 3: In Java 7, Exception will not handle all exception.
  • Below are running example with legacy way of multi catch and Java 7+.

    Multi cath block example

    import java.util.Scanner; public class MultiCatchTest { * In the following code, we have to handle two different exceptions but take same action for both. So we needed to have two different catch blocks as of Java 6.0. * @param args public static void main(String[] args) { System.out.println("Please enter a integer value :"); Scanner scn = new Scanner(System.in); int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); catch (ArithmeticException ex) System.out.println("Arithmetic " + ex); catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex);

    Output

    Please enter a integer value : Arithmetic java.lang.ArithmeticException: / by zero Please enter a integer value : Number Format Exception java.lang.NumberFormatException: For input string: "3.5"

    Multi catch block example with (Java 7 +)

    import java.util.Scanner; public class MultiCatchTest7 { public static void main(String[] args) { //After JAVA 7 * single catch block to catch multiple exceptions by separating each with | (pipe symbol) in catch block. System.out.println("Please enter a integer value :"); Scanner scn = new Scanner(System.in); int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); catch (ArithmeticException|NumberFormatException ex) System.out.println("Exception Encountered " + ex);

    Output

    Please enter a integer value : Exception Encountered java.lang.ArithmeticException: / by zero Please enter a integer value : Exception Encountered java.lang.NumberFormatException: For input string: "3.5"

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • [Solved] javax.portlet.PortletException: Error occured during request processing: INSTANCE

    Leave a comment

    This exception happened with web application or using rest services with Spring. In my case it was occurred with rest services using with Spring. It was because of conflict between old and new version of httpclient.jar and httpcore.jar. I was using latest version in my pom.xml while due to other jar dependency while deploy application added others older version jar.

    javax.portlet.PortletException: Error occured during request processing: INSTANCE at org.springframework.web.portlet.DispatcherPortlet.doRenderService(DispatcherPortlet.java:805) at org.springframework.web.portlet.FrameworkPortlet.processRequest(FrameworkPortlet.java:536) at org.springframework.web.portlet.FrameworkPortlet.doDispatch(FrameworkPortlet.java:483) at javax.portlet.GenericPortlet.render(GenericPortlet.java:233) at com.liferay.portlet.FilterChainImpl.doFilter(FilterChainImpl.java:100) at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:64) at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:111) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilterChain.doFilter(InvokerFilterChain.java:72) at com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter.doFilter(InvokerFilter.java:73) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)

    Solution

    I resolved this issue after reaching to lib folder of my web application deployment location:

    Steps 1: Removed older version jars for httpclient and httpcore from lib directory.

    Step 2: Restart the server.

    INstance not found issue
    Solution for javax.portlet.PortletException: Error occured during request processing: INSTANCE

    My issue was resolved after following above two steps.

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • File writing by BufferedWriter

    BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File.

    It gives better performance when write operations are more because when more write operations then less IO operations.

    String str = "Facing"; BufferedWriter writer = new BufferedWriter(new FileWriter(FILE)); writer.write(str); writer.close();

    when need to append more lines in file use File writer parameter with true to append more lines.

    BufferedWriter writer = new BufferedWriter(new FileWriter(FILE, true)); writer.append(' '); writer.append('Issues'); writer.append(' '); writer.append('On'); writer.append(' '); writer.append('IT'); writer.close();

    File writing by FileWriter

    FileWriter is the simplest way to write a file in java. FileWriter writes directly into Files and should be used only when number of writes are less. It also provides overloaded write method to write int, byte array and String to the File.

    File file = new File(FILE); FileWriter fr = null; try { fr = new FileWriter(file); fr.write("Facing Issues On IT"); } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); } catch (IOException e) { e.printStackTrace();

    File Writing by FileOutputStream

    FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.

    OutputStream os = null; String data="FacingIssuesOnIt"; try { os = new FileOutputStream(new File(FILE)); os.write(data.getBytes(), 0, data.length()); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace();

    File Writing by Files

    Java 7 introduced Files utility class and we can write a file using it’s write function, internally it’s using OutputStream to write byte array into file.

    String data="FacingIssuesOnIt"; try { Files.write(Paths.get(FILE), data.getBytes()); } catch (IOException e) { e.printStackTrace();

    File Writing by Channel

    RandomAccessFile stream = new RandomAccessFile(FILE, "rw"); FileChannel channel = stream.getChannel(); String value = "FacingIssuesOnIT"; byte[] strBytes = value.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length); buffer.put(strBytes); buffer.flip(); channel.write(buffer); stream.close(); channel.close();

    File Writing on specific position

    public void writeFileOnParticularPosition() throws IOException { int data = 2018; int position = 5; RandomAccessFile writer = new RandomAccessFile(FILE, "rw"); writer.seek(position); writer.writeInt(dataPos1); writer.close();

    File Writing to when Locked

    RandomAccessFile stream = new RandomAccessFile(FILE, "rw"); FileChannel channel = stream.getChannel(); FileLock lock = null; try { lock = channel.tryLock(); } catch (final OverlappingFileLockException e) { stream.close(); channel.close(); stream.writeChars("FacingIssuesOnIT"); lock.release(); stream.close(); channel.close();

    File Writing to Temporary File

    String toWrite = "FacingIssuesOnIT"; File tmpFile = File.createTempFile("test", ".tmp"); FileWriter writer = new FileWriter(tmpFile); writer.write(toWrite); writer.close();

    Complete Example

    In this example covered all the ways (BufferedWriter, FileWriter, FileOutputStream and Files) of file writing.

    import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Paths; public class FileWritingWay { private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java"; * Here in this class you will see different ways to write in file by java * @param args * @throws IOException public static void main(String[] args) { try { System.out.println("===========Java Write File using FIleWriter============"); writeFileUsingFileWriter(); System.out.println("===========Java Write File using BufferedWriter============"); writeFileUsingBufferedWriter(); System.out.println("===========Java Write File using FileOutputStream============"); writeUsingOutputStream(); System.out.println("===========Java 7 Write File using Files and Paths============"); writeUsingFiles(); System.out.println("===========Java 7 Write File using Files and Paths============"); WriteToFileWhenLocked(); System.out.println("===========Write on temporary File============"); writeToTemporaryFile(); System.out.println("===========Write File using FileChannel============"); writeFileByFileChannel(); System.out .println("===========Write File using RandomAccessFile to write in specific position============"); writeFileOnParticularPosition(); System.out.println("===========Write File using DataOutputStream============"); writeFileusingDataoutputStream(); } catch (IOException ex) { ex.printStackTrace(); * Use file writer when number of write operations are less * @param data private static void writeFileUsingFileWriter() { File file = new File(FILE); FileWriter fr = null; try { fr = new FileWriter(file); fr.write("facingIssuesOnIT"); } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); } catch (IOException e) { e.printStackTrace(); * Use BufferedWriter when number of write operations are more It uses * internal buffer to reduce real IO operations and saves time * @param data * @param noOfLines private static void writeFileUsingBufferedWriter() { try { String str = "Facing"; BufferedWriter writer = new BufferedWriter(new FileWriter(FILE)); writer.write(str); writer.close(); } catch (IOException ex) { ex.printStackTrace(); // when need to append more lines in file use FileWrite with true as // below try { String str = "Facing"; BufferedWriter writer = new BufferedWriter(new FileWriter(FILE, true)); writer.append(' '); writer.append("Issues"); writer.append(' '); writer.append("On"); writer.append(' '); writer.append("IT"); writer.close(); } catch (IOException ex) { ex.printStackTrace(); * Use Streams when you are dealing with raw data * @param data private static void writeUsingOutputStream() { OutputStream os = null; String data = "FacingissuesonIT"; try { os = new FileOutputStream(new File(FILE)); os.write(data.getBytes(), 0, data.length()); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); * Use Files class from Java 1.7 to write files, internally uses * OutputStream * @param data private static void writeUsingFiles() { String data = "facingIssuesOnIT"; try { Files.write(Paths.get(FILE), data.getBytes()); } catch (IOException e) { e.printStackTrace(); public void writeUsingPrintWiter() throws IOException { FileWriter fileWriter = new FileWriter(FILE); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print("FacingIssuesOnIT"); printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000); printWriter.close(); public static void writeFileusingDataoutputStream() throws IOException { String value = "facingIssuesOnIT"; FileOutputStream fos = new FileOutputStream(FILE); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos)); outStream.writeUTF(value); outStream.close(); public static void writeFileOnParticularPosition() throws IOException { int data = 2018; int position = 5; RandomAccessFile writer = new RandomAccessFile(FILE, "rw"); writer.seek(position); writer.writeInt(data); writer.close(); public static void writeFileByFileChannel() throws IOException { RandomAccessFile stream = new RandomAccessFile(FILE, "rw"); FileChannel channel = stream.getChannel(); String value = "FacingIssuesOnIT"; byte[] strBytes = value.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length); buffer.put(strBytes); buffer.flip(); channel.write(buffer); stream.close(); channel.close(); public static void writeToTemporaryFile() throws IOException { String toWrite = "FacingIssuesOnIT"; File tmpFile = File.createTempFile("test", ".tmp"); FileWriter writer = new FileWriter(tmpFile); writer.write(toWrite); writer.close(); public static void WriteToFileWhenLocked() throws IOException { RandomAccessFile stream = new RandomAccessFile(FILE, "rw"); FileChannel channel = stream.getChannel(); FileLock lock = null; try { lock = channel.tryLock(); } catch (final OverlappingFileLockException e) { stream.close(); channel.close(); stream.writeChars("FacingIssuesOnIT"); lock.release(); stream.close(); channel.close();

    References

  • https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
  • https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
  • https://docs.oracle.com/javase/8/docs/api/?java/io/FileOutputStream.html
  • https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
  • https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html
  • https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
  • https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileLock.html
  • https://docs.oracle.com/javase/7/docs/api/java/io/File.html
  • Scanner
  • Stream/Files (java 8): Read all file lines
  • Paths (Java 8) : Read text file as String
  • Every way have something different as BufferedReader provides buffering of data for fast reading and Scanner provides parsing ability while we can use both BufferedReader and Scanner to read a text file line by line in Java.

    Java 8 introduced Stream class java.util.stream which provides a lazy and more efficient way to read a file.

    File Reading By BufferedReader

    This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

    In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders . For example,

    BufferedReader in = new BufferedReader(Reader in, int size); try { File file = new File(FILE); BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) System.out.println(st); } catch (IOException ex) { ex.printStackTrace();

    Note : In below code examples not follow usual practices of writing good code like flushing/closing streams, Exception-Handling etc, to reduce number of lines code for better understanding.

    File Reading By FileReader

    FileReader is convenient class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.

    Constructors defined in this class are: FileReader(File file) : Creates a new FileReader, given the File to read from. FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from. FileReader(String fileName): Creates a new FileReader, given the name of the file to read from. try { FileReader fr = new FileReader(FILE); int i; while ((i = fr.read()) != -1) System.out.print((char) i); } catch (IOException ex) { ex.printStackTrace();

    File Reading By Scanner

    A scanner can parse primitive types and strings using regular expressions and breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

    try { File file = new File(FILE); Scanner sc = new Scanner(file); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } catch (Exception ex) { ex.printStackTrace();

    Read file by scanner without loop

    File file = new File(FILE); try { Scanner sc = new Scanner(file); // Use delimiter \Z for next line sc.useDelimiter("\Z"); System.out.println(sc.next()); } catch (Exception ex) { ex.printStackTrace();

    File Reading By Stream (Java8)

    Files.readAllLines() method read all lines from a file and ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
    Bytes from the file are decoded into characters using the specified charset.

    public static List readAllLines(Path path,Charset cs)throws IOException This method recognizes the following as line terminators: CARRIAGE RETURN followed by LINE FEED (u000D followed by u000A) u000A, LINE FEED u000D, CARRIAGE RETURN List&amp;amp;lt;String&amp;amp;gt; lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8); Iterator&amp;amp;lt;String&amp;amp;gt; itr = lines.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } catch (IOException e) { e.printStackTrace();

    File Reading By Paths (Java8)

    try { String data = new String(Files.readAllBytes(Paths.get(FILE))); System.out.println(data); } catch (Exception ex) { ex.printStackTrace();

    Complete Example

    In below example  covered all the above cases.

    Test Data

    Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida package com.file; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class FileReadingWay { private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java"; public static void main(String[] args) { FileReadingWay s = new FileReadingWay(); System.out.println("===============Read File By Buffered Reader================"); s.readFileByBufferedReader(); System.out.println("===============Read File By File Reader================"); s.readFileByFileReader(); System.out.println("===============Read File By Scanner================"); s.readFileByScanner(); System.out.println("===============Read File By Scanner without Loop================"); s.readFileByScannerWithOutLoop(); System.out.println("===============Read All Files================"); s.readFileByReadAllFiles(); System.out.println("===============Read Text File and String================"); s.readTextFileAsString(); private void readFileByBufferedReader() { try { File file = new File(FILE); BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) System.out.println(st); } catch (IOException ex) { ex.printStackTrace(); private void readFileByFileReader() { System.out.println(); try { FileReader fr = new FileReader(FILE); int i; while ((i = fr.read()) != -1) System.out.print((char) i); } catch (IOException ex) { ex.printStackTrace(); System.out.println(); private void readFileByScanner() { try { File file = new File(FILE); Scanner sc = new Scanner(file); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } catch (Exception ex) { ex.printStackTrace(); private void readFileByScannerWithOutLoop() { File file = new File(FILE); try { Scanner sc = new Scanner(file); // Use delimiter \Z for next line sc.useDelimiter("\Z"); System.out.println(sc.next()); } catch (Exception ex) { ex.printStackTrace(); private void readFileByReadAllFiles() { List&amp;amp;lt;String&amp;amp;gt; lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8); Iterator&amp;amp;lt;String&amp;amp;gt; itr = lines.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } catch (IOException e) { e.printStackTrace(); private void readTextFileAsString() { try { String data = new String(Files.readAllBytes(Paths.get(FILE))); System.out.println(data); } catch (Exception ex) { ex.printStackTrace();

    Output

    ===============Read File By Buffered Reader================ Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida ===============Read File By File Reader================ Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida ===============Read File By Scanner================ Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida ===============Read File By Scanner without Loop================ Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida ===============Read All Files================ Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida ===============Read Text File and String================ Index Name Age Gender Employment Address 1 Saurabh 36 M Private Sector-120 Noida 2 Gaurav 34 M Business Sector-14 Gurgaon 3 Bharti 30 M Government Sector-120 Noida

    References

  • https://docs.oracle.com/javase/7/docs/api/java/io/package-summary.html
  • http://docs.oracle.com/javase/tutorial/essential/io/
  • Java , Java Issues & Solutions

    [Solved]java.util.UnknownFormatConversionException: Conversion = ‘I’

    Leave a comment

    java.util.UnknownFormatConversionException is runtime unchecked exception which throw when an unknown conversion is given. Unless otherwise specified, passing a null argument to any method or constructor in this class will cause a NullPointerException to be thrown.

  • UnknownFormatConversionException is sub class of IllegalFormatException .
  • Constructors

  • UnknownFormatConversionException(String s) : Constructs an instance of this class with the unknown conversion.
  • Example of UnknownFormatConversionException

    In this below example by mistake use “Index” with specifiers sign (%) where considering ‘I’ as specifiers which is not match with predefined specifiers that’s what throwing this exception.

    Scanner sc = new Scanner(new File("C:\Users\saurabh.gupta1\Desktop\testdata.txt")); int i=0; while (sc.hasNextLine()) { //System.out.println(sc.nextLine()); Scanner lineScanner = new Scanner(sc.nextLine()); lineScanner.useDelimiter("|"); if(i==0) System.out.format("%-10Index%-10s%-10s%-10s%-10sn", sc.next(),sc.next(),sc.next(),sc.next(),sc.next()); System.out.format("%-10d%-10s%-10s%-10s%-10sn", i,sc.next(),sc.next(),sc.next(),sc.next(),sc.next()); catch(Exception ex) ex.printStackTrace();

    Output

    java.util.UnknownFormatConversionException: Conversion = 'I' at java.util.Formatter$FormatSpecifier.conversion(Unknown Source) at java.util.Formatter$FormatSpecifier.&amp;lt;init&amp;gt;(Unknown Source) at java.util.Formatter.parse(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.io.PrintStream.format(Unknown Source) at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:45)

    Solution

    Always follow formatting specifiers rules as given in Java formatter.

    https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html

    References

    https://docs.oracle.com/javase/8/docs/api/java/util/UnknownFormatConversionException.html

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • import java.util.Scanner; public class JavaScannerParsingExample { public static void main(String[] args) { String input = "Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh"; Scanner s = new Scanner(input).useDelimiter("\s*Gaurav\s*"); System.out.println(s.next()); System.out.println(s.next()); System.out.println(s.next()); System.out.println(s.next()); System.out.println(s.nextInt()); System.out.println(s.nextInt()); s.close();

    Output

    Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:11)

    java.util.InputMismatchException which throw by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

  • InputMismatchException is runtime unchecked exception.
  • InputMismatchException is sub class of NoSuchElementException .
  • Constructors

  • InputMismatchException() : Constructs an InputMismatchException with null as its error message string.
  • InputMismatchException(String s): Constructs an InputMismatchException , saving a reference to the error message string s for later retrieval by the getMessage method.
  • Example

    In below example create this java.util.InputMismatchException by passing some others type values other than expectation. For Example : age expected as integer value from console while passing as decimal value.

    import java.util.Scanner; public class JavaScannerExample { public static void main(String[] args) { // Create a Scanner object Scanner scanner = new Scanner(System.in); //User different type of input from console System.out.println("Please enter user name:"); String userName = scanner.nextLine(); System.out.println("Please enter age:"); int age = scanner.nextInt(); System.out.println("Please enter salary:"); double salary = scanner.nextDouble(); //Output input by user System.out.println("User Name: " + userName); System.out.println("Age: " + age); System.out.println("Salary: " + salary); catch(Exception ex) System.err.println("Entered user input are not match with required type:"); ex.printStackTrace(); Please enter user name: Saurabh Gupta Please enter age: Entered user input are not match with required type: java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at com.userinput.JavaScannerExample.main(JavaScannerExample.java:28)

    Solution

  • In such type scenarios where user interaction required always write code and ask input as scanner.nextLine();
  • Always validate values type before assign to variable.
  • If any mismatch found and throw above exception show message to insert value again as required format.
  • References

    https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • java.lang.IllegalArgumentException is runtime unchecked exception. IllegalArgumentException throw as a preconditions check to indicate that a method has been passed an illegal or inappropriate argument.

    IllegalArgumentException occurred generally in two cases:

  • IllegalArgumentException on preconditions check
  • IllegalArgumentException on chained exception
  • Constructors

  • IllegalArgumentException() : Constructs an IllegalArgumentException with no detail message.
  • IllegalArgumentException(String s) : Constructs an IllegalArgumentException with the specified detail message.
  • IllegalArgumentException(String message, Throwable cause) : Constructs a new exception with the specified detail message and cause.
  • IllegalArgumentException(Throwable cause) : Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
  • Example: IllegalArgumentException preconditions check

    In below example validating percentage and email based on basic criteria and throwing generic message as “Bad Percentage” and “Invalid Email Address”.

    public class IllegalArgumentExceptionExample { public static void main(String[] args) { validatePercentage(50); //valid percentage validatePercentage(-20);//invalida percentage catch(Exception ex) ex.printStackTrace(); validateEmail("[email protected]"); //valid email validateEmail("facingissuesonit-gmail.com");//invalid email catch(Exception ex) ex.printStackTrace(); public static void validatePercentage(int pct) { if( pct < 0 || pct > 100) { throw new IllegalArgumentException("Bad Percent"); public static void validateEmail(String email) if (!email.contains("@")) { throw new IllegalArgumentException("Invalid Email Address");

    Output

    java.lang.IllegalArgumentException: Bad Percent at com.exceptions.IllegalArgumentExceptionExample.validatePercentage(IllegalArgumentExceptionExample.java:44) at com.exceptions.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:23) java.lang.IllegalArgumentException: Invalid Email Address at com.exceptions.IllegalArgumentExceptionExample.validateEmail(IllegalArgumentExceptionExample.java:51) at com.exceptions.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:33)

    Example: IllegalArgumentException chained exception

    In below example , consider a situation in which a method throws an IllegalArgumentException with message “passing Argument is not valid” but the actual cause of exception was an ArithmeticException because of an attempt to divide by zero The method will throw only IllegalArgumentException to the caller. So the caller would not come to know about the actual cause of exception and will see only generic message.

    public class ChainedExceptionExample { public static void main(String[] args) { try { int totalAge = 500; int numberOfPerson = 0; int averageAge = averageAge(totalAge, numberOfPerson); System.out.println("Average Age :" + averageAge); } catch (Exception ex) { System.out.println(ex); ex.printStackTrace(); public static int averageAge(int totalAge, int numberOfPerson) { int avarageAge; try { * ArithmaticException can happen here because of value value * NumberOfPerson as 0 avarageAge = totalAge / numberOfPerson; } catch (Exception ex) { System.out.println(ex); // Actual Exception * Exception Chaining here by relating this ArithmaticException to * IllegalArgumentException throw new IllegalArgumentException("Passing argument is not valid", ex.getCause()); return avarageAge;

    Output

    java.lang.ArithmeticException: / by zero java.lang.IllegalArgumentException: Passing argument is not valid java.lang.IllegalArgumentException: Passing argument is not valid at com.customexceptions.ChainedExceptionExample.averageAge(ChainedExceptionExample.java:33) at com.customexceptions.ChainedExceptionExample.main(ChainedExceptionExample.java:10)

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • Java throws Keyword
  • Chained Exception allows to relate one exception with another exception, i.e one exception describes cause of another exception. Chained Exception is used in such type of situations.

    In below example , consider a situation in which a method throws an IllegalArgumentException with message “passing Argument is not valid” but the actual cause of exception was an ArithmeticException because of an attempt to divide by zero The method will throw only IllegalArgumentException to the caller. So the caller would not come to know about the actual cause of exception and will see only generic message.

    Constructors Of Throwable class

  • Throwable(Throwable cause) : Where cause is the exception that causes the current exception.
  • Throwable(String message, Throwable cause) : Where message is the exception message and cause is the exception that causes the current exception.
  • Methods Of Throwable class

  • getCause() method: This method returns actual cause of an exception.
  • initCause(Throwable cause) method: This method sets the cause for the calling exception.
  • Example of using Chained Exception

    public class ChainedExceptionExample { public static void main(String[] args) { try { int totalAge = 500; int numberOfPerson = 0; int averageAge = averageAge(totalAge, numberOfPerson); System.out.println("Average Age :" + averageAge); } catch (Exception ex) { System.out.println(ex); ex.printStackTrace(); public static int averageAge(int totalAge, int numberOfPerson) { int avarageAge; try { * ArithmaticException can happen here because of value value * NumberOfPerson as 0 avarageAge = totalAge / numberOfPerson; } catch (Exception ex) { System.out.println(ex); // Actual Exception * Exception Chaining here by relating this ArithmaticException to * IllegalArgumentException throw new IllegalArgumentException("Passing argument is not valid", ex.getCause()); return avarageAge;

    Output

    java.lang.ArithmeticException: / by zero java.lang.IllegalArgumentException: Passing argument is not valid java.lang.IllegalArgumentException: Passing argument is not valid at com.customexceptions.ChainedExceptionExample.testMethod1(ChainedExceptionExample.java:23) at com.customexceptions.ChainedExceptionExample.main(ChainedExceptionExample.java:9)

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • Java throws Keyword
  • Exception Propagation : When an exception happens, propagation is the process where exception is dropped from top to bottom of stack until not caught by catch block or if no any catch block to handle it throw to JVM .

    Ways to handle Exception Propagation in checked and unchecked exception are different.

  • Exception Propagation in Unchecked Exceptions
  • Exception Propagation in Checked Exceptions ( throws )
  • Exception Propagation in Unchecked Exceptions

    When a unchecked exception happens, Exception being dropped from to the top to the
    bottom of the stack. If not caught once, the exception again drops down to the previous method and so on until it gets caught or until it reach the very bottom of the call stack. This is called exception propagation.

    Note : By default, Unchecked Exceptions are forwarded in calling chain ( propagated ).

    In the example below, exception occurs in method3() where it is not handled, so it is propagated to previous method2() where it is not handled, again it is propagated to method1() where exception is handled.
    Exception can be handled in any method in call stack either in main() method, method1(), method2() or method3() .

    public class UncheckedExceptionPropagation { public static void main(String[] args) { method1(); System.out.println("Flow Completed.."); public static void method1() method2();//Exception propagation to method1 catch(Exception ex) ex.printStackTrace(); System.out.println("Exception Handled Here.."); public static void method2() method3();//Exception propagation to method2 public static void method3() int x=100/0;//ArithmeticException happen here

    Output

    java.lang.ArithmeticException: / by zero Exception Handled Here.. at com.customexceptions.UncheckedExceptionPropagation.method3(UncheckedExceptionPropagation.java:29) at com.customexceptions.UncheckedExceptionPropagation.method2(UncheckedExceptionPropagation.java:25) at com.customexceptions.UncheckedExceptionPropagation.method1(UncheckedExceptionPropagation.java:15) at com.customexceptions.UncheckedExceptionPropagation.main(UncheckedExceptionPropagation.java:7) Flow Completed..

    Exception Propagation in Checked Exceptions

    When a checked exception happens, the propagation of exception does not happen and its mandatory to use throws keyword here. Only unchecked exceptions are propagated. Checked exceptions throw compilation error.

    In example below, If we omit the throws keyword from the method3() and method2() functions, the compiler will generate compile time error. Because unlike in the case of unchecked exceptions, the checked exceptions cannot propagate without using throws keyword.

    Note : By default, Checked Exceptions are not forwarded in calling chain ( propagated ).

    import java.io.IOException; public class CheckedExceptionPropagation { public static void main(String[] args) { method1(); System.out.println("Flow Completed.."); public static void method1() method2();//Exception propagation to method1 catch(Exception ex) ex.printStackTrace(); System.out.println("Exception Handled Here.."); public static void method2() throws IOException method3();//Exception propagation to method2 public static void method3() throws IOException throw new IOException("Propagation Exception test");

    Output

    java.io.IOException: Propagation Exception test at com.customexceptions.CheckedExceptionPropagation.method3(CheckedExceptionPropagation.java:31) at com.customexceptions.CheckedExceptionPropagation.method2(CheckedExceptionPropagation.java:27) at com.customexceptions.CheckedExceptionPropagation.method1(CheckedExceptionPropagation.java:17) at com.customexceptions.CheckedExceptionPropagation.main(CheckedExceptionPropagation.java:9) Exception Handled Here.. Flow Completed..

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • Before discussing about 4 rules to handle exception in overriding method . You should understand concepts of

  • Method Overriding
  • Exception Handling
  • Exception handling in override method these are 4 rules where you have to handle exceptions for child class according to given parent class scenarios:

    4 Rules for Exception Handling in Overring Method
    4 Rules for Exception Handling in Overring Method

    Note : When you face any Java interview and test at least one or two questions surely will ask based on these cases to check you Exception Handling concepts and practical knowledge.

    Case 1 : If parent-class method doesn’t declare any exception

  • Child class overriding method can declare no exception in overriding method.

    Overriding Method No Exception throws
    Overriding Method No Exception throws

  • Child class overriding method can declare unchecked exception in overriding method.

    Overriding Method Throws Unchecked Exception
    Overriding Method Throws Unchecked Exception

  • Child class overriding method can declare strictly no checked exception in overriding method.

    Override method throws no checked exception
    Override method throws no checked exception

  • Case 2 : If parent-class method declares unchecked exception

  • Child class overriding method can declare no exception in overriding method.

    Parent Uncheck child no excepton
    Parent Class Unchecked Exception Child Class No Exception

  • Child class overriding method can declare any number of unchecked exception in overriding method.

    Parent Unchecked exception Child any Number Unchecked exception
    Parent Class method UncheckedException and Child Class overriding method unlimited Unchecked Exception

  • Child class overriding method can declare strictly no checked exception in overriding method.

    Parent Class Unchecked Exception and Child class Checked Exception
    Parent Class Unchecked Exception and Child class overriding method Checked Exception not allow.

  • Case 3 : If parent-class method declares checked exception

  • Child class overriding method can declare no exception in overriding method.

    Parent Class Method Checked Exception Child Class No Exception
    Parent Class Method Checked Exception Child Class Overriding Method No Exception

  • Child class overriding method can declare same checked exception in overriding method.

    Parent Class Checked Exception Child Class same Checked Exception
    Parent Class method Checked Exception Child Class overriding method same Checked Exception

  • Child class overriding method can declare sub-type of checked exception in overriding method. Parent class checked exception and child class sub class checked exception
  • Child class overriding method can declare any number of unchecked exception in overriding method. Parent class checked exception child class any number unchecked exception
  • Case 4 : If parent-class method declares both checked & unchecked exceptions

  • Child class overriding method can declare no exception in overriding method.

    Parent class checked and uncheked exception child no exception
    Parent class checked and un-cheked exception child class overriding method no exception

  • Child class overriding method can declare same checked exception in overriding method.

    Parent class having checked and uncheck exception both and child class checked exception
    Parent class having checked and uncheck exception both and child class overriding method having same checked exception

  • Child class overriding method can declare sub-type of checked exception in overriding method.

    Parent class having checked and uncheked exception child class having sub class of cheked exception
    Parent class having checked and uncheked exception child class overriding method having sub class of checked exception

  • Child class overriding method can declare any number of unchecked exception in overriding method.

    Parent class having cheked and unchecked exception and child class having unlimited unchecked exception
    Parent class having chceked and unchecked exception and child class overriding method having unlimited unchecked exception

  • Conclusions

    I have covered all scenarios for exception handling in overriding method:

  • If parent-class method doesn’t declare any exception, then child-class overriding-method can declare,
  • 1. No exception or
  • 2. Any number of unchecked exception
  • 3. but strictly no checked exception
  • If parent-class method  declare unchecked exception , then child-class overriding-method can declare,
  • 1. No exception or
  • 2. Any number of unchecked exception
  • 3. but strictly no checked exception
  • If parent-class method  declare checked exception , then child-class overriding-method can declare,
  • 1. No exception or
  • 2. Same checked exception or
  • 3. Sub-type of checked exception or
  • 4. any number of unchecked exception
  • All above conclusion hold true, even if combination of both checked & unchecked exception is declared in parent-class’ method
  • Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Questions and Answers
  • java.lang.StackOverflowError is sub class of java.lang.VirtualMachineError . JVM throws a stack overflow when application stack exhausted, due to deep recursion.

    What is StackOverFlowError?

    When a method call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the java.lang.StackOverflowError is thrown by the Java Virtual Machine (JVM) .

    Reasons to occurs java.lang.StackOverFlowError

  • Recursion : A method invokes itself during it’s execution and method calling stack reach to max limit of JVM . Example 1
  • Circular Dependency on method calling . Example 2
  • A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.

    Constructors

  • StackOverflowError(): Constructs a StackOverflowError with no detail message.
  • StackOverflowError(String s): Constructs a StackOverflowError with the specified detail message.
  • Recusrsion StackOverFlowError Example

    In this below recursion factorial of number example , I have commented out the recursion terminating condition to create StackOverFlowError.

    package com.exceptions.errors; public class StackOverFlowErrorExample { public static void main(String[] args) { RecursionExample recursion=new RecursionExample(); System.out.println(recursion.fact(7)); class RecursionExample public int fact(int n){ //Uncomment this condition to recursion terminating condition // if( n == 0 ){ // return 1; // } return n * fact(n-1);

    Output

    Exception in thread "main" java.lang.StackOverflowError at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at com.exceptions.errors.RecursionExample.fact(StackOverFlowErrorExample.java:18) at ......

    Circular Dependency StackOverFlowError Example

    In this example, we defined two classes, Company and Employee. The class Company contains one instance of the Employee class, while, the Employee class contains one instance of the Company class. Thus, we have a circular dependency between these two classes. Furthermore, each toString() method, invokes the corresponding toString() method of the other class, and so on, which results in a java.lang.StackOverflowError .

    package com.exceptions.errors; public class StackOverFlowExample2 { public static void main(String[] args) { Company company = new Company(); System.out.println(company.toString()); class Company { private int budget; private Employee employeeInstance = null; public Company() { budget = 0; employeeInstance = new Employee(); @Override public String toString() { return "FacingIssueOnIT : Company"; class Employee { private int salary; private Company companyInstance = null; public Employee() { salary = 10; companyInstance = new Company(); @Override public String toString() { return "FacingIssueOnIT : Employee";

    Output

    Exception in thread "main" java.lang.StackOverflowError at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33) at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18) at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33) at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18) at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33) at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18) at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33) at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18) at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:33) at com.exceptions.errors.Company.&amp;amp;lt;init&amp;amp;gt;(StackOverFlowExample2.java:18) at com.exceptions.errors.Employee.&amp;amp;lt;init&amp;amp;gt;

    How to deal with the StackOverflowError

  • In case of recursion, always apply terminating condition and that should execute in some cases so that method call not go to continuous call.
  • To inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code being recursively called. Once you detect these lines, you must carefully inspect your code and understand why the recursion never terminates.
  • In case recursion and terminating condition are in place correctly.  You can increase the stack’s size, in order to allow a larger number of invocations. Default thread stack configuration depend on JVM some may equals to either 512KB, or 1MB. You can increase the thread stack size using the -Xss flag. This flag can be specified either via the project’s configuration, or via the command line. The format of the -Xss argument is:
    -Xss[g|G|m|M|k|K]
  • Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Question and Answers
  • java.lang.OutOfMemoryError is subclass of java.lang.VirtualMachineError . It throws when the JVM cannot allocate an object because of out of memory, and no more memory could be made available by the garbage collector . OutOfMemoryError objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

    Types of OutOfMemoryError in Java

    Mainly two types of java.lang.OutOfMemoryError in Java:

  • The java.lang.OutOfMemoryError: Java heap space
  • The java.lang.OutOfMemoryError: PermGen space
  • Though both of them occur because JVM ran out of memory they are quite different from each other and their solutions are independent of each other.

    Constructors

  • OutOfMemoryError() : Constructs an OutOfMemoryError with no detail message.
  • OutOfMemoryError(String s): Constructs an OutOfMemoryError with the specified detail message.
  • OutOfMemoryError : Java heap space Example

    In the below example try to create java.lang.OutOfMemoryError by adding the name “Saurabh Gupta” in an infinite loop. It will add to the point as long as not throw java.lang.OutOfMemoryError .

    package com.exceptions.errors; public class OutOfMemoryErrorExample { public static void main(String[] args) { StringBuffer str=new StringBuffer("FacingIssuesOnIt"); int i=0; while(i==0) str.append("Saurabh Gupta"); System.out.println(i);

    OutOfMemoryError StackTrace

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source) at java.lang.AbstractStringBuilder.append(Unknown Source) at java.lang.StringBuffer.append(Unknown Source) at com.exceptions.errors.OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:10)

    In the above example, you see a small program can also create OutOfMemoryError because of just small wrong steps. as it’s having an infinite loop and adding tests continuously on the same variable. You will get in-depth knowledge of this in the below paragraphs.

    Reason for java.lang.OutOfMemoryError: PermGen space

    PermGen can happen in two ways:

    Reason 1:

    If you are familiar with different generations of heap and garbage collection process, new, old and permanent generation of heap space. PermGen means the Permanent Generation of the heap is used to store the String pool and various Metadata required by JVM related classes, method and other java primitives.

    Most JVM default size of Perm Space is around “64MB” which can reach easily by having too many classes and a huge number of Strings in the application.

    Point to Remember: Setting heap size by -Xmx no impact on OutOfMemory in perm space. To increase the size of perm space specify a size for permanent generation in JVM options as below.

    “-XX: PermSize” and “-XX: MaxPermSize”

    export JVM_ARGS=”-Xmx1024m -XX:MaxPermSize=256m”

    Reason 2:
    Another reason for “ java.lang.OutOfMemoryError: PermGen ” is memory leak through Classloaders . Generally, it’s happening in webserver and application servers like Glassfish, Weblogic, WebSphere or tomcat.

    In application server used different class loaders are used to load different applications so that deploy and un-deploy of one application without affecting of others application on the same server. But during un-deployment, if the container somehow keeps a reference of any class loaded by application class loader then that class and all related class will not get garbage collected and quickly fill permGen space if you deploy and un-deploy application many times.

    Solutions to Resolve java.lang.OutOfMemoryError

    Java.lang.OutOfMemoryError is a kind of error from JVM because of memory leak or objects are consuming memory but not releasing it. To identify the root cause of the problem required lots of investigation, like which object is taking memory, how much memory it is taking or finding the dreaded memory leak.

    Solve java.lang.OutOfMemoryError: Java heap space

  • An easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options. For increasing heap size in JVM better option to set  -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application.

    export JVM_ARGS=”-Xms1024m -Xmx1024m”

  • If still getting OutOfMemoryError after applying the above solution. In this case, you can use a profile tool to investigate memory leak and heap dump. For example :
  • Eclipse Memory Analyzer(MAT) to examine your heap dump.
  • Profiler like Netbeans or JProbe.
  • This is a tough solution and requires some time to analyze and find memory leaks.

    Solve java.lang.OutOfMemoryError: PermGen space

  • Easy way to solve OutOfMemoryError: PermSpace is to increase the heap size of Perm space by using JVM option   “-XX: MaxPermSize “. You can also specify the initial size of Perm space by using “-XX: PermSize” and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. For Example export JVM_ARGS=”-XX:PermSize=64M -XX:MaxPermSize=256m”
  • If still getting OutOfMemoryError after applying the above solution. In this case, you can use a profile tool to investigate memory leak and heap dump. For example :
  • Eclipse Memory Analyzer(MAT) to examine your heap dump.
  • Profiler like Netbeans or JProbe.
  • This is a tough solution and requires some time to analyze and find memory leaks.

    Solve OutOfMemoryError in PermGen Space In Tomcat

    Tomcat  6.0 onward  provides memory leak detection feature which can detect many common memory leaks on web-app perspective For Example:

  • ThreadLocal memory leaks
  • JDBC driver registration
  • RMI targes
  • LogFactory
  • Thread spawned by web-apps etc.
  • You can check complete details on http://wiki.apache.org/tomcat/MemoryLeakProtection

    Below are a couple of free tools available in java space used to analyze heap and culprits of OutOfMemoryError .

    Tools to investigate java.lang.OutOfMemoryError

  • Eclipse Memory Analyzer(MAT): It helps to analyze classloader leaks and memory leaks by analyzing the java heap dump.  It also helps to the consumption of less memory and identify the exact suspect of memory leak.
  • Visualgc (Visual Garbage Collector Monitoring Tool): Attach this tool to your instrument hot spot JVM. It visually displays all key data graphically including garbage collection, class loader, and JVM compiler performance.
  • Jhat (Heap Analyzer Tool): After JDK-6 it’s part of a new version of JDK now. We can use that command-line utility to analyze heap dump in heap dump file by using “jmap”. When you execute the below command and point your browser to port 7000 then you can start analyzing objects present in the heap dump.
    Command: jthat -J-Xmx256m heapdump
  • References

    https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html

    Know More

    To know more about Java Exception Hierarchy, in-built exception, checked exception, unchecked exceptions, and solutions. You can learn about Exception Handling in override methods and lots more. You can follow the below links:

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Question and Answers
  • Java , Java Issues & Solutions

    [Solved] java.lang.NumberFormatException: For input string “AB.C”

    Leave a comment

    NumberFormatException is runtime Unchecked Exception . It’s sub class of IllegalArgumentsException . Generally it throws to indicate that the application has attempted to convert a String to one of the numeric types, but that the string does not have the appropriate format.

    Constructors

  • NumberFormatException() : Constructs a NumberFormatException with no detail message.
  • NumberFormatException(String s) : Constructs a NumberFormatException with the specified detail message.
  • Example 1

    In below example asking to enter integer value from console and that value further use for other steps. This example will throw ArithmaticException when enter value as 0 or throw NumberFormatException for any value except integer.

    import java.util.Scanner; public class NumberFormatExceptionExample { public static void main(String[] args) { System.out.println("Please enter a integer value :"); Scanner scn = new Scanner(System.in); int n = Integer.parseInt(scn.nextLine()); if (99%n == 0) System.out.println(n + " is a factor of 99"); catch (ArithmeticException ex) System.out.println("Arithmetic " + ex); catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex);

    Output

    Please enter a integer value : Number Format Exception java.lang.NumberFormatException: For input string: "3.56"

    Example 2

    Here issue is passing string as non numeric value while parsing for Integer will throw NumberFormatException .

    int age=Integer.parseInt("Twenty");} catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex);

    Example 3

    Here issue is passing string as numeric  value which out MAX range of integer that’s what throw NumberFormatException . In this case instead of using Integer.parseInt() use Long.parseLong().

    int phoneNumber=Integer.parseInt("1234567890"); catch (NumberFormatException ex) System.out.println("Number Format Exception " + ex);

    Solutions

    Here are some common solutions for NumberFormatException:

  • Always check for numeric before using statement Integer.parseInt().
  • If expectation is big numeric value always use Long.parseLong().
  • References

    https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html

    Know More

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:

  • Java Exception Handling Tutorial
  • JDBC : Exception and Warning Handling
  • Mockito Exceptions Handling
  • Java Built-in Exceptions Solutions
  • [Top 50] Exception Handling Interview Question and Answers
    1. Create a class extends with one of the exceptions which are sub types of the java.lang.Exception class. Generally exception class always extends directly from the Exception class.
    2. Create a constructor with String parameter which is the detailed message of the exception.
    3. In this constructor, simply call the super constructor and pass the message.

    Note : There is convection to use Custom Exception name ends with word ‘Exception’.

    Steps Custom Exception or User Defined Exception
    Custom Exception or User Defined Exception

    In below example create a Custom Exception as EmployeeNotFoundException
    which is extending class java.lang.Exception and create different constructors to handle exception with exception message and stack traces.

    public class EmployeeNotFoundException extends Exception{ //Constructor to throw exception with message public EmployeeNotFoundException(String message) super(message); //Constructor to throw exception with stack trace public EmployeeNotFoundException(Throwable cause) super(cause); //Constructor throw exception meth message and stack trace public EmployeeNotFoundException(String message,Throwable cause) super(message,cause);

    Example to use Custom Exception

    import java.util.Arrays; import java.util.List; public class CustomExceptionTest { public static void main(String[] args) throws EmployeeNotFoundException{ String[] empArr ={"Saurabh", "Gaurav", "Shailesh", "Ankur", "Ranjith", "Ramesh"}; List empList = Arrays.asList(empArr); String searchStr = "Rishabh"; try { if (!empList.contains(searchStr)) { //Throw exception when emmployee name not match with existing list with customize message. throw new EmployeeNotFoundException("Employee not found in search"); } catch (Exception ex) { throw new EmployeeNotFoundException("Employee not found",ex);

    Output

    Exception in thread "main" com.customexceptions.EmployeeNotFoundException: Employee not found at com.customexceptions.CustomExceptionTest.main(CustomExceptionTest.java:16) Caused by: com.customexceptions.EmployeeNotFoundException: Employee not found in search at com.customexceptions.CustomExceptionTest.main(CustomExceptionTest.java:13)

    Conclusion

    In this topic , You have learn about :

    • What is Custom Exception or User-defined exception?
    • How to create Custom Exception or User-defined Exception?
    • and How to implement it?

    Learn More on Java Exception Handling

    To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

    UnnecessaryStubbingException is runtime and sub class of MockitoException . Mockito JUnit Runner triggers UnnecessaryStubbingException only when none of the test methods use the stubbings. This means that it is ok to put default stubbing in a ‘setup’ method or in test class constructor. That default stubbing needs to be used at least once by one of the test methods.

    Constructors

  • UnnecessaryStubbingException(String message) : Will throw exception with message.
  • Example

    //code test: String result = translator.translate("Saurabh"); //Mock: // <- stubbing used during code execution when(translator.translate("Saurabh")).thenReturn("Gupta"); // <- stubbing never used when(translator.translate("Gaurav")).thenReturn("Gupta");

    Solutions

    It is highly recommended to remove unused stubbings to keep the codebase clean. You can opt-out from detecting unused stubbing using MockitoJUnitRunner.Silent() or MockitoRule.silent() (when you are using Mockito JUnit rules.

    References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/UnnecessaryStubbingException.html

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • Mockito Exceptions
  • PotentialStubbingProblem is a RuntimeException and subclass of MockitoException . Mockito framework throws this exception when “ stubbing arguments mismatch “.

    Strict stubbing is a new opt-in feature for JUnit Rule and JUnit Runner to detect potential stubbing problems org.mockito.exceptions.misusing.PotentialStubbingProblem exception is thrown when mocked method is stubbed with some argument in test but then invoked with different argument in code.

    This exception can occurred by many reasons:

  • Mistake or typo in the test code, the argument(s) used when declaring stubbing’s is unintentionally different.
  • Mistake or typo in the code under test, the argument(s) used in the code under test is unintentionally different.
  • Intentional use of stubbed method with different argument, either in the test (more stubbing) or in code under test.
  • Constructors

  • PotentialStubbingProblem(String message) : Will throw exception with message.
  • Example

    //test method: given(mock.getSomething(200)).willReturn(something); //code under test: // stubbing argument mismatch Something something = mock.getSomething(100);

    Solutions

    public class TestExample { @Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @Test public void exampleTest() { //Change the strictness level only for this test method: mockito.strictness(Strictness.LENIENT); //remaining test code given(mock.getSomething(200)).willReturn(something); //Will work Something something = mock.getSomething(100);

    References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/PotentialStubbingProblem.html

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • Mockito Exceptions
  • RedundantListenerException is RuntimeException and sub class of MockitoException . This occurred by Mockito framework when  instance of MockitoListener is being added to Mockito Framework and there is already a listener with this implementation type registered.

    Note : It is ok to add multiple different implementations of the same listener interface type.

    Constructors

  • RedundantListenerException(String message) : Will throw exception with message.
  • Example

    MockitoFramework.addListener(MockitoListener);

    Solutions

    If you are trying to add the listener but a listener of the same type was already added (and not removed) this method will throw RedundantListenerException . This is a safeguard to ensure users actually remove the listeners via removeListener. We do not anticipate the use case where adding the same listener type multiple times is useful.

    References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/RedundantListenerException.html

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • Mockito Exceptions
  • MockitoException is RuntimeException raised by Mockito framework to emit an error either due to Mockito, or due to the User. Mockito throws exception in form of stacktrace with suggested solutions.

    StackTrace for Application calls:

    StackTraceElement [] Throwable.getStackTrace()

    StackTrace with Mockito and API calls:

    StackTraceElement [] getUnifilteredStackTrace()

    Constructors

  • MockitoException(String message) : Will throw exception with message.
  • MockitoException(String message, Throwable T) : Will throw exception with message and stacktrace.
  • Mockito Exception Subclasses

    MockitoException Hierarchy
    MockitoException Hierarchy

  • CannotStubVoidMethodWithReturnValue
  • CannotVerifyStubOnlyMock
  • FriendlyReminderException
  • InvalidUseOfMatchersException
  • MissingMethodInvocationException
  • MockitoConfigurationException
  • NotAMockException
  • NullInsteadOfMockException
  • PotentialStubbingProblem
  • RedundantListenerException
  • SmartNullPointerException
  • UnfinishedStubbingException
  • UnfinishedVerificationException
  • UnnecessaryStubbingException
  • WrongTypeOfReturnValue
  • Example

    In below example , using OngoingStubbing on mock object of Map interface where setting stub object for get() method which accept any input String and return response as String as set in thenReturn () method.

    import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.mockito.exceptions.base.MockitoException; import org.mockito.stubbing.OngoingStubbing; public class MockitoApplicationTester { @Test public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception { // Mock of Map interface Map<String, String> map = mock(Map.class); OngoingStubbing<String> mapOngoingStubbing = when(map.get(anyString())); try { mapOngoingStubbing.thenReturn("1st stubbing"); //This method will throw exception mapOngoingStubbing.thenReturn("2nd stubbing"); Assert.assertEquals(map.get("Test"), "1st stubbing"); } catch (MockitoException e) { StackTraceElement[] stacks = e.getStackTrace(); for (StackTraceElement stack : stacks) { System.out.println(stack.getMethodName()); StackTraceElement[] ustacks = e.getUnfilteredStackTrace(); for (StackTraceElement stack : ustacks) { System.out.println(stack.getMethodName()); throw e;

    Output

    org.mockito.exceptions.base.MockitoException: Incorrect use of API detected here: -> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_IndexOutOfBoundsException(MockitoApplicationTester.java:48) You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once. Examples of correct usage: when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception); when(mock.isOk()).thenReturn(true, false).thenThrow(exception); at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_IndexOutOfBoundsException(MockitoApplicationTester.java:48) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span>

    Solutions

    Above example is throwing MockitoException with message as “Incorrect use of API detected here” because of thenReturn () method set two times value for single mock stub object. For solving above issue comment one of thenRetun () statement from try block.

    References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/base/MockitoException.html#getUnfilteredStackTrace()

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • WrongTypeOfReturnValue is RuntimeException and Subclass of MockitoException. It throws when :

  • It might occurred because of wrongly written multi-threaded tests.
  • A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family of methods.
  • Constructors

  • WrongTypeOfReturnValue(String message) : Will throw exception with message.
  • Example

    Below case to show you on what case Mockito will throw WrongTypeOfReturnValue .

    import static org.mockito.Mockito.*; import static org.junit.Assert.*; import org.junit.Test; public class NestedWhen { public class Bar { public class Foo { Bar getBar() { return new Bar(); public class Product { Bar bar; Product(Foo f) { bar = f.getBar(); public class ProductService { Foo foo; ProductService(Foo f) { foo = f; Product produce() { return new Product(foo); @Test public void nestedWhenTest() { Foo mfoo = mock(Foo.class); Product mpoo = mock(Product.class); ProductService productService = spy(new ProductService(mfoo)); // throw WrongTypeOfReturnValue exception here!!! when(productService.produce()).thenReturn(mpoo);

    Output

    org.mockito.exceptions.misusing.WrongTypeOfReturnValue: NestedWhen$Product$$EnhancerByMockitoWithCGLIB$$4418933b cannot be returned by getBar() getBar() should return Bar If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because: 1. This exception *might* occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing. 2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method. at com.facingissuesonit.mockito.MockitoTestExamples.NestedWhen.nestedWhenTest(NestedWhen.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497)

    Solutions

    Here above code is throwing this exception because spy execute the real code by nature, so when calling “productService.produce()” the expression is actually executed and return a real Product. The constructor of Product takes the constructor arg “foo” which is a mock and it executes “f.getBar()”. This invocation is recorded by mockito because this “foo” instance is a mock.

    Then when you want to return “mpoo”, mockito raises the exception WrongTypeOfReturnValue saying that the recorded invocation “foo.getBar()” cannot return a Product.

    If you want to mock a partial mock, which you should avoid if possible. You need to use the following style for spies, this way Mockito can tell the spy instance to only record the invocation.

    doReturn(mpoo).when(productService).produce();

    References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/WrongTypeOfReturnValue.html

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • Mockito Exceptions
  • InvalidUseOfMatchersException is RuntimeException and subclass of MockitoException . It throws when trying to push behavior on object which is not mock.

    Constructors

  • InvalidUseOfMatchersException() : Will throw exception.
  • InvalidUseOfMatchersException (String message) : Will throw exception with message.
  • Example

    Here in below example mock Map interface and creating stub for get method to return fixed String for any type of String elements.

    import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class MockitoApplicationTester { @Test public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception { // Mock of Map interface Map<String, String> mapMock = mock(Map.class); Map<String, String> mapReal = new HashMap<String, String>(); //Issue is here because performing argument matcher without mock object when(mapReal.get(anyString())).thenReturn("1st stubbing"); //Correct statement when(mapMock.get(anyString())).thenReturn("1st stubbing"); Assert.assertEquals(mapMock.get("Test"), "1st stubbing");

    Output

    org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced argument matcher detected here: -> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22) You cannot use argument matchers outside of verification or stubbing. Examples of correct usage of argument matchers: when(mock.get(anyInt())).thenReturn(null); doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject()); verify(mock).someMethod(contains("foo")) Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode(). Mocking methods declared on non-public parent classes is not supported. at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497)

    Solutions

    Here in above code is throwing this exception because using real object to create stub that’s what throwing “ InvalidUseOfArgumentMatchersException “. To fix above this comment out wrong statement and execute again.

    This exception can occurred by others ways also:

  • T his error might show up because you use argument matchers with methods that cannot be mocked.
  • Stubbed and verified method can be used on final/private/equals()/hashCode() methods.
  • Mocking methods declared on non-public parent classes is not supported.
  • References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/InvalidUseOfMatchersException.html

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • Mockito Exceptions
  • MissingMethodInvocationException is RuntimeException and subclass of MockitoException . It generally throws when:

  • It might occurs when() requires an argument which has to be ‘a method call on a mock. For example: when(mock.getArticles()).thenReturn(articles);
  • You try to stubbed/verified either of: final/private/equals()/hashCode() methods.
  • Mocking methods declared on non-public parent classes is not supported.
  • Inside when() you don’t call method on real object always call from mock or spy.
  • Constructors

  • MissingMethodInvocationException(String message) : Will throw exception with message.
  • Example

    To complete example follow link Mockito + JUnit Tutorial

    import static org.mockito.Mockito.spy; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.mockito.Mockito.*; //@RunWith attaches a runner with the test class to initialize the test data @RunWith(org.mockito.runners.MockitoJUnitRunner.class) public class MathApplicationTestrSpy { private CalculatorService calcService; @Before public void setUp(){ Calculator calculator = new Calculator(); calcService = spy(calculator); //Issue is here because using actual object when(calculator.add(20.0,10.0)).thenReturn(30.0); @Test public void testAdd(){ Assert.assertEquals(calcService.add(20.0, 10.0),30.0,0);

    Output

    org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles); Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods *cannot* be stubbed/verified. Mocking methods declared on non-public parent classes is not supported. 2. inside when() you don't call method on mock but on some other object. at com.facingissuesonit.mockito.MockitoTestExamples.MathApplicationTestrSpy.setUp(MathApplicationTestrSpy.java:29) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)

    Solutions

    Here in above example trying stub on real object instead of mock and spy object. To solve this issue update code as below. For complete example please refer Mockito + JUnit Tutorial Mockito + JUnit Tutorial.

    @Before public void setUp(){ Calculator calculator = new Calculator(); calcService = spy(calculator); //Issue is here because using actual object //when(calcService.add(20.0,10.0)).thenReturn(30.0); //Used Spy object when(calculator.add(20.0,10.0)).thenReturn(30.0);

    References

    https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/MissingMethodInvocationException.html

    Know More

    To know more about Junit, Mockito and exception solutions follow below links:

  • Mockito +JUnit Tutorial
  • Junit Tutorial
  • Mockito Exceptions
  • Elasticsearch , ELK , Filebeat , Kibana , Logstash

    Elasticsearch Ingest Node Vs Logstash Vs Filebeat

    Leave a comment

    Elasticsearch Ingest Node

    Ingest node use to pre-process documents before the actual document indexing
    happens. The ingest node intercepts bulk and index requests, it applies transformations, and it then passes the documents back to the index or bulk APIs.

    Logstash

    Logstash is a server-side data processing pipeline that ingests data from multiple sources simultaneously, transforms it, and then sends it to different output sources like Elasticsearch, Kafka Queues, Databases etc.

    Filebeat

    Filebeat is lightweight log shipper which reads logs from thousands of logs files and forward those log lines to centralize system like Kafka topics to further processing on Logstash, directly to Logstash or Elasticsearch search.

    There is overlap in functionality between Elasticsearch Ingest Node , Logstash and Filebeat.All have there weakness and strength based on architectures and area of uses. You cam also integrate all of these Filebeat, Logstash and Elasticsearch Ingest node by minor configuration to optimize performance and analyzing of data.

    Below are some key points to compare Elasticsearch Ingest Node , Logstash and Filebeat.

    Points Elasticsearch Ingest Node Logstash Filebeat Data In and Out As ingest node runs as pipeline within the indexing flow in Elasticsearch, data has to be pushed to it
    through bulk or indexing requests and configure pipeline processors process documents before indexing of actively writing data
    to Elasticsearch. Logstash supports wide variety of input and output plugins. It can act as middle server to accept pushed data from clients over TCP, UDP and HTTP and filebeat, message queues and databases.
    It parse and process data for variety of output sources e.g elasticseach, message queues like Kafka and RabbitMQ or long term data analysis on S3 or HDFS. Filebeat specifically to shipped logs files data to Kafka, Logstash or Elasticsearch. Queuing Elasticsearch Ingest Node is not having any built in queuing mechanism in to pipeline processing.
    If the data nodes are not able to accept data, the ingest node will stop accepting data as well. Logstash provide persistent queuing feature mechanism features by storing on disk. Filebeat provide queuing mechanism with out data loss. Back-pressure Clients pushing data to ingest node need to be able to handle back-pressure by queuing data In case elasticsearch is not reachable or able to accept data for extended period otherwise there would be data loss. Logstash provide at least once delivery guarantees and buffer data locally through ingestion spikes. Filebeat designed architecture like that with out losing single bit of log line if out put systems like kafka, Logstash or Elasticsearch not available Data Processing Ingest node comes around 20 different processors, covering the functionality of
    the most commonly used Logstash plugins.

    Ingest node have some limitation like pipeline can only work in the context of a single event. Processors are
    also generally not able to call out to other systems or read data from disk. It’s also not having filters as in beats and logstash. Logstash has a larger selection of plugins to choose from. This includes
    plugins to add or transform content based on lookups in configuration files,
    Elasticsearch, Beats or relational databases.

    Logstash support filtering out and dropping events based on
    configurable criteria. Beats support filtering out and dropping events based on
    configurable criteria. Configuration “Each document can only be processed by a single pipeline when passing through the ingest node. “Logstash supports to define multiple logically separate pipelines by conditional control flow s to handle complex and multiple data formats.

    Logstash is easier to measuring and optimizing performance of the pipeline to supports monitoring and resolve potential issues quickly by excellent pipeline viewer UI.
    Minor configuration to read , shipping and filtering of data. But limitation with parsing. Specialization Ingest Node pipeline processed data before doing indexing on elasticsearch. Its middle server to parse process and filter data from multiple input plugins and send processes data to output plugins. Specific to read and shipped logs from different servers to centralize location on Elasticsearch, Kafka and if require parsing processed through Logstash. Integration Logstash supports sending data to an Ingest Pipeline. Ingest node can accept data from Filebeat and Logstash etc, Filebeat can send data to Logstash , Elasticsearch Ingest Node or Kafka. Performance Please follow below link to check performance of each on different cases: Elasticsearch Ingest Node , Logstash and Filebeat Performance comparison.

    Learn More

    To know more about Elasticsearch Ingest Node, Logstash or Filebeat follow below links:

  • Elasticsearch Tutorial
  • Filebeat Tutorial
  • Logstash Tutorial
  • Almost every developer handle Duration and Period issues while need to do any calculation based on Date and Time. In Java 8 introduces new classes to handle Duration and period.

  • Period : A date period is measured in days, months, and years. Period can be calculated by java.time.Period class.
  • Duration: A time duration is measured in hours, minutes, and seconds. Duration can be calculated by java.time.Duration class.
  • Period period= Period.between(localDate1, localDate2);

    Duration duration=Duration.between(localTime1, localTime2);

    Duration.toString() method return duration as P1Y10M6D . Here duration is 1 year, 10 month and 6 days.

    Period .toString() method return period as PT3H10M40S . Here duration is 3 hour, 10 minute and 40 seconds.

    Example

    Below is example to calculate Period and Duration  between two dates and times.

    package com.date; import java.time.Duration; import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.Period; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Java8DurationAndPeriodExample { public static void main(String[] args) { LocalDate june9th2016 = LocalDate.of(2016, Month.JUNE, 9); LocalDate April15th2017 = LocalDate.of(2017, Month.APRIL, 15); DateTimeFormatter format=DateTimeFormatter.ofPattern("MM/dd/yy"); // Compute period: Period period=Period.between(April15th2017, june9th2016); System.out.format("Period between %s and %s is %d year, %d month, %d days n" , April15th2017.format(format), june9th2016.format(format), period.getYears(), period.getMonths(), period.getDays()); // Add one month to August 10, 2018: LocalDate April15th2017plusOneMonth=April15th2017.plus(1, ChronoUnit.MONTHS); System.out.format("Adding one month to %s yields %s n", April15th2017.format(format), April15th2017plusOneMonth.format(format)); // Subtract one month from August 10, 2018: LocalDate April15th2017minusOneMonth=April15th2017.plus(-1, ChronoUnit.MONTHS); System.out.format("Subtracting one month from %s yields %s n", April15th2017.format(format), April15th2017minusOneMonth.format(format)); // Create two times for duration processing: LocalTime twelveFifteenPM = LocalTime.of(12, 15, 9); LocalTime twoTwentyFiveAM = LocalTime.of(2, 25, 0); DateTimeFormatter timeFormat=DateTimeFormatter.ofPattern("HH:mm:ss a"); Duration duration=Duration.between(twoTwentyFiveAM, twelveFifteenPM); System.out.format("Duration between %s and %s is %s n", twoTwentyFiveAM.format(timeFormat), twelveFifteenPM.format(timeFormat), duration); duration=Duration.between(twelveFifteenPM, twoTwentyFiveAM); System.out.format("Duration between %s and %s is %s n", twelveFifteenPM.format(timeFormat), twoTwentyFiveAM.format(timeFormat), duration); <span data-mce-type="bookmark" id="mce_SELREST_start" data-mce-style="overflow:hidden;line-height:0" style="overflow:hidden;line-height:0" ></span>}

    Output

    Period between 04/15/17 and 06/09/16 is 0 year, -10 month, -6 days Adding one month to 04/15/17 yields 05/15/17 Subtracting one month from 04/15/17 yields 03/15/17 Duration between 02:25:00 AM and 12:15:09 PM is PT9H50M9S Duration between 12:15:09 PM and 02:25:00 AM is PT-9H-50M-9S

    [Solved] java.time.temporal. UnsupportedTemporalType Exception: Unsupported field: YearOfEra

    1 Comment

    UnsupportedTemporalTypeException is sub class of java.time.DateTimeExceptio n which is runtime checked exception. UnsupportedTemporalTypeException indicates that a ChronoField or ChronoUnit is not supported for a Temporal class.

    Constructors

  • UnsupportedTemporalTypeException(String message): Constructs a new UnsupportedTemporalTypeException with the specified message.
  • UnsupportedTemporalTypeException(String message, Throwable cause): Constructs a new UnsupportedTemporalTypeException with the specified message and cause.
  • Exception Example

    Below is example to convert Legacy date(java.util.Date) to java.time.Instant and vice versa.

    package java.time.temporal; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Date; public class UnsupportedTemporalTypeExceptionExample { public static void main(String[] args) { SimpleDateFormat utilDateTimeFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //Exception on below line to resolve this issue uncomment at end of line. DateTimeFormatter java8DateTimeFormat=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");//.withZone(ZoneId.systemDefault());; //Date to Instant Date date=new Date(); Instant inst = date.toInstant(); System.out.println("Initial Date :"+utilDateTimeFormat.format(date)); System.out.println("Converted Instant :"+java8DateTimeFormat.format(inst)); //Instant To Date Date newDate = Date.from(inst); System.out.println("Converted Date :"+utilDateTimeFormat.format(newDate));

    Exception StackTrace

    Initial Date :2018/08/04 08:11:53 Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra at java.time.Instant.getLong(Unknown Source) at java.time.format.DateTimePrintContext.getValue(Unknown Source) at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(Unknown Source) at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(Unknown Source) at java.time.format.DateTimeFormatter.formatTo(Unknown Source) at java.time.format.DateTimeFormatter.format(Unknown Source) at com.date.Legacy2Java8DateTimeInteroprability.main(Legacy2Java8DateTimeInteroprability.java:26)

    Issue

    The Instant class doesn’t contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC. So, formatter can’t print a date because date always printed for concrete time zone. To format an Instant a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.

    Solutions

    The time-zone can be added directly to the formatter using withZone().You should set time zone to formatter and all will be fine.

    in above example you can uncomment commented section as below to solve this issue.

    DateTimeFormatter java8DateTimeFormat=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").withZone(ZoneId.systemDefault());;

    some more ways to format date

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT ) .withLocale( Locale.UK ) .withZone( ZoneId.systemDefault() ); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);

    Posts navigation