Skip to main content

Posts

Showing posts from August, 2021

Java throws Clause With Examples

Code in your method may throw exceptions that your method doesn’t handle. In that case you need to specify those exceptions along with the method declaration . That way calling method can provide exception handling mechanism for those exceptions. To specify the exceptions in your method declaration you can use throws keyword in Java . General form of throws keyword in Java type methodName(parameters) throws exception1, excpetion2...{ ... ... } try-catch block or throws You can handle the exception thrown in your method code with in the method by providing a try-catch block . If you want to delegate it to the caller method to provide exception handling mechanism, you can declare the exceptions using throws in Java . Then it is the responsibility of the calling method to provide exception handling mechanism. Of course caller method can also declare the exception using throws keyword and delegate it to the next method in the stack to handle it. As per the best practices

Checked Vs Unchecked Exception in Java

In this post we’ll see some of the differences between checked and unchecked exceptions in Java. Before going into checked exception Vs unchecked exception let’s try to understand which exception classifies as a checked exception and which one as unchecked. Table of contents Checked exception in Java Unchecked exception in Java Java exception class hierarchy Checked exception classes in Java Unchecked exception classes in Java Checked Vs Unchecked exception in Java Checked exception in Java While writing Java code, for some of the code lines compiler will complain about the unhandled exception. For example, if you create an InputStream object for reading a file in Java . InputStream is = new FileInputStream(new File("D:\\test.txt")); This statement will result in compile time error “ Unhandled exception type FileNotFoundException ”. This compile time error crops up because of the fact that the above statement may throw the type of except

Java String length() Method With Examples

