![]() |
痴情的键盘 · 独家深度 | 一文看懂 ...· 昨天 · |
![]() |
高兴的眼镜 · SpringBoot运行中修改applica ...· 12 小时前 · |
![]() |
健壮的葡萄酒 · SpringBoot - 动态修改yml配置文件· 12 小时前 · |
![]() |
文雅的猴子 · SpringBoot动态更新yml文件 - ...· 12 小时前 · |
![]() |
朝气蓬勃的咖啡豆 · SpringBoot ...· 12 小时前 · |
![]() |
近视的橙子 · 【学青会】泳将陈欣夺冠,广州体育代表团收获10金· 3 天前 · |
![]() |
烦恼的上铺 · 广拓市场渠道 ...· 2 周前 · |
![]() |
卖萌的充电器 · 科技型中小企业评价-工业和信息化部火炬中心· 5 月前 · |
![]() |
才高八斗的玉米 · 著名围棋国手简介:林海峰九段-搜狐体育· 10 月前 · |
![]() |
发财的青椒 · 车轮上的2022|BBA全球销量悉数下滑,重 ...· 1 年前 · |
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.
Follow below links to learn more posts on JDBC and solving JDBC related issues :
JDBC API introduced statement , PreparedStatement and CallableStatemnet to execute different types of queries:
Follow below links to know more on JDBC and solving JDBC issues :
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.
Here you have learned both the ways to access with or without DSN (Data Source Name).
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:
Here you learn about steps to connect database with application and specific configuration information for Oracle.
See also :
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:
Here you learn about steps to connect database with application and specific configuration information for MySQL.
See also :
Follow below links to know more on JDBC and solving JDBC issues :
JDBC Interview Questions And Answers
There are 5 steps to connect any java application with the database by using JDBC. They are as follows:
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");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 SQLExceptionEx: Connect with Oracle
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");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();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));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 SQLExceptionSee Also :
Follow below links to learn more on JDBC and solving JDBC related issues :
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 :
Below are implicit methods of enum class.
In the below examples, you will see the use of these methods.
enum Month{ JANNUARY, FEBRUARY, MARCH, APRIL, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBERenum 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();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.
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.
Output
Inserted Total Seconds :180500700 Converted Time :03 Hour : 05 Minute :00 SecondIn 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.
Output
Enter the decimal value: Binary: 1100 Enter the decimal value: Binary: 11001000In this article, you will learn to convert a date to GMT, CST, EST and PST format.
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.
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 AMIn 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";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
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 cmHere 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 IssuesTo 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.
You can get complete list of eclipse shortcuts after following below steps:
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.
Here is list of most frequently used shortcuts by developers and corresponding description.
same way you can also try others as below.
The following shortcuts are the absolute minimum a developer should be familiar with to work efficient in Eclipse.
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 .
Below are methods of Object Class for different purpose as below:
In this below examples you can see how to override and utilize these methods in different ways.
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
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
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?
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.IntegerBelow 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.
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.
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 propertiesHere 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:
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:
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.
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 overridenHere finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.
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 overridenIn this example, we have to handle exception explicitly while calling finalize() method manually while calling by Garbage Collector no exception thrown.
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.
See also : Java : Shallow Cloning Vs Deep 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);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 : BiologyOutput
BiologyNote: If class is having only primitive type values or Immutable object there is no difference between Shallow and Deep Cloning of object.
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 <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);
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.
Here you learn about Shallow and Deep copy of object by constructor and implementing by clone() method of Cloneable Interface which is marker interface.
Below are the list of differences between shallow cloning and deep cloning in java.
Example: Shallow Cloning Example
Example: Deep Cloning Example
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.
“
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.
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.
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 :
In this blog you understand below points:
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+.
Here you will know all above multiple catch block rules in details:
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);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();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);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 ”
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:
Below are running example with legacy way of multi catch and Java 7+.
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
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)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.
My issue was resolved after following above two steps.
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
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();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();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();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();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();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.
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.
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();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();
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.
In below example covered all the above cases.
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.
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();Always follow formatting specifiers rules as given in Java formatter.
https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html
https://docs.oracle.com/javase/8/docs/api/java/util/UnknownFormatConversionException.html
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.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.
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)https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html
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.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:
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");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;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
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.
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
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.
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() .
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");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
Before discussing about 4 rules to handle exception in overriding method . You should understand concepts of
Exception handling in override method these are 4 rules where you have to handle exceptions for child class according to given parent class scenarios:
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.
I have covered all scenarios for exception handling in overriding method:
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.lang.StackOverflowError is sub class of java.lang.VirtualMachineError . JVM throws a stack overflow when application stack exhausted, due to deep recursion.
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) .
A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.
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);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";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.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.
Mainly two types of java.lang.OutOfMemoryError in Java:
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.
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);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.
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.
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.
export JVM_ARGS=”-Xms1024m -Xmx1024m”
This is a tough solution and requires some time to analyze and find memory leaks.
This is a tough solution and requires some time to analyze and find memory leaks.
Tomcat 6.0 onward provides memory leak detection feature which can detect many common memory leaks on web-app perspective For Example:
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 .
https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html
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:
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.
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);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);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);Here are some common solutions for NumberFormatException:
https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html
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:
Note : There is convection to use Custom Exception name ends with word ‘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.
In this topic , You have learn about :
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.
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.
To know more about Junit, Mockito and exception solutions follow below links:
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:
To know more about Junit, Mockito and exception solutions follow below links:
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.
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.
To know more about Junit, Mockito and exception solutions follow below links:
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()
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;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.
To know more about Junit, Mockito and exception solutions follow below links:
WrongTypeOfReturnValue is RuntimeException and Subclass of MockitoException. It throws when :
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);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();
To know more about Junit, Mockito and exception solutions follow below links:
InvalidUseOfMatchersException is RuntimeException and subclass of MockitoException . It throws when trying to push behavior on object which is not mock.
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");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:
To know more about Junit, Mockito and exception solutions follow below links:
MissingMethodInvocationException is RuntimeException and subclass of MockitoException . It generally throws when:
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);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);To know more about Junit, Mockito and exception solutions follow below links:
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 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 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
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 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.
To know more about Elasticsearch Ingest Node, Logstash or Filebeat follow below links:
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 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.
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>}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.
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));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.
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);
![]() |
健壮的葡萄酒 · SpringBoot - 动态修改yml配置文件 12 小时前 |
![]() |
文雅的猴子 · SpringBoot动态更新yml文件 - code2roc 12 小时前 |
![]() |
朝气蓬勃的咖啡豆 · SpringBoot 动态加载配置文件及刷新Bean - 如.若 12 小时前 |
![]() |
近视的橙子 · 【学青会】泳将陈欣夺冠,广州体育代表团收获10金 3 天前 |
![]() |
卖萌的充电器 · 科技型中小企业评价-工业和信息化部火炬中心 5 月前 |
![]() |
才高八斗的玉米 · 著名围棋国手简介:林海峰九段-搜狐体育 10 月前 |