Java – File Mismatch Method

Java – Files mismatch() Method ”; Previous Next Files mismatch() Method The mismatch() method is available in Files class from Java 12 onwards. It provides an easy way to compare two files. Syntax The syntax of the Files.mismatch() method is – public static long mismatch(Path path, Path path2) throws IOException Where If there is no mismatch then 1L is returned else position of first mismatch is returned. Mismatch is accounted in case if file sizes are not matching or byte contents are not matching. A file is considered identical in following cases. If both locations are pointing to same file. In case path is same and file is not present, files are considered same. If files are of same size and each byte is first files matches with corresponding bytes of second file. Parameters path − the path to the first file path2 − the path to the second file Return Value The position of the first mismatch or -1L if no mismatch. Exceptions IOException − If an I/O error occurs. SecurityException − In the case of the default provider, and a security manager is installed, the checkRead() method is invoked to check read access to both files. Files mismatch() Method Examples Example: No Mismatch in Files In this example, we”ve created two txt files in temporary directory and then written same content to both the files. Using Files.mismatch() method, both files are compared to be identical or not. Based on result returned, we”re printing the message. As both file contents are same, a message will be printed as “Files matched”. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class APITester { public static void main(String[] args) throws IOException { // create two files in temp directory Path path1 = Files.createTempFile(“file1”, “.txt”); Path path2 = Files.createTempFile(“file2”, “.txt”); // write same content to both the files Files.writeString(path1, “tutorialspoint”); Files.writeString(path2, “tutorialspoint”); // check files for Mismatch, // being same content, it should return -1. long mismatch = Files.mismatch(path1, path2); // print the message based on mismatch result if(mismatch > 1L) { System.out.println(“Mismatch occurred in file1 and file2 at : ” + mismatch); }else { System.out.println(“Files matched”); } // delete the files path1.toFile().deleteOnExit(); path2.toFile().deleteOnExit(); } } Output Let us compile and run the above program, this will produce the following result − Files matched Example: Mismatch Identification in Files In this example, we”ve created two txt files in temporary directory and then written different content to the files. Using Files.mismatch() method, both files are compared to be identical or not. Based on result returned, we”re printing the message. As both file contents are different, mismatch method returns the position of first mismatch which will be printed as the output. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class APITester { public static void main(String[] args) throws IOException { // create two files in temp directory Path path1 = Files.createTempFile(“file1”, “.txt”); Path path2 = Files.createTempFile(“file2”, “.txt”); // write same content to both the files Files.writeString(path1, “tutorialspoint”); Files.writeString(path2, “tutorialspoint Java 12”); // check files for Mismatch, // being different content, it should return index of first mismatch. long mismatch = Files.mismatch(path1, path2); // print the message based on mismatch result if(mismatch > 1L) { System.out.println(“Mismatch occurred in file1 and file2 at : ” + mismatch); }else { System.out.println(“Files matched”); } // delete the files path1.toFile().deleteOnExit(); path2.toFile().deleteOnExit(); } } Output Let us compile and run the above program, this will produce the following result − Mismatch occurred in file1 and file3 at : 14 Print Page Previous Next Advertisements ”;

Java – LinkedList

Java LinkedList Class ”; Previous Next Introduction The Java LinkedList class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. Class declaration Following is the declaration for java.util.LinkedList class − public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable Parameters Following is the parameter for java.util.LinkedList class − E − This is the type of elements held in this collection. Field Fields inherited from class java.util.AbstractList. Class constructors Sr.No. Constructor & Description 1 LinkedList() This constructs constructs an empty list. 2 LinkedList(Collection<? extends E> c) This constructs a list containing the elements of the specified collection, in the order they are returned by the collection”s iterator. Class methods Sr.No. Method & Description 1 boolean add(E e) This method appends the specified element to the end of this list. 2 boolean addAll(Collection<? extends E> c) This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection”s iterator. 3 void addFirst(E e) This method returns inserts the specified element at the beginning of this list. 4 void addLast(E e) This method returns appends the specified element to the end of this list. 5 void clear() This method removes all of the elements from this list. 6 Object clone() This method returns returns a shallow copy of this LinkedList. 7 boolean contains(Object o) This method returns true if this list contains the specified element. 8 Iterator<E> descendingIterator() This method returns an iterator over the elements in this deque in reverse sequential order. 9 E element() This method retrieves, but does not remove, the head (first element) of this list. 10 E get(int index) This method returns the element at the specified position in this list. 11 E getFirst() This method returns the first element in this list. 12 E getLast() This method returns the last element in this list. 13 int indexOf(Object o) This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. 14 int lastIndexOf(Object o) This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. 15 ListIterator<E> listIterator(int index) This method returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. 16 boolean offer(E e) This method adds the specified element as the tail (last element) of this list. 17 boolean offerFirst(E e) This method inserts the specified element at the front of this list. 18 boolean offerLast(E e) This method inserts the specified element at the end of this list. 19 E peek() This method retrieves, but does not remove, the head (first element) of this list. 20 E peekFirst() This method retrieves, but does not remove, the first element of this list, or returns null if this list is empty. 21 E peekLast() This method retrieves, but does not remove, the last element of this list, or returns null if this list is empty. 22 E poll() This method retrieves and removes the head (first element) of this list. 23 E pollFirst() This method retrieves and removes the first element of this list, or returns null if this list is empty. 24 E pollLast() This method retrieves and removes the last element of this list, or returns null if this list is empty. 25 E pop() This method pops an element from the stack represented by this list. 26 void push(E e) This method pushes an element onto the stack represented by this list. 27 E remove() This method retrieves and removes the head (first element) of this list. 28 E removeFirst() This method removes and returns the first element from this list. 29 boolean removeFirstOccurrence(Object o) This method removes the first occurrence of the specified element in this list (when traversing the list from head to tail). 30 E removeLast() This method removes and returns the last element from this list. 31 boolean removeLastOccurrence(Object o) This method removes the last occurrence of the specified element in this list (when traversing the list from head to tail). 32 E set(int index, E element) This method replaces the element at the specified position in this list with the specified element. 33 int size() This method returns the number of elements in this list. 34 Spliterator<E> spliterator() This method creates a late-binding and fail-fast Spliterator over the elements in this list. 35 Object[] toArray() This method returns an array containing all of the elements in this list in proper sequence (from first to last element). Methods inherited This class inherits methods from the following classes − java.util.AbstractSequentialList java.util.AbstractList java.util.AbstractCollection java.util.Object java.util.List java.util.Deque Adding element to a LinkedList Example The following example shows the usage of Java LinkedList add(E) method to add Integers. We”re adding couple of Integers to the LinkedList object using add() method calls per element and then print each element to show the elements added. package com.tutorialspoint; import java.util.LinkedList; public class LinkedListDemo { public static void main(String[] args) { // create an empty linked list LinkedList<Integer> linkedList = new LinkedList<>(); // use add() method to add elements in the linkedList linkedList.add(20); linkedList.add(30); linkedList.add(20); linkedList.add(30); linkedList.add(15); linkedList.add(22); linkedList.add(11); // let us print all the elements available in linkedList for (Integer number : linkedList) { System.out.println(“Number = ” + number); } } } Output Let us compile and run the above program, this will produce the following result − Number = 20 Number = 30 Number = 20 Number = 30 Number = 15 Number = 22 Number = 11 Print Page Previous Next Advertisements ”;

Java – LinkedHashMap

Java LinkedHashMap Class ”; Previous Next Introduction The Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration order. Following are the important points about LinkedHashMap − The class provides all of the optional Map operations, and permits null elements. The Iteration over a HashMap is likely to be more expensive. Class declaration Following is the declaration for java.util.LinkedHashMap class − public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> Parameters Following is the parameter for java.util.LinkedHashMap class − K − This is the type of keys maintained by this map. V − This is the the type of mapped values. Class constructors Sr.No. Constructor & Description 1 LinkedHashMap() This constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75). 2 LinkedHashMap(int initialCapacity) This constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75). 3 LinkedHashMap(int initialCapacity, float loadFactor) This constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor. 4 LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) This constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode. 5 LinkedHashMap(Map<? extends K,? extends V> m) This constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map. Class methods Sr.No. Method & Description 1 boolean containsValue(Object value) This method returns true if this map maps one or more keys to the specified value. 2 Set<Map.Entry<K,​V>> entrySet() This method returns a Set view of the mappings contained in this map. 3 V get​(Object key) This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 4 Set<K> keySet() This method returns a Set view of the keys contained in this map. 5 Collection<V> values() This method returns a Collection view of the values contained in this map. Methods inherited This class inherits methods from the following classes − java.util.HashMap java.util.AbstarctMap java.util.Object java.util.Map Getting a Value from LinkedHashMap Example The following example shows the usage of Java LinkedHashMap get() method to get a value based on a key from a Map. We”ve created a Map object of Integer,Integer. Then few entries are added, map is printed. Using get() method, a value is retrieved and printed. package com.tutorialspoint; import java.util.LinkedHashMap; public class LinkedHashMapDemo { public static void main(String args[]) { // create hash map LinkedHashMap<Integer,Integer> newmap = new LinkedHashMap<>(); // populate hash map newmap.put(1, 1); newmap.put(2, 2); newmap.put(3, 3); System.out.println(“Initial map elements: ” + newmap); System.out.println(“Value: ” + newmap.get(1)); } } Output Let us compile and run the above program, this will produce the following result. Initial map elements: {1=1, 2=2, 3=3} Value: 1 Print Page Previous Next Advertisements ”;

SWING Tutorial

SWING Tutorial PDF Version Quick Guide Resources Job Search Discussion JAVA provides a rich set of libraries to create Graphical User Interface in a platform independent way. In this tutorial, we”ll look at SWING GUI controls. Audience This tutorial is designed for software professionals who are willing to learn JAVA GUI Programming in simple and easy steps. This tutorial provides great understanding on JAVA GUI Programming concepts and after completing this tutorial you will be at an intermediate level of expertise, from where you can take yourself to higher levels of expertise. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Java programming language, text editor, execution of programs, etc. Frequently Asked Questions about Swing There are some very Frequently Asked Questions(FAQ) about Swing, this section tries to answer them briefly. Why Swing is used? Swing is used to create a graphical user interface for a Java-based application. An interface is a dashboard that allows a user to interact with the system. The Java applications created using Swing are compatible with the Windows operating system. Where to write Swing Code? The Swing code for a Java application is written inside the main method, constructor, or any other method of a Java class. Why Swing is called lightweight? The Java Swing is called lightweight because its components are entirely implemented in Java. It does not rely on operating system for displaying the graphical user interface components. What are the features of Swing? Here is the list of features of Java Swing − We can run Swing application on any Java enabled platform. Swing has very lightweight components. It has pre-built layout manager which helps in organizing various components. It provides very robust event handler. Swing controls are highly customizable and configurable. What are the different versions of Swing? Swing is a part of the Java Foundation Classes (JFC) and has been included in the Java Standard Edition since version 1.2. Any new updates to Swing would be interlinked to updates to the Java Standard Edition. How long should it take to learn Swing? Swing is very easy to learn. You can learn Swing in as little as two to three weeks. However, it can take months of practice before you feel comfortable using it. Determining how long it takes to learn Swing also depends on how you plan to use it. What is a Swing component? The Swing component is a set of graphical user interface controls which includes buttons, text fields, labels, menus, password fields and so on. What are the Swing methods? Swing methods are the built-in functions provided by the Swing API for creating and manipulating GUI components. Some of the frequently used methods are add(), setSize(), setLayout(), setVisible() and many more. Print Page Previous Next Advertisements ”;

JDBC Tutorial

JDBC Tutorial PDF Version Quick Guide Resources Job Search Discussion What is JDBC? JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Why to Learn JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. Making a connection to a database. Creating SQL or MySQL statements. Executing SQL or MySQL queries in the database. Viewing & Modifying the resulting records. Applications of JDBC Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as − Java Applications Java Applets Java Servlets Java ServerPages (JSPs) Enterprise JavaBeans (EJBs). All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. The JDBC 4.0 Packages The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC version at the time of writing this tutorial. It offers the main classes for interacting with your data sources. The new features in these packages include changes in the following areas − Automatic database driver loading. Exception handling improvements. Enhanced BLOB/CLOB functionality. Connection and statement interface enhancements. National character set support. SQL ROWID access. SQL 2003 XML data type support. Annotations. Interfaces and Classes of JDBC API Following is the list of mostly used interfaces and classes in JDBC API. DriverManager class − used to load a SQL driver to connect to database. Connection interface − used to make a connection to the database using database connection string and credentials. Statement interface − used to make a query to the database. PreparedStatement interface − used for a query with placeholder values. CallableStatement interface − used to called stored procedure or functions in database. ResultSet interface − represents the query results obtained from the database. ResultSetMetaData interface − represents the metadata of the result set. BLOB class − represents binary data stored in BLOB format in database table. CLOB class − represents text data like XML stored in database table Types of API in JDBC JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below − Type 1 − a JDBC bridge is used to access ODBC drivers installed on each client machine. For example, JDBC-ODBC Bridge driver in JDK 1.2. Type 2 − JDBC API calls are converted into native C/C++ API calls, which are unique to the database. These APIs are vendor specific and vendor provided driver is required to be installed. It is also called JDBC Native API. For example, Oracle Call Interface (OCI) driver. Type 3 − A three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server. It is also called JDBC-Net Pure Java driver. Type 4 − A pure Java-based driver communicates directly with the vendor”s database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. For example, MySQL”s Connector/J driver to connect to MySQL database. Audience This tutorial is designed for Java programmers who would like to understand the JDBC framework in detail along with its architecture and actual usage. Prerequisites Before proceeding with this tutorial, you should have a good understanding of Java programming language. As you are going to deal with RDBMS, you should have prior exposure to SQL and Database concepts. Print Page Previous Next Advertisements ”;

Java 12 – New Features

Java 12 – New Features ”; Previous Next Java 12 is a major feature release and it has brought many language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was releasd on Mar 2019, just six months after Java 11 release. Java 12 is a non-LTS release. New Features Following are the major new features which are introduced in Java 12. JVM Changes − JEP 189, JEP 346, JEP 344, and JEP 230. Switch Expressions − A preview feature allowing switch to use lambda expression. File.mismatch() method − File Comparison is made easy via mismatch method. Compact Number Formatting − Numbers can be formatted like 2K, 3M etc easily. Teeing Collector in Stream API − A merging operator on multiple collectors. String new methods − four new methods introduced to format a string. JEP 334 − JVM Constants API introduced. JEP 305 − A preview feature allowing pattern matching for instanceOf. Garbage Collection Enhancement Print Page Previous Next Advertisements ”;

JSP Tutorial

JSP Tutorial PDF Version Quick Guide Resources Job Search Discussion Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Server Pages to develop your web applications in simple and easy steps. Why to Learn JSP? JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI. Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having separate CGI files. JSP are always compiled before they are processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested. JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines. Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding. Applications of JSP As mentioned before, JSP is one of the most widely used language over the web. I”m going to list few of them here: JSP vs. Active Server Pages (ASP) The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. JSP vs. Pure Servlets It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. JSP vs. Server-Side Includes (SSI) SSI is really only intended for simple inclusions, not for “real” programs that use form data, make database connections, and the like. JSP vs. JavaScript JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc. JSP vs. Static HTML Regular HTML, of course, cannot contain dynamic information. Audience This tutorial has been prepared for the beginners to help them understand basic functionality of Java Server Pages (JSP) to develop your web applications. After completing this tutorial you will find yourself at a moderate level of expertise in using JSP from where you can take yourself to next levels. Prerequisites We assume you have little knowledge of how web applications work over HTTP, what is web server and what is web browsers. It will be great if you have some knowledge of web application development using any programming language. Frequently Asked Questions about JSP There are some very Frequently Asked Questions(FAQ) about JSP, this section tries to answer them briefly. What is the full form of JSP? The full form of JSP is JavaServer Pages. In some textbooks, you can find that JSP stands for Jakarta Server Pages. Is JSP front end or backend? JSP is a front-end technology used to develop a graphical user interface of a Java application. Which web servers support JSP technology? The JSP technology is supported by several web servers. The most popular are Apache Tomcat, GlassFish, Apache TomEE, WildFly and many more. What is JSP life cycle? There are four steps involved in JSP life cycle, which are − JSP Compilation − In this step, JSP is parsed and converted into a servlet for the compilation. JSP Initialization − The initialization is performed by invoking the jspInit() method. JSP Execution − In the following step, all the requests are handled. JSP Cleanup − The final step involves removal of JSP from use. Who invented JSP? JSP was released by Sun Microsystems in 1999. What is the syntax of JSP? The syntax of JSP is very simple, we simply need to start JSP tag with “<%” and end with “%>”. Then, save the JSP file with the extension “.jsp”. Which version of JSP is the latest? The latest version of JSP is 3.1 which was released on 31st April 2022. Which is better servlet or JSP? Both Servlet and JSP are used to create web applications using Java programming language. Both have their unique characteristic and functionality. Servlet is faster as compared to JSP, however, JSP is more flexible than servlet. How can we handle the exceptions in JSP? In JSP, we use errorPage and isErrorPage attributes to handle exceptions. How to learn JSP? Here is the summarized list of tips which you can follow to learn JSP − First and most important to make up your mind to learn JSP. Install the required IDE and other software that are essential for JSP on your computer system. Follow our tutorial step by step starting from the very beginning. Read more articles, watch online courses or buy a book on JSP to enhance your knowledge. Try to develop small software or projects using JSP. Print Page Previous Next Advertisements ”;

Java – Datetime Api

Java 8 – New Date-Time API ”; Previous Next With Java 8, a new Date-Time API is introduced to cover the following drawbacks of old date-time API. Not thread safe − java.util.Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable and does not have setter methods. Poor design − Default Date starts from 1900, month starts from 1, and day starts from 0, so no uniformity. The old API had less direct methods for date operations. The new API provides numerous utility methods for such operations. Difficult time zone handling − Developers had to write a lot of code to deal with timezone issues. The new API has been developed keeping domain-specific design in mind. Java 8 introduces a new date-time API under the package java.time. Following are some of the important classes introduced in java.time package. Local − Simplified date-time API with no complexity of timezone handling. Zoned − Specialized date-time API to deal with various timezones. Java Local Date-Time API LocalDate/LocalTime and LocalDateTime classes simplify the development where timezones are not required. Let”s see them in action. Example: Local Date-Time API import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.Month; public class Java8Tester { public static void main(String args[]) { Java8Tester java8tester = new Java8Tester(); java8tester.testLocalDateTime(); } public void testLocalDateTime() { // Get the current date and time LocalDateTime currentTime = LocalDateTime.now(); System.out.println(“Current DateTime: ” + currentTime); LocalDate date1 = currentTime.toLocalDate(); System.out.println(“date1: ” + date1); Month month = currentTime.getMonth(); int day = currentTime.getDayOfMonth(); int seconds = currentTime.getSecond(); System.out.println(“Month: ” + month +”day: ” + day +”seconds: ” + seconds); LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012); System.out.println(“date2: ” + date2); //12 december 2014 LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12); System.out.println(“date3: ” + date3); //22 hour 15 minutes LocalTime date4 = LocalTime.of(22, 15); System.out.println(“date4: ” + date4); //parse a string LocalTime date5 = LocalTime.parse(“20:15:30”); System.out.println(“date5: ” + date5); } } It should produce the following output − Current DateTime: 2014-12-09T11:00:45.457 date1: 2014-12-09 Month: DECEMBERday: 9seconds: 45 date2: 2012-12-10T11:00:45.457 date3: 2014-12-12 date4: 22:15 date5: 20:15:30 Java Zoned Date-Time API Zoned date-time API is to be used when time zone is to be considered. Let us see them in action. Example: Zoned Date-Time API import java.time.ZonedDateTime; import java.time.ZoneId; public class Java8Tester { public static void main(String args[]) { Java8Tester java8tester = new Java8Tester(); java8tester.testZonedDateTime(); } public void testZonedDateTime() { // Get the current date and time ZonedDateTime date1 = ZonedDateTime.parse(“2007-12-03T10:15:30+05:30[Asia/Karachi]”); System.out.println(“date1: ” + date1); ZoneId id = ZoneId.of(“Europe/Paris”); System.out.println(“ZoneId: ” + id); ZoneId currentZone = ZoneId.systemDefault(); System.out.println(“CurrentZone: ” + currentZone); } } It should produce the following output − date1: 2007-12-03T10:15:30+05:00[Asia/Karachi] ZoneId: Europe/Paris CurrentZone: Etc/UTC Java Chrono Units Enum java.time.temporal.ChronoUnit enum is added in Java 8 to replace the integer values used in old API to represent day, month, etc. Let us see them in action. Example: Chrono Units Enum import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class Java8Tester { public static void main(String args[]) { Java8Tester java8tester = new Java8Tester(); java8tester.testChromoUnits(); } public void testChromoUnits() { //Get the current date LocalDate today = LocalDate.now(); System.out.println(“Current date: ” + today); //add 1 week to the current date LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS); System.out.println(“Next week: ” + nextWeek); //add 1 month to the current date LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS); System.out.println(“Next month: ” + nextMonth); //add 1 year to the current date LocalDate nextYear = today.plus(1, ChronoUnit.YEARS); System.out.println(“Next year: ” + nextYear); //add 10 years to the current date LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES); System.out.println(“Date after ten year: ” + nextDecade); } } It should produce the following result − Current date: 2014-12-10 Next week: 2014-12-17 Next month: 2015-01-10 Next year: 2015-12-10 Date after ten year: 2024-12-10 Java Period and Duration With Java 8, two specialized classes are introduced to deal with the time differences. Period − It deals with date based amount of time. Duration − It deals with time based amount of time. Let us see them in action. Example: Period and Duration import java.time.temporal.ChronoUnit; import java.time.LocalDate; import java.time.LocalTime; import java.time.Duration; import java.time.Period; public class Java8Tester { public static void main(String args[]) { Java8Tester java8tester = new Java8Tester(); java8tester.testPeriod(); java8tester.testDuration(); } public void testPeriod() { //Get the current date LocalDate date1 = LocalDate.now(); System.out.println(“Current date: ” + date1); //add 1 month to the current date LocalDate date2 = date1.plus(1, ChronoUnit.MONTHS); System.out.println(“Next month: ” + date2); Period period = Period.between(date2, date1); System.out.println(“Period: ” + period); } public void testDuration() { LocalTime time1 = LocalTime.now(); Duration twoHours = Duration.ofHours(2); LocalTime time2 = time1.plus(twoHours); Duration duration = Duration.between(time1, time2); System.out.println(“Duration: ” + duration); } } It should produce the following output − Current date: 2014-12-10 Next month: 2015-01-10 Period: P-1M Duration: PT2H Java Temporal Adjusters TemporalAdjuster is used to perform the date mathematics. For example, get the “Second Saturday of the Month” or “Next Tuesday”. Let us see them in action. Example: Temporal Adjusters import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; import java.time.DayOfWeek; public class Java8Tester { public static void main(String args[]) { Java8Tester java8tester = new Java8Tester(); java8tester.testAdjusters(); } public void testAdjusters() { //Get the current date LocalDate date1 = LocalDate.now(); System.out.println(“Current date: ” + date1); //get the next tuesday LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.TUESDAY)); System.out.println(“Next Tuesday on : ” + nextTuesday); //get the second saturday of next month LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1); LocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY)).with(TemporalAdjusters.next(DayOfWeek.SATURDAY)); System.out.println(“Second Saturday on : ” + secondSaturday); } } It should produce the following result − Current date: 2014-12-10 Next Tuesday on : 2014-12-16 Second Saturday on : 2014-12-13 Backward Compatibility A toInstant() method is added to the original Date and Calendar objects, which can be used to convert them to the new Date-Time API. Use an ofInstant(Insant,ZoneId) method to get a LocalDateTime or ZonedDateTime object. Let us see them in action. Example of Backward Compatibility import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.Date; import java.time.Instant; import java.time.ZoneId; public class Java8Tester { public static void main(String args[]) { Java8Tester java8tester = new Java8Tester(); java8tester.testBackwardCompatability(); } public void testBackwardCompatability() { //Get the current date Date currentDate = new Date();

Java – Strings

Java – Strings Class ”; Previous Next Description Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Creating Strings The most direct way to create a string is to write − String greeting = “Hello world!”; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!”. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. Creating String from Char Array Example public class StringDemo { public static void main(String args[]) { char[] helloArray = { ”h”, ”e”, ”l”, ”l”, ”o”, ”.” }; String helloString = new String(helloArray); System.out.println( helloString ); } } This will produce the following result − Output hello. Note − The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. The following program is an example of length(), method String class. Getting Length of the String Example public class StringDemo { public static void main(String args[]) { String palindrome = “Dot saw I was Tod”; int len = palindrome.length(); System.out.println( “String Length is : ” + len ); } } This will produce the following result − Output String Length is : 17 Concatenating Strings The String class includes a method for concatenating two strings − string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in − “My name is “.concat(“Zara”); Strings are more commonly concatenated with the &plus; operator, as in − “Hello,” + ” world” + “!” which results in − “Hello, world!” Let us look at the following example − Concatenating String Example public class StringDemo { public static void main(String args[]) { String string1 = “saw I was “; System.out.println(“Dot ” + string1 + “Tod”); } } This will produce the following result − Output Dot saw I was Tod Creating Formatted Strings You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String”s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of − Formatted String Example System.out.printf(“The value of the float variable is ” + “%f, while the value of the integer ” + “variable is %d, and the string ” + “is %s”, floatVar, intVar, stringVar); You can write − String fs; fs = String.format(“The value of the float variable is ” + “%f, while the value of the integer ” + “variable is %d, and the string ” + “is %s”, floatVar, intVar, stringVar); System.out.println(fs); String Methods Here is the list of methods supported by String class − Sr.No. Method & Description 1 char charAt(int index) This method returns the char value at the specified index. 2 int codePointAt(int index) This method returns the character (Unicode code point) at the specified index. 3 int codePointBefore(int index) This method returns the character (Unicode code point) before the specified index. 4 int codePointCount(int beginIndex, int endIndex) This method returns the number of Unicode code points in the specified text range of this String. 5 int compareTo(String anotherString) This method compares two strings lexicographically. 6 int compareToIgnoreCase(String str) This method compares two strings lexicographically, ignoring case differences. 7 String concat(String str) This method concatenates the specified string to the end of this string. 8 boolean contains(CharSequence s) This method ceturns true if and only if this string contains the specified sequence of char values. 9 boolean contentEquals(CharSequence cs) This method compares this string to the specified CharSequence. 10 static String copyValueOf(char[] data) This method returns a String that represents the character sequence in the array specified. 11 boolean endsWith(String suffix) This method tests if this string ends with the specified suffix. 12 boolean equals(Object anObject) This method compares this string to the specified object. 13 boolean equalsIgnoreCase(String anotherString) This method compares this String to another String, ignoring case considerations. 14 static String format(String format, Object… args) This method returns a formatted string using the specified format string and arguments. 15 byte[] getBytes() This method encodes this String into a sequence of bytes using the platform”s default charset, storing the result into a new byte array. 16 void getChars(int srcBegin, int

Java – Stream API Improvements

Java – Stream API Improvements ”; Previous Next Streams were introduced in Java to help developers perform aggregate operations from a sequence of objects. With Java 9, few more methods are added to make streams better. takeWhile(Predicate Interface) Method Syntax default Stream<T> takeWhile(Predicate<? super T> predicate) takeWhile method takes all the values until the predicate returns false. It returns, in case of ordered stream, a stream consisting of the longest prefix of elements taken from this stream matching the given predicate. Example package com.tutorialspoint; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { Stream.of(“a”,”b”,”c”,””,”e”,”f”).takeWhile(s->!s.isEmpty()) .forEach(System.out::print); } } Output takeWhile method takes all a, b, and c values, then once string is empty, it stopped executing. abc dropWhile(Predicate Interface) Syntax default Stream<T> dropWhile(Predicate<? super T> predicate) dropWhile method throw away all the values at the start until the predicate returns true. It returns, in case of ordered stream, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements matching the given predicate. Example package com.tutorialspoint; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { Stream.of(“a”,”b”,”c”,””,”e”,”f”).dropWhile(s-> !s.isEmpty()) .forEach(System.out::print); System.out.println(); Stream.of(“a”,”b”,”c”,””,”e”,””,”f”).dropWhile(s-> !s.isEmpty()) .forEach(System.out::print); } } Output dropWhile method drops a,b and c values, then once string is empty, it takes all the values. ef ef iterate Method Syntax static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) iterate method now has hasNext predicate as parameter which stops the loop once hasNext predicate returns false. Example package com.tutorialspoint; import java.util.stream.IntStream; public class Tester { public static void main(String[] args) { IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println); } } Output 3 6 9 ofNullable Syntax static <T> Stream<T> ofNullable(T t) ofNullable method is introduced to prevent NullPointerExceptions and to avoid null checks for streams. This method returns a sequential Stream containing single element, if non-null, otherwise returns an empty Stream. Example package com.tutorialspoint; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { long count = Stream.ofNullable(100).count(); System.out.println(count); count = Stream.ofNullable(null).count(); System.out.println(count); } } Output 1 0 Print Page Previous Next Advertisements ”;