Java – Inter Thread Communication ”; Previous Next If you are aware of interprocess communication then it will be easy for you to understand interthread communication. Inter-thread Communication in Java Inter-thread communication is important when you develop an application where two or more threads exchange some information. Inter-thread communication is achieved by using the wait(), notify(), and notifyAll() methods of the Object class. Methods used for Inter-thread Communication There are three simple methods and a little trick which makes thread communication possible. All the three methods are listed below − Sr.No. Method & Description 1 public void wait() Causes the current thread to wait until another thread invokes the notify(). 2 public void notify() Wakes up a single thread that is waiting on this object”s monitor. 3 public void notifyAll() Wakes up all the threads that called wait( ) on the same object. These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context. Example of Inter-thread Communication in Java This examples shows how two threads can communicate using wait() and notify() method. You can create a complex system using the same concept. class Chat { boolean flag = false; public synchronized void Question(String msg) { if (flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = true; notify(); } public synchronized void Answer(String msg) { if (!flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = false; notify(); } } class T1 implements Runnable { Chat m; String[] s1 = { “Hi”, “How are you ?”, “I am also doing fine!” }; public T1(Chat m1) { this.m = m1; new Thread(this, “Question”).start(); } public void run() { for (int i = 0; i < s1.length; i++) { m.Question(s1[i]); } } } class T2 implements Runnable { Chat m; String[] s2 = { “Hi”, “I am good, what about you?”, “Great!” }; public T2(Chat m2) { this.m = m2; new Thread(this, “Answer”).start(); } public void run() { for (int i = 0; i < s2.length; i++) { m.Answer(s2[i]); } } } public class TestThread { public static void main(String[] args) { Chat m = new Chat(); new T1(m); new T2(m); } } When the above program is complied and executed, it produces the following result − Output Hi Hi How are you ? I am good, what about you? I am also doing fine! Great! Print Page Previous Next Advertisements ”;
Category: Java
Java – Write to File
Java – Write To Files ”; Previous Next Write To File in Java We can write to a file in Java using multiple ways. Following are three most popular ways to create a file in Java − Using FileOutputStream() constructor Using FileWriter.write() method Using Files.write() method Let”s take a look at each of the way to write file in Java. Write To File Using FileOutputStream Constructor FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn”t already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object. Syntax Following constructor takes a file name as a string to create an input stream object to write the file − OutputStream f = new FileOutputStream(“C:/java/hello.txt”) Syntax Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method then we”re writing bytes to the stream as follows − File f = new File(“C:/java/hello.txt”); OutputStream f = new FileOutputStream(f); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } Example: Write To File Using FileOutputStream Constructor Following is the example to demonstrate FileOutputStream to write a file in current directory − package com.tutorialspoint; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileTest { public static void main(String args[]) { try { byte bWrite [] = {65, 66, 67, 68, 69}; OutputStream os = new FileOutputStream(“test.txt”); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream(“test.txt”); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + ” “); } is.close(); } catch (IOException e) { System.out.print(“Exception”); } } } The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen. Output A B C D E Write To File Using FileWriter.write() Method FileWriter.write() method of FileWriter class allows to write chars to a file as shown below − Syntax // get an existing file File file = new File(“d://test//testFile1.txt”); // Write Content FileWriter writer = new FileWriter(file); writer.write(“Test data”); writer.close(); Example: Write To File Using FileWriter.write() Method Following is the example to demonstrate File to write to a file in given directory using FileWriter.write() method − package com.tutorialspoint; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileTest { public static void main(String args[]) { try { File file = new File(“d://test//testFile1.txt”); //Create the file if (file.createNewFile()) { System.out.println(“File is created!”); } else { System.out.println(“File already exists.”); } // Write Content FileWriter writer = new FileWriter(file); writer.write(“Test data”); writer.close(); // read content FileReader reader = new FileReader(file); int c; while ((c = reader.read()) != -1) { char ch = (char) c; System.out.print(ch); } } catch (IOException e) { System.out.print(“Exception”); } } } The above code would create file test.txt and would write given string in text format. Same would be the output on the stdout screen. Output File is created! Test data Write To File Using Files.write() Method Files.write() is a newer and more flexible method create a file and write content to a file in same command as shown below − Syntax String data = “Test data”; Files.write(Paths.get(“d://test/testFile3.txt”), data.getBytes()); List<String> lines = Arrays.asList(“1st line”, “2nd line”); Files.write(Paths.get(“file6.txt”), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); Example: Write To File Using Files.write() Method Following is the example to demonstrate File to create a file in given directory using Files.write() method − package com.tutorialspoint; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; public class FileTest { public static void main(String args[]) { try { String data = “Test data”; Files.write(Paths.get(“d://test/testFile3.txt”), data.getBytes()); List<String> lines = Arrays.asList(“1st line”, “2nd line”); Files.write(Paths.get( “file6.txt”), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); List<String> content = Files.readAllLines(Paths.get(“d://test/testFile3.txt”)); System.out.println(content); content = Files.readAllLines(Paths.get(“file6.txt”)); System.out.println(content); } catch (IOException e) { System.out.print(“Exception”); } } } The above code would create file test.txt and would write given strings in text format. Same would be the output on the stdout screen. Output [Test data] [1st line, 2nd line] Print Page Previous Next Advertisements ”;
Java – Built-in Exceptions
Java – Built-in Exceptions ”; Previous Next Built-in Exceptions in Java Java defines several exception classes inside the standard package java.lang. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. Types of Java Built-in Exceptions Built-in Exceptions in Java are categorized into two categories Checked Exceptions and Unchecked Exceptions. Checked Exceptions: The checked exceptions are handled by the programmer during writing the code, they can be handled using the try-catch block. These exceptions are checked at compile-time. Unchecked Exceptions: The unchecked exceptions are not handled by the programmer. These exceptions are thrown on run-time. Some of the unchecked exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc. Common Built-in Exceptions in Java Java defines several other types of exceptions that relate to its various class libraries. Following is the list of Java Unchecked and Checked RuntimeException. Sr.No. Exception & Description 1 ArithmeticException Arithmetic error, such as divide-by-zero. 2 ArrayIndexOutOfBoundsException Array index is out-of-bounds. 3 ArrayStoreException Assignment to an array element of an incompatible type. 4 ClassCastException Invalid cast. 5 IllegalArgumentException Illegal argument used to invoke a method. 6 IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. 7 IllegalStateException Environment or application is in incorrect state. 8 IllegalThreadStateException Requested operation not compatible with the current thread state. 9 IndexOutOfBoundsException Some type of index is out-of-bounds. 10 NegativeArraySizeException Array created with a negative size. 11 NullPointerException Invalid use of a null reference. 12 NumberFormatException Invalid conversion of a string to a numeric format. 13 SecurityException Attempt to violate security. 14 StringIndexOutOfBounds Attempt to index outside the bounds of a string. 15 UnsupportedOperationException An unsupported operation was encountered. 16 ClassNotFoundException Class not found. 17 CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. 18 IllegalAccessException Access to a class is denied. 19 InstantiationException Attempt to create an object of an abstract class or interface. 20 InterruptedException One thread has been interrupted by another thread. 21 NoSuchFieldException A requested field does not exist. 22 NoSuchMethodException A requested method does not exist. Examples of Java Built-in Exception Example 1: Demonstrating Arithmetic Exception Without try-catch In this example, we”re creating an error by dividing a value by 0. In this case, an unchecked exception will be raised. Being unchecked, compiler won”t complain and program will compile successfully. Once program runs, the exception will be thrown and JVM will intercepts the same and terminate the program before printing the last statement. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int b = 0; int c = 1/b; System.out.println(“c :” + c); } } Output Exception in thread “main” java.lang.ArithmeticException: / by zero at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8) Example 2: Demonstrating Arithmetic Exception With try-catch In this example, we”re handling unchecked exception. As first step, we”re generating an error by dividing a value by 0. In this case, an unchecked exception will be raised. We”re handling via ArithmeticException. Once program runs, the exception will be thrown and catch block will intercepts the same and print the last statement. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int b = 0; int c = 1/b; System.out.println(“c :” + c); } catch (ArithmeticException e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Example 3: Demonstrating No Such Method Exception In this example, we”re showcasing that a checked exception is to be handled by code otherwise compiler will complain. Whenever a method throws a checked exception, it has to either handle the exception or declare throws exception statement as we”re doing for getName() method. When we try to run the method, JVM complains the compilation problem as shown in output listed below: package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { ExcepTest excepTest = new ExcepTest(); excepTest.getName(); } private String getName() throws NoSuchMethodException { throw new NoSuchMethodException(); } } Output Exception in thread “main” java.lang.Error: Unresolved compilation problem: Unhandled exception type NoSuchMethodException at com.tutorialspoint.ExcepTest.main(ExcepTest.java:7) java_exceptions.htm Print Page Previous Next Advertisements ”;
Java – Boolean
Java – Boolean class ”; Previous Next Java Boolean Class The Java Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. Boolean Class Declaration in Java Following is the declaration for java.lang.Boolean class − public final class Boolean extends Object implements Serializable, Comparable<Boolean> Boolean Class Fields Following are the fields for java.lang.Boolean class − static Boolean FALSE − This is the Boolean object corresponding to the primitive value false. static Boolean TRUE − This is the Boolean object corresponding to the primitive value true. static Class<Boolean> TYPE − This is the Class object representing the primitive type boolean. Boolean Class Constructors Sr.No. Constructor & Description 1 Boolean(boolean value) This allocates a Boolean object representing the value argument. 2 Boolean(String s) This allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string “true”. Boolean Class Methods Sr.No. Method & Description 1 boolean booleanValue() This method returns the value of this Boolean object as a boolean primitive. 2 int compareTo(Boolean b) This method compares this Boolean instance with another. 3 boolean equals(Object obj) This method returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object. 4 static boolean getBoolean(String name) This method returns true if and only if the system property named by the argument exists and is equal to the string “true”. 5 int hashCode() This method returns a hash code for this Boolean object. 6 int hashCode(boolean value) This method returns a hash code for a given boolean value. It is compatible with Boolean.hashCode(). 7 static boolean logicalAnd(boolean a, boolean b) This method returns the result of applying the logical AND operator to the specified boolean operands. 8 static boolean logicalOr(boolean a, boolean b) This method returns the result of applying the logical OR operator to the specified boolean operands. 9 static boolean logicalXor(boolean a, boolean b) This method returns the result of applying the logical XOR operator to the specified boolean operands. 10 static boolean parseBoolean(String s) This method parses the string argument as a boolean. 11 String toString() This method returns a String object representing this Boolean”s value. 12 static String toString(boolean b) This method returns a String object representing the specified boolean. 13 static Boolean valueOf(boolean b) This method returns a Boolean instance representing the specified boolean value. 14 static Boolean valueOf(String s) This method returns a Boolean with a value represented by the specified string. Methods Inherited This class inherits methods from the following classes − java.lang.Object Example of Java Boolean Class The following example shows the usage of some important methods provided by Boolean class. package com.tutorialspoint; public class BooleanDemo { public static void main(String[] args) { // create 2 Boolean objects b1, b2 Boolean b1, b2; // assign values to b1, b2 b1 = Boolean.valueOf(true); b2 = Boolean.valueOf(false); // create an int res int res; // compare b1 with b2 res = b1.compareTo(b2); String str1 = “Both values are equal “; String str2 = “Object value is true”; String str3 = “Argument value is true”; if( res == 0 ) { System.out.println( str1 ); } else if( res > 0 ) { System.out.println( str2 ); } else if( res < 0 ) { System.out.println( str3 ); } } } Output Let us compile and run the above program, this will produce the following result − Object value is true Print Page Previous Next Advertisements ”;
Java – Wrapper Classes
Java – Wrapper Classes ”; Previous Next Why Java Wrapper Classes Required? Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc. Example int i = 5000; float gpa = 13.65f; double mask = 125; However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes. Java Wrapper Classes Wrapper classes are those whose objects wraps a primitive data type within them. In the java.lang package java provides a separate class for each of the primitive data types namely Byte, Character, Double, Integer, Float, Long, Short. At the time of instantiation, these classes accept a primitive datatype directly, or in the form of String. Wrapper classes provide methods to, convert primitive datatypes within them to String objects and, to compare them with other objects etc. Using wrapper classes, you can also add primitive datatypes to various Collection objects such as ArrayList, HashMap etc. You can also pass primitive values over a network using wrapper classes. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number. Object of Java Wrapper Class The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class. And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package. Creating Java Wrapper Class Objects In Java, to create a wrapper object, you have to use the wrapper class instead of the primitive data type. If you want to print the values of these objects, just print the object. Consider the below syntax: wrapper_class object_name = value; Example of Java Wrapper Class Following is an example of boxing and unboxing − In this example, we”ve showcase use of primitives and their operations using a wrapper class. In first statement we”ve assigned an int to an Integer object x which is termed as boxing. In second statment, we”re adding 10 to x which requires x to be unboxed as int and addition is performed and result is assigned back to the variable x and printed. public class Test { public static void main(String args[]) { Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x); } } Output 15 When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer. List of Java Wrapper Classes Following is the list of the wrapper classes that all the subclasses of the Number class − Sr.No. Class & Description 1 Boolean The Java Boolean class wraps a value of the primitive type boolean in an object. 2 Byte The Java Byte class wraps a value of the primitive type byte in an object. 3 Character The Java Character class wraps a value of the primitive type char in an object. 4 Double The Java Double class wraps a value of the primitive type double in an object. 5 Float The Java Float class wraps a value of the primitive type float in an object. 6 Integer The Java Float class wraps a value of the primitive type float in an object. 7 Long The Java Long class wraps a value of the primitive type long in an object. 8 Short The Java Short class wraps a value of the primitive type short in an object. Print Page Previous Next Advertisements ”;
Java – try-catch Block
Java Try Catch Block ”; Previous Next An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. Java try and catch A method catches an exception using a combination of the try and catch keywords. A try and catch block is placed around the code that might generate an exception. Code within a try and catch block is referred to as protected code, and the syntax for using try/catch looks like the following − The try Block The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. The catch Block A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Syntax of Java try and catch Block try { // Protected code } catch (ExceptionName e1) { // Catch block } Example of Java try and catch Block In following example, an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. As we”ve enclosed the code with a try block, this exception can be handled within next catch block which we”ve declared to catch ArrayIndexOutOfBoundsException. After catching the exception, we can take the corresponding action. Here we”re printing the details of the exception thrown. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple Catch Blocks With Java Try A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following − Syntax: Multiple Catch Blocks try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Example: Multiple Catch Blocks Here is code segment showing how to use multiple try/catch statements. In this example, we”re creating an error by dividing a value by 0. As it is not an ArrayIndexOutOfBoundsException, next catch block handles the exception and prints the details. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“ArrayIndexOutOfBoundsException thrown :” + e); }catch (Exception e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Catching Multiple Exceptions with Java Try and Catch Block Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it − Syntax: Catching Multiple Exceptions catch (IOException|FileNotFoundException ex) { logger.log(ex); throw ex; Example: Catching Multiple Exceptions Here is code segment showing how to use multiple catch in a single statement. In this example, we”re creating an error by dividing a value by 0. In single statement, we”re handling ArrayIndexOutOfBoundsException and ArithmeticException. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Print Page Previous Next Advertisements ”;
Java – Number
Java – Numbers Class ”; Previous Next Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc. Consider the below example: int i = 5000; float gpa = 13.65f; double mask = 125; Sometimes, there may be some situations where we need to use objects instead of primitive data types. To achieve this, Java provides wrapper classes. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number. Java Number Class The Number class is an abstract class in java.lang package. It is the superclass of the classes that represent numeric values convertible to primitive data types such as byte, short, int, long, float, and double. The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class. And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package. Following is an example of boxing and unboxing − Example In this example, we”ve showcase use of primitives and their operations using a wrapper class. In first statement we”ve assigned an int to an Integer object x which is termed as boxing. In second statment, we”re adding 10 to x which requires x to be unboxed as int and addition is performed and result is assigned back to the variable x and printed. public class Test { public static void main(String args[]) { Integer x = 5; // boxes int to an Integer object x = x + 10; // unboxes the Integer to a int System.out.println(x); } } This will produce the following result − Output 15 When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer. Java Number Class Methods Following is the list of the instance methods that all the subclasses of the Number class implements − Sr.No. Method & Description 1 byteValue() This method returns the value of the specified number as a byte. 2 doubleValue() This method returns the value of the specified number as a double. 3 floatValue() This method returns the value of the specified number as a float. 4 intValue() This method returns the value of the specified number as a int. 5 longValue() This method returns the value of the specified number as a long. 6 compareTo() Compares this Number object to the argument. 7 equals() Determines whether this number object is equal to the argument. 8 valueOf() Returns an Integer object holding the value of the specified primitive. 9 toString() Returns a String object representing the value of a specified number. 10 parseInt() This method is used to get the primitive data type of a certain String. 11 min() Returns the smaller of the two arguments. 12 max() Returns the larger of the two arguments. Java Number: Wrapper Classes Following is the list of the wrapper classes that all the subclasses of the Number class − Sr.No. Class & Description 1 Boolean The Java Boolean class wraps a value of the primitive type boolean in an object. 2 Byte The Java Byte class wraps a value of the primitive type byte in an object. 3 Character The Java Character class wraps a value of the primitive type char in an object. 4 Double The Java Double class wraps a value of the primitive type double in an object. 5 Float The Java Float class wraps a value of the primitive type float in an object. 6 Integer The Java Integer class wraps a value of the primitive type int in an object. 7 Long The Java Long class wraps a value of the primitive type long in an object. 8 Short The Java Short class wraps a value of the primitive type short in an object. Print Page Previous Next Advertisements ”;
Java – Singleton Class
Java – Singleton Class ”; Previous Next Java Singleton Design Pattern Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. Java Singleton Class This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. Advantages of Singleton Design Pattern Singleton design pattern saves memory because only one object instance is created and it also provides global access to its instance. Use of Singleton Design Pattern The singleton design pattern is used when you want to create such a class that has only one instance. It is mainly used in multithreading to create multi-threaded and database-related applications. Some of the designs where singleton design pattern is used: To create logger classes To create configuration management-related classes To create classes related to database connection pooling To create a class for the caching mechanism Java Singleton Class/Design Pattern: Examples Example 1 The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance(). The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance − package com.tutorialspoint; class Singleton { private static Singleton singleton = new Singleton( ); /* A private Constructor prevents any other * class from instantiating. */ private Singleton() { } /* Static ”instance” method */ public static Singleton getInstance( ) { return singleton; } /* Other methods protected by singleton-ness */ protected void demoMethod( ) { System.out.println(“demoMethod for singleton”); } } public class Tester { public static void main(String[] args) { Singleton tmp = Singleton.getInstance( ); tmp.demoMethod( ); } } If you compile and execute the above program, you will get the following result − Output demoMethod for singleton Example 2 Following implementation shows a classic Singleton design pattern. In this example, the ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method. Here, ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed. package com.tutorialspoint; class ClassicSingleton { private static ClassicSingleton instance = null; private ClassicSingleton() { // Exists only to defeat instantiation. } public static ClassicSingleton getInstance() { if(instance == null) { instance = new ClassicSingleton(); } return instance; } protected void demoMethod( ) { System.out.println(“demoMethod for singleton”); } } public class Tester { public static void main(String[] args) { ClassicSingleton tmp = ClassicSingleton.getInstance( ); tmp.demoMethod( ); } } If you compile and execute the above program, you will get the following result − Output demoMethod for singleton Example 3 Following implementation shows a threadsafe Singleton object creation. In this example, the ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method which we”ve made threadsafe using synchronized keyword. class ClassicSingleton { private static ClassicSingleton instance = null; private ClassicSingleton() { // Exists only to defeat instantiation. } public static synchronized ClassicSingleton getInstance() { if(instance == null) { instance = new ClassicSingleton(); } return instance; } protected void demoMethod( ) { System.out.println(“demoMethod for singleton”); } } public class Tester { public static void main(String[] args) { ClassicSingleton tmp = ClassicSingleton.getInstance( ); tmp.demoMethod( ); } } If you compile and execute the above program, you will get the following result − Output demoMethod for singleton Print Page Previous Next Advertisements ”;
Java – Enum Strings
Java – Enum String ”; Previous Next Java enum is a special construct to represents a group of pre-defined constant strings and provides clarity in code while used as constants in application code. By default, an enum string representation is the same as its declaration. Consider the following example: enum WEEKDAY { MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY, SATURDAY, SUNDAY } If we print the string representation of the above enum using the enum directly, using toString(), or using the name() method, it will print the same string as declared. System.out.println(WEEKDAY.MONDAY); System.out.println(WEEKDAY.MONDAY.toString()); System.out.println(WEEKDAY.MONDAY.name()); It will print the result as shown below: MONDAY MONDAY MONDAY Overriding Enum toString() Method Now in case, we want to change the default string representation to the enum”s string representation, we can create an overridden toString() method for each value of the enum constructor as shown below: enum WEEKDAY { MONDAY{ // overridden toString() method per value public String toString() { return “Day 1 of the Week: Monday”; } }; // or override toString() per enum // priority will be given to value level toString() method. public String toString() { return “Day 1 of the Week: Monday”; } } In this case, we”re overriding a default toString() method of the enum to give a custom description. Example: Overriding toString() Method in Java In this example, we”ve created an enum WEEKDAY. Using toString() method, we”re setting a custom description of enum value. package com.tutorialspoint; enum WEEKDAY { // enum value constants MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY, SATURDAY, SUNDAY; // override the toString() method for custom description @Override public String toString() { return switch(this) { case MONDAY: yield “Day 1”; case TUESDAY:yield “Day 2”; case WEDNESDAY:yield “Day 3”; case THRUSDAY:yield “Day 4”; case FRIDAY:yield “Day 5”; case SATURDAY:yield “DAY 6”; case SUNDAY: yield “Day 7″; }; } } public class Tester { public static void main(String[] args) { // invoke toString() internally System.out.println(WEEKDAY.MONDAY); // invoke toString explicitly System.out.println(WEEKDAY.TUESDAY.toString()); // invoke name() method to get the default name System.out.println(WEEKDAY.WEDNESDAY.name()); } } Output Let us compile and run the above program, this will produce the following result − Day 1 Day 2 WEDNESDAY Example: Overriding toString() Method Per Value in Java In this example, we”ve overridden toString() methods per value of this enum WEEKDAY. This way we can customize string representation per value in this way as well. package com.tutorialspoint; enum WEEKDAY { // override the toString() method for custom description MONDAY{ @Override public String toString() { return “Day 1”; } }, TUESDAY{ @Override public String toString() { return “Day 2”; } }, WEDNESDAY{ @Override public String toString() { return “Day 3”; } }, THRUSDAY{ @Override public String toString() { return “Day 4”; } }, FRIDAY{ @Override public String toString() { return “Day 5”; } }, SATURDAY{ @Override public String toString() { return “Day 6”; } }, SUNDAY{ @Override public String toString() { return “Day 7″; } }; } public class Tester { public static void main(String[] args) { // invoke toString() internally System.out.println(WEEKDAY.MONDAY); // invoke toString explicitly System.out.println(WEEKDAY.TUESDAY.toString()); // invoke name() method to get the default name System.out.println(WEEKDAY.WEDNESDAY.name()); } } Output Let us compile and run the above program, this will produce the following result − Day 1 Day 2 WEDNESDAY enum name() method is final and cannot be overridden. It can be used to get the default name of the enum while string representation of enum is overridden by toString() method. Print Page Previous Next Advertisements ”;
Java – Read Files
Java – Reading File ”; Previous Next Reading a File in Java We can read a file in Java using multiple ways. Following are three most popular ways to create a file in Java − Using FileInputStream() constructor Using FileReader.read() method Using Files.readAllLines() method Let”s take a look at each of the way to read file in Java. Reading File Using FileInputStream() Constructor FileInputStream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available. Syntax Following constructor takes a file name as a string to create an input stream object to read the file − InputStream f = new FileInputStream(“C:/java/hello.txt”); Syntax Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows − File f = new File(“C:/java/hello.txt”); InputStream f = new FileInputStream(f); Example: Reading File Using FileInputStream() Constructor Following is the example to demonstrate FileInputStream to read a file from current directory − package com.tutorialspoint; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileTest { public static void main(String args[]) { try { byte bWrite [] = {65, 66, 67, 68, 69}; OutputStream os = new FileOutputStream(“test.txt”); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream(“test.txt”); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + ” “); } is.close(); } catch (IOException e) { System.out.print(“Exception”); } } } The above code would create file test.txt and would write given numbers in binary format. Same would be read using FileInputStream and the output is printed on the stdout screen. Output A B C D E Reading File Using FileReader.read() Method FileReader.read() method of FileReader class allows to read chars from a file as shown below − Syntax // get an existing file File file = new File(“d://test//testFile1.txt”); // read content FileReader reader = new FileReader(file); int c; while ((c = reader.read()) != -1) { char ch = (char) c; System.out.print(ch); } Example: Reading File Using FileReader.read() Method Following is the example to demonstrate File to read a file in given directory using FileReader.read() method − package com.tutorialspoint; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileTest { public static void main(String args[]) { try { File file = new File(“d://test//testFile1.txt”); //Create the file if (file.createNewFile()) { System.out.println(“File is created!”); } else { System.out.println(“File already exists.”); } // Write Content FileWriter writer = new FileWriter(file); writer.write(“Test data”); writer.close(); // read content FileReader reader = new FileReader(file); int c; while ((c = reader.read()) != -1) { char ch = (char) c; System.out.print(ch); } } catch (IOException e) { System.out.print(“Exception”); } } } The above code would create file test.txt and would write given string in text format. Same would be the output on the stdout screen. Output File is created! Test data Reading File Using Files.readAllLines() Method Files.readAllLines() is a newer method to read all content of a file as a List of String as shown below − Syntax List<String> content = Files.readAllLines(Paths.get(“d://test/testFile3.txt”)); Example: Reading File Using Files.readAllLines() Method Following is the example to demonstrate File to read a file from a given directory using readAllLines() method − package com.tutorialspoint; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; public class FileTest { public static void main(String args[]) { try { String data = “Test data”; Files.write(Paths.get(“d://test/testFile3.txt”), data.getBytes()); List<String> lines = Arrays.asList(“1st line”, “2nd line”); Files.write(Paths.get( “file6.txt”), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); List<String> content = Files.readAllLines(Paths.get(“d://test/testFile3.txt”)); System.out.println(content); content = Files.readAllLines(Paths.get(“file6.txt”)); System.out.println(content); } catch (IOException e) { System.out.print(“Exception”); } } } The above code would create file test.txt and would write given strings in text format. Same would be the output on the stdout screen. Output [Test data] [1st line, 2nd line] Print Page Previous Next Advertisements ”;