To find length of a String you can use length() method of the Java String class . This method returns the count of characters in the String object including spaces. Java String length() method examples 1. In the examples there are two strings and length of those String is calculated using length() method. public class StringLength { public static void main(String[] args) { String str1 = "String length method"; //separated by 4 spaces String str2 = "Hello World"; System.out.println("Length of str1- " + str1.length()); System.out.println("Length of str2- " + str2.length()); } } Output Length of str1- 20 Length of str2- 14 2- Printing each character by iterating a String, using String’s length() method to limit the iteration. public class StringLength { public static void main(String[] args) { String str = "Hello"; for(int i = 0; i < str.length(); i++) { System.out.println(str.charAt(i

Compact Strings in Java 9

One of the enhancement in Java 9 is Compact String with the goal to make String class and related classes more space efficient while maintaining performance in most scenarios. Motivation for introducing Compact String in Java Till Java 8 String was stored internally as a character array with each character taking 2 bytes of space where UTF16 was used for character encoding. Data gathered from many different applications indicates that strings are a major component of heap usage, moreover most String objects contain only Latin-1 also called ISO-8859-1 characters. Latin-1 is a 8-bit character set meaning it needs 1 byte of space i.e. 1 byte less than UTF16 for each character. If strings can be stored using Latin-1 character encoding that will bring substantial reduction in memory usage by String objects. That is the motivation behind compact Strings in Java. Java 9 compact Strings Java 9 onwards this space efficiency optimization is brought to String class in Java using a new

Java StringJoiner Class With Method Examples

In Java 8 a new class StringJoiner has been added that can be used for joining the Strings using the specified delimiter. There is also an option to pass prefix and suffix to be added to the final joined String. Read Also: Java String join() Method With Examples Java StringJoiner class constructors StringJoiner(CharSequence delimiter) - Constructs a StringJoiner with no characters in it, with no prefix or suffix, and a copy of the supplied delimiter. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) - Constructs a StringJoiner with no characters in it using copies of the supplied prefix, delimiter and suffix. Java StringJoiner examples 1. Constructing a String with colon ":" as delimiter. public class JoinStrings { public static void main(String[] args) { // Specifying delimiter StringJoiner sj = new StringJoiner(":"); // adding values sj.add("Java"); sj.add("Python"); sj.a

Java StringBuilder With Method Examples

StringBuilder in Java is a mutable sequence of characters which means using this class you can create mutable strings (String that can be modified). The API provided by StringBuilder class is compatible with StringBuffer with one noticeable difference, with StringBuilder there is no guarantee of synchronization. When StringBuffer is being used by a single thread it is recommended that StringBuilder be used instead of StringBuffer as it will be faster as there is no synchronization overhead. Why is StringBuilder class required You may be wondering why is StringBuilder or StringBuffer class required when String class is already there with an extensive API. In the post String in Java we have already seen that String objects are immutable and their values cannot be changed after they are created. Because of this immutability property when you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains t

Why String is Immutable in Java

String in Java is immutable that brings us to the question why this decision to design String class as immutable. In this post we’ll see some of the reasons for this design decision. Java String objects are immutable Java String class is immutable which means once a String object is created it cannot be changed. When you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation. For example suppose there is String str- String str = “Hello”; That means str refers to the memory location where value "Hello" is stored. Now if you concatenate another value to this String and assign it to the same reference. Since original string can’t be modified because of String being immutable so this concatenation means a new String object is created with the modified value and str starts pointing to this new object. str = str.concat(" World"); As you can see s

Constant String Pool in Java

When a String object is created using string literal (value enclosed in double quotes) that String object is created in a part of memory known as constant string pool in Java . In this tutorial you’ll learn what is string pool in Java and how it optimizes memory when Strings are created. For another feature added to make String in Java more space efficient check this post- Compact Strings in Java 9 Java constant String pool There are two ways to create a String in Java - Using String literal Using new keyword When you create a String using String literal, for example String str = “hello” Memory for this string is created in a memory area knows as string pool in Java. This String pool is part of the heap memory. Now the question is why this String pool is required and how it optimizes memory usage? String is a special class in Java and one of the most used too. That is why the concept of constant String pool is used to minimize memory usage. Whenever any String

Java StringBuffer With Method Examples

StringBuffer in Java is a thread-safe, mutable sequence of characters thus using StringBuffer class you can create modifiable String objects . In the post String in Java we have already seen that String objects are immutable i.e. Strings are constant; their values cannot be changed after they are created. Because of this immutability property when you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation. That may lead to creation of lots of intermediate String objects if String is modified several times which in turn means more memory being used for these intermediate objects. Using StringBuffer object you can avoid this problem of creating several objects as it is mutable. Unsurprisingly the principal operations on a StringBuffer are the append and insert methods. Table of contents Important points about Java StringBuffer Java StringBuffer Constructors

Merging PDFs in Java Using PDFBox

In this post we’ll see a Java program to merge PDFs using PDFBox library. To know more about Apache PDFBox library and PDF examples in Java using PDFBox check this post- Generating PDF in Java Using PDFBox Tutorial Merging PDFs using PDFBox To merge PDFs, PDFBox library provides PDFMergerUtility class which takes a list of pdf documents and merge them, saving the result in a new document. Add the PDF files that are to be merged using addSource() method of the PDFMergerUtility class. Add the destination PDF file name using the setDestinationFileName() method of the PDFMergerUtility class. Following Java program shows how two PDF documents can be merged using PDFBox. import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.multipdf.PDFMergerUtility; public class PDFMerger { public static final String MERGED_PDF = "F://knpcode//result//PDFBox//Merged.pdf"; publi

Java String Class With Method Examples

In this tutorial we’ll learn about String in Java which is one of the most important and extensively used class in Java . Java String String in Java is a sequence of characters and it is represented by String class residing in java.lang Package. Whenever you create a String in Java it is created as an object of String class. String class provides many constructors and methods to create and manipulate strings, in this post and in successive posts we'll see application of some of the most used String methods. Table of contents Creating String in Java Creating Java String using string literal Creating String using new keyword Creating Formatted Strings Important points about String in Java Java String class methods Creating String in Java Since every string in Java is an instance of String class so a new String can of course be created using new operator. Apart from that String can also be created by assigning a string literal to a String instan