Java – How to Use Comparable? ”; Previous Next Java Comparable Interface Comparable interface is a very important interface which can be used by Java Collections to compare custom objects and sort them. Using comparable interface, we can sort our custom objects in the same way how wrapper classes, string objects get sorted using Collections sorting methods. Using comparable, we can make the elements as sortable. Comparable Interface Methods The Comparable interface defines a methods: compareTo(). The compareTo() method, shown here, compares the passed object for order − The compare() Method int compareTo(Object obj) obj is the object to be compared. This method returns zero if the objects are equal. It returns a positive value if current object is greater than obj. Otherwise, a negative value is returned. By overriding compareTo(), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can implement a comparison method that reverses the outcome of a comparison. The equals() Method The equals() method, shown here, tests whether an object equals the invoking comparator − boolean equals(Object obj) obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals() is unnecessary, and most simple comparators will not do so. Comparable Interface to Sort Custom Object In this example, we”re using Comparable interface to sort a custom object Dog based on comparison criterias. Example import java.util.ArrayList; import java.util.Collections; import java.util.List; class Dog implements Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { // compare the name using alphabetical order return (this.name).compareTo(d.name); } @Override public String toString() { return this.name + “,” + this.age; } } public class ComparableDemo { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<>(); list.add(new Dog(“Shaggy”, 3)); list.add(new Dog(“Lacy”, 2)); list.add(new Dog(“Roger”, 10)); list.add(new Dog(“Tommy”, 4)); list.add(new Dog(“Tammy”, 1)); Collections.sort(list); // Sorts the array list System.out.println(“Sorted by name:”); // printing the sorted list of names System.out.print(list); } } Output This will produce the following result − Sorted by name: [Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4] Note − Sorting of the Arrays class is as the same as the Collections. Comparable Interface to Sort Custom Object in Reverse Order Example In this example, we”re using Collections.reverseOrder() method to reverse sort the Dog objects. import java.util.ArrayList; import java.util.Collections; import java.util.List; class Dog implements Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return (this.name).compareTo(d.name); } @Override public String toString() { return this.name + “,” + this.age; } } public class ComparableDemo { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<>(); list.add(new Dog(“Shaggy”, 3)); list.add(new Dog(“Lacy”, 2)); list.add(new Dog(“Roger”, 10)); list.add(new Dog(“Tommy”, 4)); list.add(new Dog(“Tammy”, 1)); Collections.sort(list, Collections.reverseOrder()); // Sorts the array list System.out.println(“Sorted by name in reverse order:”); // printing the sorted list of names System.out.print(list); } } Output This will produce the following result − Sorted by name in reverse order: [Tommy,4, Tammy,1, Shaggy,3, Roger,10, Lacy,2] Example In this example, we”re using Comparable interface to sort Dog objects based on their ages. import java.util.ArrayList; import java.util.Collections; import java.util.List; class Dog implements Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; } // Overriding the compareTo method public int compareTo(Dog d) { return this.age – d.age; } @Override public String toString() { return this.name + “,” + this.age; } } public class ComparableDemo { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<>(); list.add(new Dog(“Shaggy”, 3)); list.add(new Dog(“Lacy”, 2)); list.add(new Dog(“Roger”, 10)); list.add(new Dog(“Tommy”, 4)); list.add(new Dog(“Tammy”, 1)); Collections.sort(list); // Sorts the array list System.out.println(“Sorted by age:”); // printing the sorted list by age System.out.print(list); } } Output This will produce the following result − Sorted by age: [Tammy,1, Lacy,2, Shaggy,3, Tommy,4, Roger,10] Print Page Previous Next Advertisements ”;
Category: Java
Java – REPL (JShell)
Java – REPL (JShell) ”; Previous Next Introduction to REPL (JShell) REPL stands for Read Evaluate Print Loop. JShell was introduced in Java 9 which is an interactive console. JShell as REPL allows to run arbitrary snippet of java code in console without need to save and compile java code file. This facility is very important to test codes quickly like evaluating regular expression, checking formating of strings, date formats etc. JShell reads each line entered, evaluates it and then print the result and then again becomes ready for next set of input. Advantages of Using JShell This capability of JShell gives developers following advantages – No editor is needed to write a Java program. JShell itself works as editor and executes the Java code. Using JShell, there is no requirement to save a Java file, compile and execute code cycle. Code can be directly tested in JShell without saving anything. Compilation is not needed prior to execution of code. If any compile-time or runtime error occurs, start fresh. Running JShell Open command prompt and type jshell. D:test>jshell | Welcome to JShell — Version 20.0.2 | For an introduction type: /help intro With JShell, we can test methods, classes, expressions as well. In following examples, let”s explore some of the features of JShell. Create and Invoke Method in JShell Following snippet showing a sample “Hello World” program in JShell. Here, we”ve created a method greet() which has a single statement to print a message as “Hello World!”. As next, we”ve invoked the method greet() and result is printed on the console. Hello World Example in JShell jshell> void greet() { System.out.println(“Hello World!”);} | created method greet() jshell> greet() Hello World! jshell> Creating Variables in JShell Following snippet shows how to create variables in JShell. semi-colon is optional. We can create objects as well in JShell. If a variable is not initialized then it is given a default value or null if it is an object reference. Once a variable is created, it can be used as shown in the last statement where we”ve used the string variable to print its value. Example jshell> int i = 10 i ==> 10 jshell> String name = “Mahesh”; name ==> “Mahesh” jshell> Date date = new Date() date ==> Fri Feb 02 14:52:49 IST 2024 jshell> long l l ==> 0 jshell> List list list ==> null jshell> name name ==> “Mahesh” Evaluate Expression in JShell Following snippet shows how to evaluate an expression using JShell. Here we”ve passed a statement which returns a formatted string. JShell automatically created a String variable $9 and assigned it the result. As next statement, we”ve printed. Example jshell> String.format(“%d pages read.”, 10); $9 ==> “10 pages read.” jshell> $9 $9 ==> “10 pages read.” Jshell Built-In Commands JShell provides various commands to list the variables created, methods created, imports used etc. Some of the important JShell commands are – /drop – This command drops code snippets identified by name, ID, or ID range. /edit – This command opens an editor. /env – This command displays the environment settings. /exit – This command exists from the tool. /history – This command displays the history of the tool. /help – This command displays the command”s help. /imports – This command displays the current active imports. Example: Demonstrating /help Command We can view all commands using /help option. jshell> /help | Type a Java language expression, statement, or declaration. | Or type one of the following commands: | /list [<name or id>|-all|-start] | list the source you have typed | /edit <name or id> | edit a source entry | /drop <name or id> | delete a source entry | /save [-all|-history|-start] <file> | Save snippet source to a file | /open <file> | open a file as source input | /vars [<name or id>|-all|-start] | list the declared variables and their values | /methods [<name or id>|-all|-start] | list the declared methods and their signatures | /types [<name or id>|-all|-start] | list the type declarations … Example: Demonstrating /vars Command In following example, we”ve used /vars command to print the variables declared during a session. C:UsersMahesh>jshell | Welcome to JShell — Version 20.0.2 | For an introduction type: /help intro jshell> int i = 10 i ==> 10 jshell> String name=”Mahesh” name ==> “Mahesh” jshell> /vars | int i = 10 | String name = “Mahesh” jshell> Example: Demonstrating /imports Command We can use /imports command to check the imports available in JShell as shown below: jshell> /imports | import java.io.* | import java.math.* | import java.net.* | import java.nio.file.* | import java.util.* | import java.util.concurrent.* | import java.util.function.* | import java.util.prefs.* | import java.util.regex.* | import java.util.stream.* jshell> Exiting JShell We can use /exit command to exit JShell as shown below: Example jshell> /exit | Goodbye C:UsersMahesh> Print Page Previous Next Advertisements ”;
Java – Naming Thread
Java – Naming a Thread with Examples ”; Previous Next Name a Thread while Implementing a Runnable Interface If your class is intended to be executed as a thread and is implementing a Runnable interface. You will need to instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Naming a Thread while extending a Thread Class The second way to create a thread is to create a new class that extends Thread class. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. In order to name the thread, we need to call the super class Thread constructor with name. class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); … } … } Example 1 Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, State: Running Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Example 2 In this example, we”ve created a ThreadDemo class which extends Thread class. We”re not passing any name to the Thread and it will print the default names assigned to the threads by the system. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); thread1.start(); thread2.start(); } } Output Thread: main, State: New Thread: main, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-0, State: Running Thread: Thread-0, 4 Thread: Thread-0, 3 Thread: Thread-1, State: Running Thread: Thread-0, 2 Thread: Thread-1, 4 Thread: Thread-0, 1 Thread: Thread-1, 3 Thread: Thread-0, State: Dead Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Print Page Previous Next Advertisements ”;
Java – Data Structures
Java – Data Structures ”; Previous Next The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes − Enumeration BitSet Vector Stack Dictionary Hashtable Properties All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which is discussed in the next chapter − The Enumeration The Enumeration interface isn”t itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure. For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements. Example Following is an example showing usage of Enumeration for a Vector. import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration<String> days; Vector<String> dayNames = new Vector<>(); dayNames.add(“Sunday”); dayNames.add(“Monday”); dayNames.add(“Tuesday”); dayNames.add(“Wednesday”); dayNames.add(“Thursday”); dayNames.add(“Friday”); dayNames.add(“Saturday”); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } } } Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday To have more detail about this interface, check The Enumeration. The BitSet The BitSet class implements a group of bits or flags that can be set and cleared individually. This class is very useful in cases where you need to keep up with a set of Boolean values; you just assign a bit to each value and set or clear it as appropriate. Example The following program illustrates several of the methods supported by BitSet data structure − import java.util.BitSet; public class BitSetDemo { public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i = 0; i < 16; i++) { if((i % 2) == 0) bits1.set(i); if((i % 5) != 0) bits2.set(i); } System.out.println(“Initial pattern in bits1: “); System.out.println(bits1); System.out.println(“nInitial pattern in bits2: “); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println(“nbits2 AND bits1: “); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println(“nbits2 OR bits1: “); System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println(“nbits2 XOR bits1: “); System.out.println(bits2); } } Output Initial pattern in bits1: {0, 2, 4, 6, 8, 10, 12, 14} Initial pattern in bits2: {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} bits2 AND bits1: {2, 4, 6, 8, 12, 14} bits2 OR bits1: {0, 2, 4, 6, 8, 10, 12, 14} bits2 XOR bits1: {} The Vector The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements. Like an array, elements of a Vector object can be accessed via an index into the vector. The nice thing about using the Vector class is that you don”t have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary. Example The following program illustrates several of the methods supported by Vector collection − import java.util.*; public class VectorDemo { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println(“Initial size: ” + v.size()); System.out.println(“Initial capacity: ” + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println(“Capacity after four additions: ” + v.capacity()); v.addElement(new Double(5.45)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println(“Current capacity: ” + v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println(“First element: ” + (Integer)v.firstElement()); System.out.println(“Last element: ” + (Integer)v.lastElement()); if(v.contains(new Integer(3))) System.out.println(“Vector contains 3.”); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println(“nElements in vector:”); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + ” “); System.out.println(); } } Output Initial size: 0 Initial capacity: 3 Capacity after four additions: 5 Current capacity: 5 Current capacity: 7 Current capacity: 9 First element: 1 Last element: 12 Vector contains 3. Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12 The Stack The Stack class implements a last-in-first-out (LIFO) stack of elements. You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others. When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off. Example The following program illustrates several of the methods supported by Stack collection − import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println(“push(” + a + “)”); System.out.println(“stack: ” + st); } static void showpop(Stack st) { System.out.print(“pop -> “); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println(“stack: ” + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println(“stack: ” + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println(“empty stack”); } } } Output stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack The Dictionary The Dictionary class is an abstract class that defines a data structure for mapping keys to values. This is useful in cases where you want to be able to access data via a particular key rather than an integer index. Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation. Example The following example shows the usage of Java Dictionary keys() method. We”re creating a dictionary instance using Hashtable object of Integer, Integer. Then we”ve added few elements to it. An enumeration is retrieved using keys() method and enumeration is then iterated to print the keys of the dictionary. package com.tutorialspoint; import java.util.Enumeration; import java.util.Dictionary; import java.util.Hashtable; public class DictionaryDemo { public static void main(String[] args) { // create a new hashtable Dictionary<Integer, Integer> dictionary = new Hashtable<>();
Java – Nested try Block
Java – Nested Try Block ”; Previous Next Nested Try Block A try block can be nested within another try block. This structure is termed as Nested try block. Whenever an exception is raised within a nested try block, its exception is pushed to Stack. The exception propagates from child to parent try block and so on. Syntax The syntax for nested catch blocks looks like the following − try { // parent try block try { // child try block } catch(ExceptionType1 e1){ // child catch block } } catch (ExceptionType2 e1) { // parent catch block } The previous statements demonstrate two try/catch blocks, but you can have any number of them. If an exception occurs in the protected child code, the exception is thrown to the catch block of the child list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes up to the parent 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. Pointer To Remember While Using Nested Try Block Child catch block should have specific exception for better code clarity. Parent catch block can have more generic exception handled so that if child catch block is not able to handle the exception then parent catch block can handle it. There in no restriction on exception hiearchy to be used in child vs parent catch block. If a exception is handled correctly in child catch block, then in parent, another exception can be raised and handled. Java Nested Try Block Example Here is code segment showing how to use nested try/catch statements. In this example, we”re creating an error by dividing a value by 0 in a nested try block. The child catch block is handling the exception and printing the same. Now in parent try block, we”re again creating an error by using an invalid array index while accessing array elements and exception is raised. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; try { int b = 0; int c = 1/b; }catch(Exception e) { System.out.println(“Exception thrown: ” + e); } 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.ArithmeticException: / by zero Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block More Examples Example 1 In this code segment, we”re showing how to use another example of nested try/catch statements. In this example, we”re creating an error by dividing a value by 0 in nested try block but we”re not handling in corresponding catch block. As parent try block is handling the exception raised as generic exception, it captures the exception raised by child catch block and prints the same. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; try { int b = 0; int c = 1/b; }catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown: ” + e); } System.out.println(“Access element three :” + a[3]); } 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 Example 2 In this code segment, we”re showing the case of nested try/catch statements where exceptions are not handled by any of the catch block. In this example, we”re creating an error by dividing a value by 0 in nested try block but we”re not handling this kind of exception in any catch block. Now JVM will capture the exception and terminate the program without printing the last statement. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; try { int b = 0; int c = 1/b; }catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown: ” + e); } 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 in thread “main” java.lang.ArithmeticException: / by zero at com.tutorialspoint.ExcepTest.main(ExcepTest.java:10) Print Page Previous Next Advertisements ”;
Java – Socket Class
Java – Socket Class with Examples ”; Previous Next Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket. The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client”s OutputStream is connected to the server”s InputStream, and the client”s InputStream is connected to the server”s OutputStream. The Java Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method. Declaration public class Socket extends Object implements Closeable Constructors Sr.No. Method & Description 1 public Socket() This method creates an unconnected socket, with the system-default type of SocketImpl. 2 public Socket(String host, int port) throws UnknownHostException, IOException This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server. 3 public Socket(String host,int port,InetAddress localAddr,int localPort) throws IOException This method creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied. 4 public Socket(InetAddress host, int port) throws IOException This method is identical to the previous constructor, except that the host is denoted by an InetAddress object. 5 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException. This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String. 6 public Socket(Proxy proxy) This method creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings. When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port. Methods Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket object, so these methods can be invoked by both the client and the server. Sr.No. Method & Description 1 void bind(SocketAddress bindpoint) Binds the socket to a local address. 2 void close() Closes this socket. 3 void connect(SocketAddress endpoint) Connects this socket to the server. 4 void connect(SocketAddress endpoint, int timeout) Connects this socket to the server with a specified timeout value. 5 SocketChannel getChannel() Returns the unique SocketChannel object associated with this socket, if any. 6 InetAddress getInetAddress() Returns the address to which the socket is connected. 7 InputStream getInputStream() Returns an input stream for this socket. 8 boolean getKeepAlive() Tests if SO_KEEPALIVE is enabled. 9 InetAddress getLocalAddress() Gets the local address to which the socket is bound. 10 int getLocalPort() Returns the local port number to which this socket is bound. 11 SocketAddress getLocalSocketAddress() Returns the address of the endpoint this socket is bound to. 12 boolean getOOBInline() Tests if SO_OOBINLINE is enabled. 13 <T> T getOption(SocketOption<T> name) Returns the value of a socket option. 14 OutputStream getOutputStream() Returns an output stream for this socket. 15 int getPort() Returns the remote port number to which this socket is connected. 16 int getReceiveBufferSize() Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket. 17 SocketAddress getRemoteSocketAddress() Returns the address of the endpoint this socket is connected to, or null if it is unconnected. 18 boolean getReuseAddress() Tests if SO_REUSEADDR is enabled. 19 int getSendBufferSize() Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket. 20 int getSoLinger() Returns setting for SO_LINGER. 21 int getSoTimeout() Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity). 22 boolean getTcpNoDelay() Tests if TCP_NODELAY is enabled. 23 int getTrafficClass() Gets traffic class or type-of-service in the IP header for packets sent from this Socket 24 boolean isBound() Returns the binding state of the socket. 25 boolean isClosed() Returns the closed state of the socket. 26 boolean isConnected() Returns the connection state of the socket. 27 boolean isInputShutdown() Returns whether the read-half of the socket connection is closed. 28 boolean isOutputShutdown() Returns whether the write-half of the socket connection is closed. 29 void sendUrgentData(int data) Send one byte of urgent data on the socket. 30 void setKeepAlive(boolean on) Enable/disable SO_KEEPALIVE. 31 void setOOBInline(boolean on) Enable/disable SO_OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. 32 <T> Socket setOption(SocketOption<T> name, T value) Sets the value of a socket option. 33 void setPerformancePreferences(int connectionTime, int latency, int bandwidth) Sets performance preferences for this socket. 34 void setReceiveBufferSize(int size) Sets the SO_RCVBUF option to the specified value for this Socket. 35 void setReuseAddress(boolean on) Enable/disable the SO_REUSEADDR socket option. 36 void setSendBufferSize(int size) Sets the SO_SNDBUF option to the specified value for this Socket. 37 static void setSocketImplFactory(SocketImplFactory fac) Sets the client socket implementation factory for the application. 38 void setSoLinger(boolean on, int linger) Enable/disable SO_LINGER with the specified linger time in seconds. 39 void setSoTimeout(int timeout) Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. 40 void setTcpNoDelay(boolean on) Enable/disable TCP_NODELAY (disable/enable Nagle”s algorithm). 41 void setTrafficClass(int tc) Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket. 42 void shutdownInput() Places the input stream
Java – Iterators
Java – How to Use Iterator? ”; Previous Next Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps − Obtain an iterator to the start of the collection by calling the collection”s iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ). For collections that implement List, you can also obtain an iterator by calling ListIterator. The Methods Declared by Iterator Sr.No. Method & Description 1 boolean hasNext( ) Returns true if there are more elements. Otherwise, returns false. 2 Object next( ) Returns the next element. Throws NoSuchElementException if there is not a next element. 3 void remove( ) Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ). The Methods Declared by ListIterator Sr.No. Method & Description 1 void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next( ). 2 boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false. 3 boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false. 4 Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element. 5 int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list. 6 Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. 7 int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1. 8 void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. 9 void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ). Example 1 Here is an example demonstrating Iterator. It uses an ArrayList object, but the general principles apply to any type of collection. import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorDemo { public static void main(String args[]) { // Create an array list List<String> al = new ArrayList<>(); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); // Use iterator to display contents of al System.out.print(“Original contents of al: “); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } System.out.println(); } } Output Original contents of al: C A E B D F Example 2 Here is an example demonstrating ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection. Of course, ListIterator is available only to those collections that implement the List interface. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IteratorDemo { public static void main(String args[]) { // Create an array list List<String> al = new ArrayList<>(); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); // Use iterator to display contents of al System.out.print(“Original contents of al: “); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } } } Output Original contents of al: C A E B D F Example 3 Here is an example demonstrating ListIterator to modify the list while iterating. It uses an ArrayList object, but the general principles apply to any type of collection. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IteratorDemo { public static void main(String args[]) { // Create an array list List<String> al = new ArrayList<>(); // add elements to the array list al.add(“C”); al.add(“A”); al.add(“E”); al.add(“B”); al.add(“D”); al.add(“F”); // Use iterator to display contents of al System.out.print(“Original contents of al: “); Iterator<String> itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } System.out.println(); // Modify objects being iterated ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) { Object element = litr.next(); litr.set(element + “+”); } System.out.print(“Modified contents of al: “); itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + ” “); } System.out.println(); // Now, display the list backwards System.out.print(“Modified list backwards: “); while(litr.hasPrevious()) { Object element = litr.previous(); System.out.print(element + ” “); } System.out.println(); } } Output Original contents of al: C A E B D F Modified contents of al: C+ A+ E+ B+ D+ F+ Modified list backwards: F+ D+ B+ E+ A+ C+ Print Page Previous Next Advertisements ”;
Java – Creating a Thread
Java – Creating a Thread ”; Previous Next There are two different ways to create a thread in Java. We have listed them as follows: By Implementing a Runnable Interface By Extending a Thread Class Create a Thread by Implementing a Runnable Interface If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps − Step 1 As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) Step 2 As a second step, you will instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread. Step 3 Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Example to Create a Thread by Implementing a Runnable Interface In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. package com.tutorialspoint; class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name) { threadName = name; System.out.println(“Thread: ” + threadName + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + threadName + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); } System.out.println(“Thread: ” + threadName + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) { RunnableDemo runnableDemo1 = new RunnableDemo( “Thread-1”); RunnableDemo runnableDemo2 = new RunnableDemo( “Thread-2″); Thread thread1 = new Thread(runnableDemo1); Thread thread2 = new Thread(runnableDemo2); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Create a Thread by Extending a Thread Class The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 You will need to override run() method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method − public void run( ) Step 2 Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start( ); Example to Create a Thread by Extending a Thread Class Here is the preceding program rewritten to extend the Thread − In this example, we”ve created a ThreadDemo class which extends Thread class. We”re calling super(name) in constructor() method to assign a name to the thread and called super.start() to start the thread processing. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2″); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, State: Running Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead Example: Demonstrating sleep() Method In this example, we”re show-casing use of sleep() method to delay the processing. It helps in show the parallel processing in the output. We”ve added Thread.sleep() call in the run method. InterruptedException is handled as thread can be interrupted during sleep mode. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( String name) { super(name); System.out.println(“Thread: ” + name + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } public void start () { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Start”); super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo( “Thread-1”); ThreadDemo thread2 = new ThreadDemo( “Thread-2”); thread1.start(); thread2.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-1, 1 Thread:
Java – Reentrant Monitor
Java – Reentrant Monitor ”; Previous Next Reentrant Monitor in Java ReetrantLock is a class that implements Lock Interface. It provides the synchronization feature with great flexibility which is why it is the most used lock class in Java. It is necessary for the reliable and fair working of thread. Here, threads are small sub-processes of a big operation. In this article, we are going to learn ReetrantLock and how they manage threads so that they can work efficiently. Working of ReetrantLock When multiple threads try to access a shared resource then, ReetrantLock restricts access to a single thread at a time through lock() and unlock() methods. Suppose there are three people trying to book a train ticket. At the same time, all three people will try to access the booking system, it may happen that two people end up booking the same seat. Reetrant Lock can handle this situation. First, all three people will request to acquire the booking system through tryLock() method. When one acquires the booking system then, it restricts the particular seat booking through lock() method. After booking, the person will call the unlock() method to release the acquired lock. Till the resources are busy other people will wait in a queue for their turn and after the release of lock they will come in a runnable state. ReetrantLock tries to provide locks in a fair manner. We can set for how long a thread can acquire lock and also, it ensures that a thread with the longest wait time may get access to lock first. By default the locks are unfair, to make it fair we need to pass Boolean value true in its constructor. Syntax ReentrantLock nameOflock = new ReentrantLock(); // by default false Or, ReentrantLock nameOflock = new ReentrantLock(true); // we can make it true The locks are explicit and can lock or unlock in any order. A single thread can ask for the lock multiple times that”s the reason the name of lock is Reentrant. We can count the number of times a lock is acquired by using getHoldCount() method. Multithreading Without Reentrant Lock The following example illustrates the multithreading witout use of Reetrant Lock in above code. We”ve created a class Thrd with a method operation() to perform a given task. Now we”ve created three thread classes and call the operation() method. In the main() method, three objects of thread class are defined and their start() method to start the execution of threads. Example of Multithreading Without Reentrant Lock package com.tutorialspoint; class Thrd { static void operation(int data) { for(int i = 1; i <= 4; i++) { System.out.println(data++); } } } class Thrd1 extends Thread { // thread number 1 public void run() { Thrd.operation(1); // method calling } } class Thrd2 extends Thread { // thread number 2 public void run() { Thrd.operation(5); // method calling } } class Thrd3 extends Thread { // thread number 3 public void run() { Thrd.operation(10); // method calling } } public class TestThread { public static void main(String args[]) { // creating object for thread class Thrd1 oprt1 = new Thrd1(); Thrd2 oprt2 = new Thrd2(); Thrd3 oprt3 = new Thrd3(); // Starting the thread operation oprt1.start(); oprt2.start(); oprt3.start(); } } This produces a different result every time you run this program − Output 1 2 3 4 10 11 12 13 5 6 7 8 Multithreading With Reentrant Lock The following example illustrates the use of Reetrant Lock in above code. We”ve created a class Thrd and inside this thread, we”ve defined an object of ReentrantLock. A method operation() store the Boolean value of tryLock() method to a variable named lockAcquired which will check if lock gets acquired by any thread or not. If the lock is acquired lock is given to that thread using lock() method and then the thread start performing the given task. The task will be performed in the try block and the lock will be released in the finally block using unlock() method. Now we”ve created three thread classes and call the operation() method. In the main() method, three objects of thread class are defined and their start() method to start the execution of threads. Example of Multithreading With Reentrant Lock package com.tutorialspoint; import java.util.concurrent.locks.ReentrantLock; class Thrd { // creating object of ReentrantLock class private static ReentrantLock lockr = new ReentrantLock(); static void operation(int data) { // give access to lock boolean lockAcquired = lockr.tryLock(); if (lockAcquired) { try { lockr.lock(); // giving lock to thread for(int i = 1; i <= 4; i++) { System.out.println(data++); } // checking lock count System.out.println(“Count of Lock: ” + lockr.getHoldCount()); } finally { lockr.unlock(); // unlocking the lock } } else { System.out.println(“I am in else block”); } } } class Thrd1 extends Thread { // thread number 1 public void run() { Thrd.operation(1); // method calling } } class Thrd2 extends Thread { // thread number 2 public void run() { Thrd.operation(5); // method calling } } class Thrd3 extends Thread { // thread number 3 public void run() { Thrd.operation(10); // method calling } } public class TestThread { public static void main(String args[]) { // creating object for thread class Thrd1 oprt1 = new Thrd1(); Thrd2 oprt2 = new Thrd2(); Thrd3 oprt3 = new Thrd3(); // Starting the thread operation oprt1.start(); oprt2.start(); oprt3.start(); } } This produces a different result every time you run this program − Output I am in else block 5 6 7 8 Count of Lock: 2 I am in else block Multithreading With Reentrant Lock as True The following example illustrates the use of Reetrant Lock in above code. We”ve created a class Thrd and inside this thread, we”ve defined an object of ReentrantLock with fair value as true. A method operation() store the Boolean value of tryLock() method to a variable named lockAcquired which will check if lock gets acquired by any thread or not. If the lock is acquired lock is given to that thread
Java – Thread Deadlock
Java – Thread Deadlock ”; Previous Next Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here is an example. Example: Demonstrating Deadlock Situation public class TestThread { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 T1 = new ThreadDemo1(); ThreadDemo2 T2 = new ThreadDemo2(); T1.start(); T2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println(“Thread 1: Holding lock 1…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 1: Waiting for lock 2…”); synchronized (Lock2) { System.out.println(“Thread 1: Holding lock 1 & 2…”); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock2) { System.out.println(“Thread 2: Holding lock 2…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 2: Waiting for lock 1…”); synchronized (Lock1) { System.out.println(“Thread 2: Holding lock 1 & 2…”); } } } } } When you compile and execute the above program, you find a deadlock situation and following is the output produced by the program − Output Thread 1: Holding lock 1… Thread 2: Holding lock 2… Thread 1: Waiting for lock 2… Thread 2: Waiting for lock 1… The above program will hang forever because neither of the threads in position to proceed and waiting for each other to release the lock, so you can come out of the program by pressing CTRL+C. Deadlock Solution Example Let”s change the order of the lock and run of the same program to see if both the threads still wait for each other − Example public class TestThread { public static Object Lock1 = new Object(); public static Object Lock2 = new Object(); public static void main(String args[]) { ThreadDemo1 T1 = new ThreadDemo1(); ThreadDemo2 T2 = new ThreadDemo2(); T1.start(); T2.start(); } private static class ThreadDemo1 extends Thread { public void run() { synchronized (Lock1) { System.out.println(“Thread 1: Holding lock 1…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 1: Waiting for lock 2…”); synchronized (Lock2) { System.out.println(“Thread 1: Holding lock 1 & 2…”); } } } } private static class ThreadDemo2 extends Thread { public void run() { synchronized (Lock1) { System.out.println(“Thread 2: Holding lock 1…”); try { Thread.sleep(10); } catch (InterruptedException e) {} System.out.println(“Thread 2: Waiting for lock 2…”); synchronized (Lock2) { System.out.println(“Thread 2: Holding lock 1 & 2…”); } } } } } So just changing the order of the locks prevent the program in going into a deadlock situation and completes with the following result − Output Thread 1: Holding lock 1… Thread 1: Waiting for lock 2… Thread 1: Holding lock 1 & 2… Thread 2: Holding lock 1… Thread 2: Waiting for lock 2… Thread 2: Holding lock 1 & 2… The above example is to just make the concept clear, however, it is a complex concept and you should deep dive into it before you develop your applications to deal with deadlock situations. java_multithreading.htm Print Page Previous Next Advertisements ”;