Java – HttpURLConnection Class ”; Previous Next Java HttpURLConnection Class java.net.HttpURLConnection, is an abstract class which represents the HTTP-specific URL connection. Instances of this class can be used both to read from and to write to the resource referenced by the URL. For example − If you connect to a URL whose protocol is HTTP, the URL.openConnection() method returns an HttpURLConnection object. Steps to make a connection to a URL Following are the steps to make a connectiion to the URL and start processing. Invoke URL.openConnection() method to get HttpURLConnection object of an HTTP based URL. Update setup parameters and general request properties as required using connection object various setter methods. Create a connection to remote object using connect() method of connection object. Once remote object is available, access the content/headers of the remote object. HttpURLConnection Class Declaration public abstract class HttpURLConnection extends URLConnection HttpURLConnection Class Fields Sr.No. Field & Description 1 protected int chunkLength The chunk-length when using chunked encoding streaming mode for output. 2 protected int fixedContentLength The fixed content-length when using fixed-length streaming mode. 3 protected long fixedContentLengthLong The fixed content-length when using fixed-length streaming mode. 4 static int HTTP_ACCEPTED HTTP Status-Code 202: Accepted. 5 static int HTTP_BAD_GATEWAY HTTP Status-Code 502: Bad Gateway. 6 static int HTTP_BAD_METHOD HTTP Status-Code 405: Method Not Allowed. 7 static int HTTP_BAD_REQUEST HTTP Status-Code 400: Bad Request. 8 static int HTTP_CLIENT_TIMEOUT HTTP Status-Code 408: Request Time-Out. 9 static int HTTP_CONFLICT HTTP Status-Code 409: Conflict. 10 static int HTTP_CREATED HTTP Status-Code 201: Created. 11 static int HTTP_ENTITY_TOO_LARGE HTTP Status-Code 413: Request Entity Too Large. 12 static int HTTP_FORBIDDEN HTTP Status-Code 403: Forbidden. 13 static int HTTP_GATEWAY_TIMEOUT HTTP Status-Code 504: Gateway Timeout. 14 static int HTTP_GONE HTTP Status-Code 410: Gone. 15 static int HTTP_INTERNAL_ERROR HTTP Status-Code 500: Internal Server Error. 16 static int HTTP_LENGTH_REQUIRED HTTP Status-Code 411: Length Required. 17 static int HTTP_MOVED_PERM HTTP Status-Code 301: Moved Permanently. 18 static int HTTP_MOVED_TEMP HTTP Status-Code 302: Temporary Redirect. 19 static int HTTP_MULT_CHOICE HTTP Status-Code 300: Multiple Choices. 20 static int HTTP_NO_CONTENT HTTP Status-Code 204: No Content. 21 static int HTTP_NOT_ACCEPTABLE HTTP Status-Code 406: Not Acceptable. 22 static int HTTP_NOT_AUTHORITATIVE HTTP Status-Code 203: Non-Authoritative Information. 23 static int HTTP_NOT_FOUND HTTP Status-Code 404: Not Found. 24 static int HTTP_NOT_IMPLEMENTED HTTP Status-Code 501: Not Implemented. 25 static int HTTP_NOT_MODIFIED HTTP Status-Code 304: Not Modified. 26 static int HTTP_OK HTTP Status-Code 200: OK. 27 static int HTTP_PARTIAL HTTP Status-Code 206: Partial Content. 28 static int HTTP_PAYMENT_REQUIRED HTTP Status-Code 402: Payment Required. 29 static int HTTP_PRECON_FAILED HTTP Status-Code 412: Precondition Failed. 30 static int HTTP_PROXY_AUTH HTTP Status-Code 407: Proxy Authentication Required. 31 static int HTTP_REQ_TOO_LONG HTTP Status-Code 414: Request-URI Too Large. 32 static int HTTP_RESET HTTP Status-Code 205: Reset Content. 33 static int HTTP_SEE_OTHER HTTP Status-Code 303: See Other. 34 static int HTTP_UNAUTHORIZED HTTP Status-Code 401: Unauthorized. 35 static int HTTP_UNAVAILABLE HTTP Status-Code 503: Service Unavailable. 36 static int HTTP_UNSUPPORTED_TYPE HTTP Status-Code 415: Unsupported Media Type. 37 static int HTTP_USE_PROXY HTTP Status-Code 305: Use Proxy. 38 static int HTTP_VERSION HTTP Status-Code 505: HTTP Version Not Supported. 39 protected boolean instanceFollowRedirects If true, the protocol will automatically follow redirects. 40 protected String method The HTTP method (GET,POST,PUT,etc.). 41 protected int responseCode An int representing the three digit HTTP Status-Code. 42 protected String responseMessage The HTTP response message. HttpURLConnection Class Methods The HttpURLConnection class has many methods for setting or determining information about the connection, including the following − Sr.No. Method & Description 1 abstract void disconnect() Indicates that other requests to the server are unlikely in the near future. 2 InputStream getErrorStream() Returns the error stream if the connection failed but the server sent useful data nonetheless. 3 static boolean getFollowRedirects() Returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed. 4 String getHeaderField(int n) Returns the value for the nth header field. 5 String getHeaderFieldKey(int n) Returns the key for the nth header field. 6 boolean getInstanceFollowRedirects() Returns the value of this HttpURLConnection”s instanceFollowRedirects field. 7 Permission getPermission() Returns a SocketPermission object representing the permission necessary to connect to the destination host and port. 8 String getRequestMethod() Get the request method. 9 int getResponseCode() Gets the status code from an HTTP response message. 10 String getResponseMessage() Gets the HTTP response message, if any, returned along with the response code from a server. 11 void setAuthenticator(Authenticator auth) Supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection. 12 void setChunkedStreamingMode(int chunklen) This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. 13 void setFixedLengthStreamingMode(int contentLength) This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance. 14 void setFixedLengthStreamingMode(long contentLength) This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance. 15 static void setFollowRedirects(boolean set) Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class. 16 void setInstanceFollowRedirects(boolean followRedirects) Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance. 17 void setRequestMethod(String method) Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions. 18 abstract boolean usingProxy() Indicates if the connection is going through a proxy. Extends This class extends following classes java.lang.Object java.net.URLConnection Example of Java HttpURLConnection Class The following HttpURLConnection program connects to a URL entered from the command line. If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time. package com.tutorialspoint; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class HttpUrlConnectionDemo { public static void main(String [] args) { try { URL url = new URL(“https://www.tutorialspoint.com”); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) {
Category: Java
Java – Collections
Java – Collections Framework ”; Previous Next Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties. Why Collections Framework? The collections framework was designed to meet several goals, such as − The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient. The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability. The framework had to extend and/or adapt a collection easily. Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose. Java Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following − Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy. Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections. Hierarchy of Collection Framework All classes and interfaces for the collection framework are available in java.utli package. The following diagram shows the hierarchy of the collection framework in Java: Java Collection Interfaces The collections framework defines several interfaces. This section provides an overview of each interface − Sr.No. Interface & Description 1 The Collection Interface This enables you to work with groups of objects; it is at the top of the collections hierarchy. 2 The List Interface This extends Collection and an instance of List stores an ordered collection of elements. 3 The Set This extends Collection to handle sets, which must contain unique elements. 4 The SortedSet This extends Set to handle sorted sets. 5 The Map This maps unique keys to values. 6 The Map.Entry This describes an element (a key/value pair) in a map. This is an inner class of Map. 7 The SortedMap This extends Map so that the keys are maintained in an ascending order. 8 The Enumeration This is legacy interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator. Java Collection Classes Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections. The standard collection classes are summarized in the following table − Sr.No. Class & Description 1 AbstractCollection Implements most of the Collection interface. 2 AbstractList Extends AbstractCollection and implements most of the List interface. 3 AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. 4 LinkedList Implements a linked list by extending AbstractSequentialList. 5 ArrayList Implements a dynamic array by extending AbstractList. 6 AbstractSet Extends AbstractCollection and implements most of the Set interface. 7 HashSet Extends AbstractSet for use with a hash table. 8 LinkedHashSet Extends HashSet to allow insertion-order iterations. 9 TreeSet Implements a set stored in a tree. Extends AbstractSet. 10 AbstractMap Implements most of the Map interface. 11 HashMap Extends AbstractMap to use a hash table. 12 TreeMap Extends AbstractMap to use a tree. 13 WeakHashMap Extends AbstractMap to use a hash table with weak keys. 14 LinkedHashMap Extends HashMap to allow insertion-order iterations. 15 IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents. The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them. The following legacy classes defined by java.util have been discussed in the previous chapter − Sr.No. Class & Description 1 Vector This implements a dynamic array. It is similar to ArrayList, but with some differences. 2 Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. 3 Dictionary Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. 4 Hashtable Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. 5 Properties Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. 6 PriorityQueue PriorityQueue class is an unbounded priority queue based on a priority heap. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects. 7 BitSet A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. 8 ArrayDeque ArrayDeque class provides resizable-array and implements the Deque interface. Array deques have no capacity restrictions so they grow as necessary to support usage. 9 EnumMap EnumMap class is a specialized Map implementation for use with enum keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. 10 Queue The queue interface is
Java – Thread Pools
Java – Thread Pools ”; Previous Next Thread Pools A thread pool is a collection of pre-initialized threads. The general plan behind a thread pool is to form variety of threads at method startup and place them into a pool, wherever they sit and expect work. once a server receives a call for participation, it awakens a thread from this pool−if one is available−and passes it the request for service. Once the thread completes its service, it returns to the pool and awaits a lot of work. If the pool contains no accessible thread, the server waits till one becomes free. Why Use Thread Pools in Java? It saves time as a result of there”s no need to produce new thread. It is utilized in Servlet and JSP wherever instrumentality creates a thread pool to method the request. Creating Thread Pools in Java Java provides a java.util.concurrent.Executors class provides couple of methods to create a thread pools. Executors Class Methods Following are few important and useful methods this class to create Thread Pools – Sr.No. Method & Description 1 public static ExecutorService newCachedThreadPool() Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. 2 public static ExecutorService newFixedThreadPool(int nThreads) Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. 3 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically. 4 public static ExecutorService newWorkStealingPool() Creates a work-stealing thread pool using all available processors as its target parallelism level. Creating a Thread Pool Using newFixedThreadPool() Method A fixed thread pool obtainted by calling the static newFixedThreadPool() method of Executors class. Syntax ExecutorService fixedPool = Executors.newFixedThreadPool(2); Where, Maximum 2 threads will be active to process tasks. If more than 2 threads are submitted then they are held in a queue until threads become available. A new thread is created to take its place if a thread terminates due to failure during execution shutdown on executor is not yet called. Any thread exists till the pool is shutdown. Example: Creating a Thread Pool Using newFixedThreadPool() Method The following TestThread program shows usage of Executors newFixedThreadPool() method to create a thread pool of two threads. We”re using a ThreadPoolExecutor object and initialized with newFixedThreadPool(2), a fix thread pool of size 2. Then we”re printing various attributes of the threadpool. Then we”re adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes. package com.tutorialspoint; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution System.out.println(“Core threads: ” + pool.getCorePoolSize()); System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println(“Running Task! Thread Name: ” + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println(“Task Completed! Thread Name: ” + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } } Output Largest executions: 0 Maximum allowed threads: 2 Current threads in pool: 0 Currently executing threads: 0 Total number of threads(ever scheduled): 0 Core threads: 2 Largest executions: 2 Maximum allowed threads: 2 Current threads in pool: 2 Currently executing threads: 2 Total number of threads(ever scheduled): 4 Running Task! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-2 Running Task! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1 Running Task! Thread Name: pool-1-thread-1 Task Completed! Thread Name: pool-1-thread-2 Task Completed! Thread Name: pool-1-thread-1 Here although, we”ve submitted four threads but only two threads are executed as ThreadPool is fixed to accept only two threads. Creating a Thread Pool Using newCachedThreadPool() Method A cached thread pool obtainted by calling the static newCachedThreadPool() method of Executors class. Syntax ExecutorService executor = Executors.newCachedThreadPool(); Where, newCachedThreadPool method creates an executor having an expandable thread pool. Such an executor is suitable for applications that launch many short-lived tasks. Example: Creating a Thread Pool Using newCachedThreadPool() Method The following TestThread program shows usage of Executors newCachedThreadPool() method to create a expandable thread pool of threads. We”re using a ThreadPoolExecutor object and initialized with newCachedThreadPool(). Then we”re printing various attributes of the threadpool. Then we”re adding few threads to the executor and then same attributes of threadpool are printed to reflect the changes. package com.tutorialspoint; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution System.out.println(“Core threads: ” + pool.getCorePoolSize()); System.out.println(“Largest executions: ” + pool.getLargestPoolSize()); System.out.println(“Maximum allowed threads: ” + pool.getMaximumPoolSize()); System.out.println(“Current threads in pool: ” + pool.getPoolSize()); System.out.println(“Currently executing threads: ” + pool.getActiveCount()); System.out.println(“Total number of threads(ever scheduled): ” + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println(“Running Task! Thread Name: ” + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println(“Task Completed! Thread Name: ” + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } } Output Largest executions: 0 Maximum allowed threads:
Java – Thread Control
Java – Thread Control ”; Previous Next Java Thread Control Core Java provides complete control over multithreaded program. You can develop a multithreaded program which can be suspended, resumed, or stopped completely based on your requirements. There are various static methods which you can use on thread objects to control their behavior. Methods for Controlling Java Thread Following table lists down the methods for controlling a thread in Java: − Sr.No. Method & Description 1 public void suspend() This method puts a thread in the suspended state and can be resumed using resume() method. 2 public void stop() This method stops a thread completely. 3 public void resume() This method resumes a thread, which was suspended using suspend() method. 4 public void wait() Causes the current thread to wait until another thread invokes the notify(). 5 public void notify() Wakes up a single thread that is waiting on this object”s monitor. Be aware that the latest versions of Java has deprecated the usage of suspend( ), resume( ), and stop( ) methods and so you need to use available alternatives. Example of Thread Control in Java class RunnableDemo implements Runnable { public Thread t; private String threadName; boolean suspended = false; RunnableDemo( String name) { threadName = name; System.out.println(“Creating ” + threadName ); } public void run() { System.out.println(“Running ” + threadName ); try { for(int i = 10; i > 0; i–) { System.out.println(“Thread: ” + threadName + “, ” + i); // Let the thread sleep for a while. Thread.sleep(300); synchronized(this) { while(suspended) { wait(); } } } } catch (InterruptedException e) { System.out.println(“Thread ” + threadName + ” interrupted.”); } System.out.println(“Thread ” + threadName + ” exiting.”); } public void start () { System.out.println(“Starting ” + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } void suspend() { suspended = true; } synchronized void resume() { suspended = false; notify(); } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( “Thread-1”); R1.start(); RunnableDemo R2 = new RunnableDemo( “Thread-2”); R2.start(); try { Thread.sleep(1000); R1.suspend(); System.out.println(“Suspending First Thread”); Thread.sleep(1000); R1.resume(); System.out.println(“Resuming First Thread”); R2.suspend(); System.out.println(“Suspending thread Two”); Thread.sleep(1000); R2.resume(); System.out.println(“Resuming thread Two”); } catch (InterruptedException e) { System.out.println(“Main thread Interrupted”); }try { System.out.println(“Waiting for threads to finish.”); R1.t.join(); R2.t.join(); } catch (InterruptedException e) { System.out.println(“Main thread Interrupted”); } System.out.println(“Main thread exiting.”); } } The above program produces the following output − Output Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 10 Running Thread-2 Thread: Thread-2, 10 Thread: Thread-1, 9 Thread: Thread-2, 9 Thread: Thread-1, 8 Thread: Thread-2, 8 Thread: Thread-1, 7 Thread: Thread-2, 7 Suspending First Thread Thread: Thread-2, 6 Thread: Thread-2, 5 Thread: Thread-2, 4 Resuming First Thread Suspending thread Two Thread: Thread-1, 6 Thread: Thread-1, 5 Thread: Thread-1, 4 Thread: Thread-1, 3 Resuming thread Two Thread: Thread-2, 3 Waiting for threads to finish. Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. Main thread exiting. java_multithreading.htm Print Page Previous Next Advertisements ”;
Java – Arrays
Java – Arrays ”; Previous Next What are Arrays in Java? Java provides a data structure called the array, which stores a fixed-size sequential collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. Declaring Array Variables To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable − Syntax dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way. Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Example The following code snippets are examples of this syntax − double[] myList; // preferred way. or double myList[]; // works but not preferred way. Creating Arrays You can create an array by using the new operator with the following syntax − Syntax arrayRefVar = new dataType[arraySize]; The above statement does two things − It creates an array using new dataType[arraySize]. It assigns the reference of the newly created array to the variable arrayRefVar. Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − dataType[] arrayRefVar = new dataType[arraySize]; Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, …, valuek}; The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1. Example Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList − double[] myList = new double[10]; Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9. Processing Arrays When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. Example: Creating, Iterating and Performing Other Operations on Arrays public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + ” “); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println(“Total is ” + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println(“Max is ” + max); } } This will produce the following result − Output 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5 The foreach Loops with Arrays JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. The following code displays all the elements in the array myList − Example: Displaying All Elements of an Arrays public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } } This will produce the following result − Output 1.9 2.9 3.4 3.5 Passing Arrays to Methods Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array − Example public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + ” “); } } You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2 − Example printArray(new int[]{3, 1, 2, 6, 4, 2}); Returning an Array from a Method A method may also return an array. For example, the following method returns an array that is the reversal of another array − Example public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length – 1; i < list.length; i++, j–) { result[j] = list[i]; } return result; } The Arrays Class The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types. Sr.No. Method & Description 1 public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)). 2 public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) 3 public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types
Java – Generics
Java – Generics ”; Previous Next It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering. Why Generics are used in Java? Generics are used to create such classes, interfaces, and methods with parameters that can operate on different data types along. This feature was introduced in Java 5. Java – Generics Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements. Advantage of Java Generics No scarification of type-safety No requirement of type-casting Compile-time checking Code reusability and improved performance Types of Java Generics Generic Methods You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Rules to Define Generic Methods Following are the rules to define Generic Methods − All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method”s return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments. A generic method”s body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). Example of Java Generic Methods Following example illustrates how we can print an array of different type using a single Generic method − public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for(E element : inputArray) { System.out.printf(“%s “, element); } System.out.println(); } public static void main(String args[]) { // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { ”H”, ”E”, ”L”, ”L”, ”O” }; System.out.println(“Array integerArray contains:”); printArray(intArray); // pass an Integer array System.out.println(“nArray doubleArray contains:”); printArray(doubleArray); // pass a Double array System.out.println(“nArray characterArray contains:”); printArray(charArray); // pass a Character array } } Output Array integerArray contains: 1 2 3 4 5 Array doubleArray contains: 1.1 2.2 3.3 4.4 Array characterArray contains: H E L L O Bounded Type Parameters There may be times when you”ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter”s name, followed by the extends keyword, followed by its upper bound. Example of Bounded Type Parameters Following example illustrates how extends is used in a general sense to mean either “extends” (as in classes) or “implements” (as in interfaces). This example is Generic method to return the largest of three Comparable objects − public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf(“Max of %d, %d and %d is %dnn”, 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf(“Max of %.1f,%.1f and %.1f is %.1fnn”, 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf(“Max of %s, %s and %s is %sn”,”pear”, “apple”, “orange”, maximum(“pear”, “apple”, “orange”)); } } Output Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear Generic Classes A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters. Example of Generic Classes Following example illustrates how we can define a generic class − public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String(“Hello World”)); System.out.printf(“Integer Value :%dnn”, integerBox.get()); System.out.printf(“String Value :%sn”, stringBox.get()); } } Output Integer Value :10 String Value :Hello World Print Page Previous Next Advertisements ”;
Java – Directories
Java – Directory Operations ”; Previous Next Directory in Java A directory is a File which can contain a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail, check a list of all the methods which you can call on File object and what are related to directories. Creating Directories There are two useful File utility methods, which can be used to create directories − The mkdir() method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet. The mkdirs() method creates both a directory and all the parents of the directory. Example to Create Directory in Java Following example creates “/tmp/user/java/bin” directory − package com.tutorialspoint; import java.io.File; public class DirectoryTest { public static void main(String args[]) { String dirname = “/tmp/user/java/bin”; File directory = new File(dirname); // Create directory now. directory.mkdirs(); // create new file object File file = new File(“/tmp/user/java/bin”); System.out.println(file.exists()); } } Output Compile and execute the above code to create “/tmp/user/java/bin” folders. true Note − Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly. Listing (Reading) Directories You can use list() method provided by File object to list down all the files and directories available in a directory as follows − Example to Read (List) a Directory in Java package com.tutorialspoint; import java.io.File; public class DirectoryTest { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File(“/tmp”); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); } } catch (Exception e) { // if any error occurs e.printStackTrace(); } } } Output This will produce the following result based on the directories and files available in your /tmp directory − user Deleting Directories You can use delete() method provided by File object to delete a directory as follows − Example to Delete a Directory in Java package com.tutorialspoint; import java.io.File; public class DirectoryTest { public static void main(String[] args) { File file = new File(“/tmp/user/java/bin”); if(file.exists()) { boolean success = file.delete(); if (success) { System.out.println(“The directory has been successfully deleted.”); }else { System.out.println(“The directory deletion failed.”); } }else { System.out.println(“The directory is not present.”); } } } Output This will produce the following result based on the directories and files available in your /tmp directory − The directory has been successfully deleted. Print Page Previous Next Advertisements ”;
Java – try-with-resources
Java – Try with Resources ”; Previous Next Try with Resources The Java try-with-resources statement is a try statement that is used for declaring one or more resources such as streams, sockets, databases, connections, etc. These resources must be closed while the program is being finished. The try-with-resources statement closes the resources at the end of the statement. The try-with-resources feature was introduced in Java7. The try-with-resources can also be a replacement for try-catch-finally with resources objects. The try-with-resources statement is also referred as “Automatic Resource Management” and it was introduced in Java7. This statement is a replacement of try-catch-finally-statement if you are working resources objects. Syntax of Try with Resources To use this statement, you simply need to declare the required resources within the parenthesis, and the created resource will be closed automatically at the end of the block. Following is the syntax of try-with-resources statement: try(resources declarations) { // use of the resources } catch(Exception e) { // exception handling } For example, opening a file with try-with-resources: try(FileReader fr = new FileReader(“file path”)) { // use the resource } catch () { // body of catch } } Following is the program that reads the data in a file using try-with-resources statement. Example: Try with Resources in Java In this program, we”re creating the FileReader object within try with resources statement. FileReader fr, reference is declared within the try statement and we need not to remember to close it in finally block as it will be closed automatically by JVM so that there is no memory leak or loose connection possibility. import java.io.FileReader; import java.io.IOException; public class Try_withDemo { public static void main(String args[]) { try(FileReader fr = new FileReader(“E://file.txt”)) { char [] a = new char[50]; fr.read(a); // reads the contentto the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); } } } Try with Resources having Multiple Resources You can also declare multiple resource inside a try block. Consider the below-given example, // This example is to use Try with Resources // with multiple Resources import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class Main { public static void main(String[] args) { // try block with multiple resources try ( FileReader fileReader = new FileReader(“file1.txt”); BufferedReader bufferedReader = new BufferedReader(fileReader); FileWriter fileWriter = new FileWriter(“file2.txt”); PrintWriter printWriter = new PrintWriter(fileWriter) ) { String line; while ((line = bufferedReader.readLine()) != null) { // Read content line by line and write it // to the output (file2.txt) file printWriter.println(line); } System.out.println(“Content copied.”); } catch (IOException e) { e.printStackTrace(); } } } Example: Without Try with Resources In the following program, we are reading data from a file using FileReader and we are closing it using finally block. In this program, we”re creating the FileReader object within try block. FileReader fr, reference is declared outside the try block so that it is accessible outside the try block and we need to remember to close it in finally block or before program exits so that there is no memory leak or loose connection possibility. import java.io.File; import java.io.FileReader; import java.io.IOException; public class ReadData_Demo { public static void main(String args[]) { FileReader fr = null; try { File file = new File(“file.txt”); fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); }finally { try { fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } Try with Resources: Points to Remember Following points are to be kept in mind while working with try-with-resources statement. To use a class with try-with-resources statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime. You can declare more than one class in try-with-resources statement. While you declare multiple classes in the try block of try-with-resources statement these classes are closed in reverse order. Except the declaration of resources within the parenthesis everything is the same as normal try/catch block of a try block. The resource declared in try gets instantiated just before the start of the try-block. The resource declared at the try block is implicitly declared as final. try with resources improvement with Java 9 Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example. In this example, we”ll use BufferedReader as resource to read a string and then BufferedReader is to be closed. Before Java 9 import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData(“test”)); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (BufferedReader br1 = br) { return br1.readLine(); } } } Output Let us compile and run the above program, this will produce the following result − test Here we need to declare a resource br1 within try statment and then use it. In Java9, we don”t need to declare br1 anymore and following program will give the same result. Java 9 onwards import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData(“test”)); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (br) { return br.readLine(); } } } Output Let us compile and run the above program, this will produce the following result
Java – Thread Priority
Java – Thread Priority ”; Previous Next Priority of a Thread in Java Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. You can get and set the priority of a Thread. Thread class provides methods and constants for working with the priorities of a Thread. Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent. Built-in Property Constants of Thread Class Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). MIN_PRIORITY: Specifies the minimum priority that a thread can have. NORM_PRIORITY: Specifies the default priority that a thread is assigned. MAX_PRIORITY: Specifies the maximum priority that a thread can have. Thread Priority Setter and Getter Methods Thread.getPriority() Method: This method is used to get the priority of a thread. Thread.setPriority() Method: This method is used to set the priority of a thread, it accepts the priority value and updates an existing priority with the given priority. Example of Thread Priority in Java In this example, we”re showing a simple one thread program where we”re not declaring any thread and checking the thread name and priority in the program execution. package com.tutorialspoint; public class TestThread { public void printName() { System.out.println(“Thread Name: ” + Thread.currentThread().getName()); System.out.println(“Thread Priority: ” +Thread.currentThread().getPriority()); } public static void main(String args[]) { TestThread thread = new TestThread(); thread.printName(); } } Output Thread Name: main Thread Priority: 5 More Examples of Thread Priority Example 1 In this example, we”ve created a ThreadDemo class which extends Thread class. We”ve created three threads. Each thread is assigned a priority. In run() method, we”re printing the priorities and in output, it is reflecting in threads execution. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread Name: ” + Thread.currentThread().getName() + “, Thread Priority: ” +Thread.currentThread().getPriority()); 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(); } } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread1.setPriority(Thread.MAX_PRIORITY); thread2.setPriority(Thread.MIN_PRIORITY); thread3.setPriority(Thread.NORM_PRIORITY); thread1.start(); thread2.start(); thread3.start(); } } Output Thread Name: Thread-2, Thread Priority: 5 Thread Name: Thread-1, Thread Priority: 1 Thread Name: Thread-0, Thread Priority: 10 Thread: Thread-1, 4 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-0, 4 Thread: Thread-1, 2 Thread: Thread-2, 3 Thread: Thread-0, 3 Thread: Thread-0, 2 Thread: Thread-0, 1 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-1, 1 Example 2 In this example, we”ve created a ThreadDemo class which extends Thread class. We”ve created three threads. As we”re not setting any priority, each thread has a normal priority. In run() method, we”re printing the priorities and in output, threads are executing in any order. package com.tutorialspoint; class ThreadDemo extends Thread { ThreadDemo( ) { } public void run() { System.out.println(“Thread Name: ” + Thread.currentThread().getName() + “, Thread Priority: ” +Thread.currentThread().getPriority()); 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(); } } public void start () { super.start(); } } public class TestThread { public static void main(String args[]) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); ThreadDemo thread3 = new ThreadDemo(); thread1.start(); thread2.start(); thread3.start(); } } Output Thread Name: Thread-1, Thread Priority: 5 Thread Name: Thread-2, Thread Priority: 5 Thread Name: Thread-0, Thread Priority: 5 Thread: Thread-2, 4 Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-0, 4 Thread: Thread-2, 2 Thread: Thread-1, 2 Thread: Thread-2, 1 Thread: Thread-0, 3 Thread: Thread-1, 1 Thread: Thread-0, 2 Thread: Thread-0, 1 Print Page Previous Next Advertisements ”;
Java – Create a File
Java – Creating Files ”; Previous Next Create File in Java We can create a file in Java using multiple ways. Following are three most popular ways to create a file in Java − Using FileOutputStream() constructor Using File.createNewFile() method Using Files.write() method Let”s take a look at each of the way to create file in Java. Create 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. Following constructor takes a file name as a string to create an input stream object to write the file − Syntax 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 as follows − File f = new File(“C:/java/hello.txt”); OutputStream f = new FileOutputStream(f); Example: Create File Using FileOutputStream Constructor Following is the example to demonstrate FileOutputStream to create 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 Create File Using File.createNewFile() Method File.createNewFile() method allows to create a file in given location or in current directory as follows − Syntax 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.”); } Example: Create File Using File.createNewFile() Method Following is the example to demonstrate File to create a file in given directory using createNewFile() 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”); } } } Output 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. File is created! Test data Create 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: Create 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”); } } } Output 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. [Test data] [1st line, 2nd line] Print Page Previous Next Advertisements ”;