Java – continue Statement ”; Previous Next Java continue Statement The continue statement can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement. In a while loop or do/while loop, control immediately jumps to the Boolean expression. Syntax The syntax of a continue is a single statement inside any loop − continue; Flow Diagram Examples Example 1: Using continue with while loop In this example, we”re showing the use of a continue statement to skip an element 15 in a while loop which is used to print element from 10 to 19. Here we”ve initialized an int variable x with a value of 10. Then in while loop, we”re checking x as less than 20 and within while loop, we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 15. Once x is 15, continue statement will jump the while loop while skipping the execution of the body and loop continues. public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { x++; if(x == 15){ continue; } System.out.print(“value of x : ” + x ); System.out.print(“n”); } } } Output value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 16 value of x : 17 value of x : 18 value of x : 19 value of x : 20 Example 2: Using continue with for loop In this example, we”re showing the use of a continue statement within a for loop to skip an elements of an array to print. Here we”re creating an array of integers as numbers and initialized it some values. We”ve created a variable named index to represent index of the array within for loop, check it against size of the array and incremented it by 1. Within for loop body, we”re printing element of the array using index notation. Once 30 is encountered as value, continue statement jumps to the update section of for loop and loop continues. public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int index = 0; index < numbers.length; index++) { if(numbers[index] == 30){ continue; } System.out.print(“value of item : ” + numbers[index] ); System.out.print(“n”); } } } Output value of item : 10 value of item : 20 value of item : 40 value of item : 50 Example 3: Using continue with do while loop In this example, we”re showing the use of a continue statement to skip an element 15 in a do while loop which is used to print element from 10 to 19. Here we”ve initialized an int variable x with a value of 10. Then in do while loop, we”re checking x as less than 20 after body and within while loop, we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 15. Once x is 15, continue statement will jump the while loop while skipping the execution of the body and loop continues. public class Test { public static void main(String args[]) { int x = 10; do { x++; if(x == 15){ continue; } System.out.print(“value of x : ” + x ); System.out.print(“n”); } while( x < 20 ); } } Output value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 16 value of x : 17 value of x : 18 value of x : 19 value of x : 20 java_loop_control.htm Print Page Previous Next Advertisements ”;
Category: Java
Java – Constructors
Java – Constructors ”; Previous Next Java Constructors Java constructors are special types of methods that are used to initialize an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. Typically, you will use a constructor to give initial values to the instance variables defined by the class or to perform any other start-up procedures required to create a fully formed object. All classes have constructors, whether you define one or not because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your constructor, the default constructor is no longer used. Rules for Creating Java Constructors You must follow the below-given rules while creating Java constructors: The name of the constructors must be the same as the class name. Java constructors do not have a return type. Even do not use void as a return type. There can be multiple constructors in the same class, this concept is known as constructor overloading. The access modifiers can be used with the constructors, use if you want to change the visibility/accessibility of constructors. Java provides a default constructor that is invoked during the time of object creation. If you create any type of constructor, the default constructor (provided by Java) is not invoked. Creating a Java Constructor To create a constructor in Java, simply write the constructor”s name (that is the same as the class name) followed by the brackets and then write the constructor”s body inside the curly braces ({}). Syntax Following is the syntax of a constructor − class ClassName { ClassName() { } } Example to create a Java Constructor The following example creates a simple constructor that will print “Hello world”. public class Main { // Creating a constructor Main() { System.out.println(“Hello, World!”); } public static void main(String[] args) { System.out.println(“The main() method.”); // Creating a class”s object // that will invoke the constructor Main obj_x = new Main(); } } This program will print: The main() method. Hello, World! Types of Java Constructors There are three different types of constructors in Java, we have listed them as follows: Default Constructor No-Args Constructor Parameterized Constructor 1. Default Constructor If you do not create any constructor in the class, Java provides a default constructor that initializes the object. Example: Default Constructor (A Class Without Any Constructor) In this example, there is no constructor defined by us. The default constructor is there to initialize the object. public class Main { int num1; int num2; public static void main(String[] args) { // We didn”t created any structure // a default constructor will invoke here Main obj_x = new Main(); // Printing the values System.out.println(“num1 : ” + obj_x.num1); System.out.println(“num2 : ” + obj_x.num2); } } Output num1 : 0 num2 : 0 2. No-Args (No Argument) Constructor As the name specifies, the No-argument constructor does not accept any argument. By using the No-Args constructor you can initialize the class data members and perform various activities that you want on object creation. Example: No-Args Constructor This example creates no-args constructor. public class Main { int num1; int num2; // Creating no-args constructor Main() { num1 = -1; num2 = -1; } public static void main(String[] args) { // no-args constructor will invoke Main obj_x = new Main(); // Printing the values System.out.println(“num1 : ” + obj_x.num1); System.out.println(“num2 : ” + obj_x.num2); } } Output num1 : -1 num2 : -1 3. Parameterized Constructor A constructor with one or more arguments is called a parameterized constructor. Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor”s name. Example 1: Parameterized Constructor This example creates a parameterized constructor. public class Main { int num1; int num2; // Creating parameterized constructor Main(int a, int b) { num1 = a; num2 = b; } public static void main(String[] args) { // Creating two objects by passing the values // to initialize the attributes. // parameterized constructor will invoke Main obj_x = new Main(10, 20); Main obj_y = new Main(100, 200); // Printing the objects values System.out.println(“obj_x”); System.out.println(“num1 : ” + obj_x.num1); System.out.println(“num2 : ” + obj_x.num2); System.out.println(“obj_y”); System.out.println(“num1 : ” + obj_y.num1); System.out.println(“num2 : ” + obj_y.num2); } } Output obj_x num1 : 10 num2 : 20 obj_y num1 : 100 num2 : 200 Example 2: Parameterized Constructor Here is a simple example that uses a constructor − // A simple constructor. class MyClass { int x; // Following is the constructor MyClass(int i ) { x = i; } } You would call constructor to initialize objects as follows − public class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass( 10 ); MyClass t2 = new MyClass( 20 ); System.out.println(t1.x + ” ” + t2.x); } } Output 10 20 Constructor Overloading in Java Constructor overloading means multiple constructors in a class. When you have multiple constructors with different parameters listed, then it will be known as constructor overloading. Example: Constructor Overloading In this example, we have more than one constructor. // Example of Java Constructor Overloading // Creating a Student Class class Student { String name; int age; // no-args constructor Student() { this.name = “Unknown”; this.age = 0; } // parameterized constructor having one parameter Student(String name) { this.name = name; this.age = 0; } // parameterized constructor having both parameters Student(String name, int age) { this.name = name; this.age = age; } public void printDetails() { System.out.println(“Name : ” + this.name); System.out.println(“Age : ” + this.age); } } public class Main { public static void main(String[] args) { Student std1 = new Student(); // invokes no-args constructor Student std2 = new Student(“Jordan”); // invokes parameterized constructor Student std3 = new Student(“Paxton”, 25); // invokes parameterized constructor // Printing
Java – Main Thread
Java – Main Thread ”; Previous Next Main Thread in Java Whenever we run a Java program, main thread is created automatically. This thread is responsible for execution of java program. Java runtime searches for main method to execute and create a main thread based on it. If we”re creating multiple threads then all child threads will be spawned from main thread. This main thread is the first thread to be created and is generally the last thread and it is used to perform shut down tasks. How to Control Main Thread? The main thread is created by the JVM automatically when a program starts. But you can control a Main thread by using different Thread methods and techniques. The following are some of the methods for controlling the Main thread. sleep() Method join() Method interrupt() Method Example of Java Main Thread In this example, we”re showing a simple one thread program where we”re not declaring any thread and checking the thread name 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 Example of Main Thread Example 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. In main method, we”ve created two threads. In output, you can check, current thread name is printed as main while threads are created using constructor() method call. 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-1, 4 Thread: Thread-0, 2 Thread: Thread-1, 3 Thread: Thread-0, 1 Thread: Thread-1, 2 Thread: Thread-0, State: Dead Thread: Thread-1, 1 Thread: Thread-1, 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. In main method, we”ve created two threads. In output, you can check, current thread name is printed as main while threads are created using constructor() method call. In the end of main method, we”re printing the state of main thread. 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(); System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } } Output Thread: main, State: New Thread: main, State: New Thread: main, State: Start Thread: main, State: Start Thread: Thread-0, State: Running Thread: main, State: Dead Thread: Thread-1, State: Running Thread: Thread-0, 4 Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-0, 3 Thread: Thread-0, 2 Thread: Thread-0, 1 Thread: Thread-0, State: Dead In this output, you can check that main thread was finished in earlier stages but threads were still running and finished their execution. Print Page Previous Next Advertisements ”;
Java – Networking
Java – Networking ”; Previous Next Java Networking Java networking (or, Java network programming) refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network. Advantages of Java Networking Creating server-client applications Implementing networking protocols Implement socket programming Creating web services Package Used in Networking The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand. The java.net package provides support for the two common network protocols − TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. This chapter gives a good understanding on the following two subjects − Socket Programming − This is the most widely used concept in Networking and it has been explained in very detail. URL Processing − This would be covered separately. Click here to learn about URL Processing in Java language. Socket Programming in Java Networking 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. The following steps occur when establishing a TCP connection between two computers using sockets − The server instantiates a ServerSocket object, denoting which port number communication is to occur on. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to. The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client”s socket. 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. TCP is a two-way communication protocol, hence data can be sent across both streams at the same time. Following are the useful classes providing complete set of methods to implement sockets. ServerSocket Class Constructors The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests. The ServerSocket class has four constructors − Sr.No. Method & Description 1 public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application. 2 public ServerSocket(int port, int backlog) throws IOException Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue. 3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on. 4 public ServerSocket() throws IOException Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket. If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests. ServerSocket Class Methods Following are some of the common methods of the ServerSocket class − Sr.No. Method & Description 1 public int getLocalPort() Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you. 2 public Socket accept() throws IOException Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely. 3 public void setSoTimeout(int timeout) Sets the time-out value for how long the server socket waits for a client during the accept(). 4 public void bind(SocketAddress host, int backlog) Binds the socket to the specified server and port in the SocketAddress object. Use this method if you have instantiated the ServerSocket using the no-argument constructor. When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and the server, and communication can begin. Socket Class Constructors The java.net.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. The Socket class has five constructors that a client uses to connect to a server − Sr.No. Method & Description 1 public Socket(String host, int port) throws UnknownHostException, IOException. This method attempts to connect to the specified server
Java – throw Exception
Java – Throws and Throw | Throw an Exception ”; Previous Next Java throws and throw If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method”s signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. Syntax Following is the syntax of throwing an exception using throws and throw – method(parameters) throws exception { // Method implementation throw new exception(); } The following method declares that it throws a RemoteException − Consider the below example code to use throws and throw keywords – import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } // Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException − import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } // Remainder of class definition } Java Throws and Throw Example Following example shows the use of throw keyword to send an exception in case a invalid argument is passed. We”re calling a divide method which checks if second parameter is zero then it will throw an IllegalArgumentException with a custom message. As IllegalArgumentException is an unchecked exception, the divide method is not required to declares throws statement. Now as parent method is not handling the exception, JVM intercepts the same and prints the error message and terminates the program. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; System.out.println(“result:” + divide(a,b)); } private static int divide(int a, int b) { if(b == 0) { throw new IllegalArgumentException(“second argument cannot be zero.”); } return a / b; } } Output Exception in thread “main” java.lang.IllegalArgumentException: second argument cannot be zero. at com.tutorialspoint.ExcepTest.divide(ExcepTest.java:13) at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8) More Examples Example 1: Throw an exception on invalid arguments Following example shows the use of throw and throws keywords to send an exception in case a invalid argument is passed and handle the exception. We”re calling a divide method which checks if second parameter is zero then it will throw an Exception with a custom message. As Exception is a checked exception, the divide method is required to declares throws statement. Now as parent method is to either handle the exception or declares the throws exception, we”re handling the exception and printing the message. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; try { System.out.println(“result:” + divide(a,b)); } catch (Exception e) { System.out.println(“Exception: ” + e); } } private static int divide(int a, int b) throws Exception { if(b == 0) { throw new Exception(“second argument cannot be zero.”); } return a / b; } } Output Exception: java.lang.Exception: second argument cannot be zero. Example 2: Using throws and throw in main and other method Following example shows the use of throw and throws keywords to send an exception in case a invalid argument is passed and exception is not handled. We”re calling a divide method which checks if second parameter is zero then it will throw an Exception with a custom message. As Exception is a checked exception, the divide method is required to declares throws statement. Now as parent method is to either handle the exception or declares the throws exception, we”re declaring to throw the exception and JVM will handle the exception. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) throws Exception { int a = 3; int b = 0; System.out.println(“result:” + divide(a,b)); } private static int divide(int a, int b) throws Exception { if(b == 0) { throw new Exception(“second argument cannot be zero.”); } return a / b; } } Output Exception in thread “main” java.lang.Exception: second argument cannot be zero. at com.tutorialspoint.ExcepTest.divide(ExcepTest.java:15) at com.tutorialspoint.ExcepTest.main(ExcepTest.java:9) Print Page Previous Next Advertisements ”;
Java – Block Synchronization
Java – Block Synchronization ”; Previous Next When we start two or more threads within a Java program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Block Synchronization in Java Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Syntax Following is the general form of the synchronized statement − synchronized(objectidentifier) { // Access shared variables and other shared resources } Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, they print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, then it prints counter very much in sequence for both the threads. Multithreading Example without Synchronization Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread. Example package com.tutorialspoint; class PrintDemo { public void printCount() { try { for(int i = 5; i > 0; i–) { Thread.sleep(50); System.out.println(“Counter — ” + i ); } } catch (Exception e) { System.out.println(“Thread interrupted.”); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo printDemo; ThreadDemo( String name, PrintDemo pd) { threadName = name; printDemo = pd; } public void run() { printDemo.printCount(); System.out.println(“Thread ” + threadName + ” exiting.”); } public void start () { System.out.println(“Starting ” + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { PrintDemo printDemo = new PrintDemo(); ThreadDemo t1 = new ThreadDemo( “Thread – 1 “, printDemo ); ThreadDemo t2 = new ThreadDemo( “Thread – 2 “, printDemo ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println(“Interrupted”); } } } Output This produces a different result every time you run this program − Starting Thread – 1 Starting Thread – 2 Counter — 5 Counter — 5 Counter — 4 Counter — 4 Counter — 3 Counter — 3 Counter — 2 Counter — 2 Counter — 1 Counter — 1 Thread Thread – 1 exiting. Thread Thread – 2 exiting. Multithreading Example with Synchronization at Block level Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. We”ve put synchronized keyword over a block so that counter increment code is now locked as per the object during method execution. We”re using current object as lock which we”re passing in the synchronized block as parameter. Example package com.tutorialspoint; class PrintDemo { public void printCount() { try { for(int i = 5; i > 0; i–) { Thread.sleep(50); System.out.println(“Counter — ” + i ); } } catch (Exception e) { System.out.println(“Thread interrupted.”); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo printDemo; ThreadDemo( String name, PrintDemo pd) { threadName = name; printDemo = pd; } public void run() { synchronized(printDemo) { printDemo.printCount(); } System.out.println(“Thread ” + threadName + ” exiting.”); } public void start () { System.out.println(“Starting ” + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { PrintDemo printDemo = new PrintDemo(); ThreadDemo t1 = new ThreadDemo( “Thread – 1 “, printDemo ); ThreadDemo t2 = new ThreadDemo( “Thread – 2 “, printDemo ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println(“Interrupted”); } } } Output This produces the same result every time you run this program − Starting Thread – 1 Starting Thread – 2 Counter — 5 Counter — 4 Counter — 3 Counter — 2 Counter — 1 Thread Thread – 1 exiting. Counter — 5 Counter — 4 Counter — 3 Counter — 2 Counter — 1 Thread Thread – 2 exiting. Multithreading Example with Synchronization at Method level Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. W”ve put synchronized keyword over a method this time so that complete method is locked as per the object during method execution. Example package com.tutorialspoint; class PrintDemo extends Thread { public void printCount() { try { for(int i = 5; i > 0; i–) { Thread.sleep(50); System.out.println(“Counter — ” + i ); } } catch (Exception e) { System.out.println(“Thread ” + Thread.currentThread().getName()+” interrupted.”); } } public synchronized void run() { printCount(); System.out.println(“Thread ” + Thread.currentThread().getName() + ” exiting.”); } } public class TestThread { public static void main(String args[]) { PrintDemo printDemo = new PrintDemo(); Thread t1 = new Thread(printDemo ); Thread t2 = new Thread(printDemo ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println(“Interrupted”); } } } Output This
Java – Thread Group
Java – ThreadGroup Class ”; Previous Next ThreadGroup Class The Java ThreadGroup class represents a set of threads. It can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent. ThreadGroup Class Declaration Following is the declaration for java.lang.ThreadGroup class − public class ThreadGroup extends Object implements Thread.UncaughtExceptionHandler ThreadGroup Class Constructors Sr.No. Constructor & Description 1 ThreadGroup(String name) This constructs a new thread group. 2 ThreadGroup(ThreadGroup parent, String name) This creates a new thread group. ThreadGroup Class Methods Sr.No. Method & Description 1 int activeCount() This method returns an estimate of the number of active threads in this thread group. 2 int activeGroupCount() This method returns an estimate of the number of active groups in this thread group. 3 void checkAccess() This method determines if the currently running thread has permission to modify this thread group. 4 void destroy() This method Destroys this thread group and all of its subgroups. 5 int enumerate(Thread[] list) This method copies into the specified array every active thread in this thread group and its subgroups. 6 int enumerate(Thread[] list, boolean recurse) This method copies into the specified array every active thread in this thread group. 7 int enumerate(ThreadGroup[] list) This method copies into the specified array references to every active subgroup in this thread group. 8 int enumerate(ThreadGroup[] list, boolean recurse) This method copies into the specified array references to every active subgroup in this thread group. 9 int getMaxPriority() This method returns the maximum priority of this thread group. 10 String getName() This method returns the name of this thread group. 11 ThreadGroup getParent() This method returns the parent of this thread group. 12 void interrupt() This method interrupts all threads in this thread group. 13 boolean isDaemon() This method Tests if this thread group is a daemon thread group. 14 boolean isDestroyed() This method tests if this thread group has been destroyed. 15 void list() This method prints information about this thread group to the standard output. 16 boolean parentOf(ThreadGroup g) This method tests if this thread group is either the thread group argument or one of its ancestor thread groups. 17 void setDaemon(boolean daemon) This method changes the daemon status of this thread group. 18 void setMaxPriority(int pri) This method sets the maximum priority of the group. 19 String toString() This method returns a string representation of this Thread group. 20 void uncaughtException(Thread t, Throwable e) This method called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific Thread.UncaughtExceptionHandler installed. Methods Inherited This class inherits methods from the following classes − java.lang.Object Example of ThreadGroup Class in Java Following example showcases the usage of ThreadGroup in a multithreaded program. package com.tutorialspoint; public class ThreadGroupDemo implements Runnable { public static void main(String[] args) { ThreadGroupDemo tg = new ThreadGroupDemo(); tg.func(); } public void func() { try { // create a parent ThreadGroup ThreadGroup pGroup = new ThreadGroup(“Parent ThreadGroup”); // create a child ThreadGroup for parent ThreadGroup ThreadGroup cGroup = new ThreadGroup(pGroup, “Child ThreadGroup”); // create a thread Thread t1 = new Thread(pGroup, this); System.out.println(“Starting ” + t1.getName() + “…”); t1.start(); // create another thread Thread t2 = new Thread(cGroup, this); System.out.println(“Starting ” + t2.getName() + “…”); t2.start(); // display the number of active threads System.out.println(“Active threads in “” + pGroup.getName() + “” = ” + pGroup.activeCount()); // block until the other threads finish t1.join(); t2.join(); } catch (InterruptedException ex) { System.out.println(ex.toString()); } } // implements run() public void run() { for(int i = 0;i < 1000;i++) { i++; } System.out.println(Thread.currentThread().getName() + ” finished executing.”); } } Output Let us compile and run the above program, this will produce the following result − Starting Thread-0… Starting Thread-1… Thread-0 finished executing. Active threads in “Parent ThreadGroup” = 1 Thread-1 finished executing. Print Page Previous Next Advertisements ”;
JVM – Java Virtual Machine
JVM (Java Virtual Machine) Architecture ”; Previous Next What is JVM (Java Virtual Machine)? The JVM (Java Virtual Machine) is a virtual machine, an abstract computer that has its own ISA, memory, stack, heap, etc. It runs on the host OS and places its demands for resources on it. The JVM (Java Virtual Machine) is a specification and can have different implementations, as long as they adhere to the specs. The specs can be found in the below link − https://docs.oracle.com Oracle has its own JVM implementation (called the HotSpot JVM), the IBM has its own (the J9 JVM, for example). The operations defined inside the spec are given below (source − Oracle JVM Specs) The ”class” file format Data types Primitive types and values Reference types and values Run-time data areas Frames Representation of objects Floating-point arithmetic Special methods Exceptions Instruction set summary Class libraries Public design, private implementation JVM (Java Virtual Machine) Architecture The architecture of the HotSpot JVM 3 is shown below − The execution engine comprises the garbage collector and the JIT compiler. The JVM comes in two flavors − client and server. Both of these share the same runtime code but differ in what JIT is used. We shall learn more about this later. The user can control what flavor to use by specifying the JVM flags -client or -server. The server JVM has been designed for long-running Java applications on servers. The JVM comes in 32b and 64b versions. The user can specify what version to use by using -d32 or -d64 in the VM arguments. The 32b version could only address up to 4G of memory. With critical applications maintaining large datasets in memory, the 64b version meets that need. Components of JVM (Java Virtual Machine) Architecture The following are the main components of JVM (Java Virtual Machine) architecture: 1. Class Loader The JVM manages the process of loading, linking and initializing classes and interfaces in a dynamic manner. During the loading process, the JVM finds the binary representation of a class and creates it. During the linking process, the loaded classes are combined into the run-time state of the JVM so that they can be executed during the initialization phase. The JVM basically uses the symbol table stored in the run-time constant pool for the linking process. Initialization consists of actually executing the linked classes. The following are the types of class loaders: BootStrap class loader: This class loader is on the top of the class loader hierarchy. It loads the standard JDK classes in the JRE”s lib directory. Extension class loader: This class loader is in the middle of the class loader hierarchy and is the immediate child of the bootstrap class loader and loads the classes in the JRE”s libext directory. Application class loader: This class loader is at the bottom of the class loader hierarchy and is the immediate child of the application class loader. It loads the jars and classes specified by the CLASSPATH ENV variable. 2. Linking and Initialization The linking process consists of the following three steps − Verification − This is done by the Bytecode verifier to ensure that the generated .class files (the Bytecode) are valid. If not, an error is thrown and the linking process comes to a halt. Preparation − Memory is allocated to all static variables of a class and they are initialized with the default values. Resolution − All symbolic memory references are replaced with the original references. To accomplish this, the symbol table in the run-time constant memory of the method area of the class is used. Initialization is the final phase of the class-loading process. Static variables are assigned original values and static blocks are executed. 3. Runtime Data Areas The JVM spec defines certain run-time data areas that are needed during the execution of the program. Some of them are created while the JVM starts up. Others are local to threads and are created only when a thread is created (and destroyed when the thread is destroyed). These are listed below − PC (Program Counter) Register It is local to each thread and contains the address of the JVM instruction that the thread is currently executing. Stack It is local to each thread and stores parameters, local variables and return addresses during method calls. A StackOverflow error can occur if a thread demands more stack space than is permitted. If the stack is dynamically expandable, it can still throw OutOfMemoryError. Heap It is shared among all the threads and contains objects, classes” metadata, arrays, etc., that are created during run-time. It is created when the JVM starts and is destroyed when the JVM shuts down. You can control the amount of heap your JVM demands from the OS using certain flags (more on this later). Care has to be taken not to demand too less or too much of the memory, as it has important performance implications. Further, the GC manages this space and continually removes dead objects to free up the space. Method Area This run-time area is common to all threads and is created when the JVM starts up. It stores per-class structures such as the constant pool (more on this later), the code for constructors and methods, method data, etc. The JLS does not specify if this area needs to be garbage collected, and hence, implementations of the JVM may choose to ignore GC. Further, this may or may not expand as per the application”s needs. The JLS does not mandate anything with regard to this. Run-Time Constant Pool The JVM maintains a per-class/per-type data structure that acts as the symbol table (one of its many roles) while linking the loaded classes. Native Method Stacks When a thread invokes a native method, it enters a new world in which the structures and security restrictions of the Java virtual machine no longer hamper its freedom. A native method can likely access the runtime data areas of the virtual machine (it depends
Java – Class Attributes
Java – Class Attributes ”; Previous Next Java Class Attributes Java class attributes are the variables that are bound in a class i.e., the variables which are used to define a class are class attributes. A class attribute defines the state of the class during program execution. A class attribute is accessible within class methods by default. For example, there is a class “Student” with some data members (variables) like roll_no, age, and name. These data members are considered class attributes. Creating (Declaring) Java Class Attributes To create (declare) a class attribute, use the access modifier followed by the data type and attribute name. It”s similar to declaring a variable. Syntax Use the below syntax to declare a class attribute: access_modifier type attribute_name; Example: Declaring Java Class Attributes public class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } } In above class, we”ve fields like breed, age, and color which are also known as class attributes. Accessing Java Class Attributes To access the class attribute, you need to create an object first and then use the dot (.) operator with the object name. Class attributes can be also called within the class methods directly. Syntax Use the below syntax to access a class attribute: object_name.attribute_name; Example: Accessing Java Class Attributes Consider this example, demonstrating how to access the class attributes. class Dog { // Declaring and initializing the attributes String breed = “German Shepherd”; int age = 2; String color = “Black”; } public class Main { public static void main(String[] args) { // Creating an object of the class Dog Dog obj = new Dog(); // Accessing class attributes & printing the values System.out.println(obj.breed); System.out.println(obj.age); System.out.println(obj.color); } } Output German Shepherd 2 Black Modifying Java Class Attributes To modify a class attribute, access the attribute and assign a new value using the assignment (=) operator. Syntax Use the below syntax to modify a class attribute: object_name.attribute_name = new_value; Example: Modifying Java Class Attributes Consider this example, demonstrating how to modify the class attributes. class Dog { // Declaring and initializing the attributes String breed = “German Shepherd”; int age = 2; String color = “Black”; } public class Main { public static void main(String[] args) { // Creating an object of the class Dog Dog obj = new Dog(); // Accessing class attributes & printing the values System.out.println(“Before modifying:”); System.out.println(obj.breed); System.out.println(obj.age); System.out.println(obj.color); // Modifying class attributes obj.breed = “Golden Retriever”; obj.age = 3; obj.color = “Golden”; // Printing System.out.println(“nAfter modifying:”); System.out.println(obj.breed); System.out.println(obj.age); System.out.println(obj.color); } } Output Before modifying: German Shepherd 2 Black After modifying: Golden Retriever 3 Golden Making Java Class Attributes Read Only You can also make the class attributes read-only by using the final keyword after the access modifier while declaring an attribute. Syntax Use the below syntax to make class attribute read-only: access_modifier final data_type attribute_name; Example: Making Java Class Attributes Read Only In the below example, the name attribute is set to read-only using the final keyword. Now this attribute can not be modified and JVM will complain if we try to modify this attribute. package com.tutorialspoint; class Dog { final String name = “Tommy”; } public class Tester { public static void main(String[] args) { Dog dog = new Dog(); dog.name = “Tommy”; // Error while modifying name System.out.println(dog.name); } } Output Compile and run Tester. This will produce the following result − Exception in thread “main” java.lang.Error: Unresolved compilation problem: The final field Dog.name cannot be assigned at com.tutorialspoint.Tester.main(Tester.java:10) Print Page Previous Next Advertisements ”;
Java – Static Synchronization ”; Previous Next Synchronization is a way that establishes cooperation between multiple threads trying to access shared resources. It is necessary for reliable thread interaction and is done using the ”synchronized” keyword. Here, threads are small sub processes of a big operation. In this article, we are going to learn static synchronization and how they manage threads so that they can work efficiently. Multithreading Multithreading is a feature of Java programming language that allows us to perform multiple operations simultaneously. In it, the operation gets divided into multiple smaller parts called a thread. Each thread performs one independent task without affecting the other thread’s performance. The main benefit of multithreading is the optimal use of resources like CPU and it boosts the execution time of allocated operations. Synchronization The threads are executed in an asynchronous manner therefore, it is impossible to predict how they are going to interact. Sometimes, several threads may try to access a single resource, then a problem arises because it might create a faulty result of the allocated task. At this time, Synchronization comes into the picture and ensures that a single thread can access the given resource at one time. This is possible because of the lock object that guards the synchronized region. When a thread enters that region, the lock gets assigned to it and it releases the lock after executing its task. Till the resources are busy other threads wait in a queue for their turn. Static Synchronization in Java When we use this type of synchronization then, if a thread is in the static synchronized region, all other threads trying to access this region will be blocked. Since static methods belong to the class therefore, static synchronization applies class level lock. Syntax of Static Synchronization static synchronized returnType nameOfMethod( Type parameters) { // code } Here returnType may be void or any primitive data type. parameters contains name of the variable followed by datatype. Multithreading Without Static Synchronization Here is a simple example which may or may not print counter value in sequence and every time we run it, it produces a different result based on CPU availability to a thread. Example of Multithreading Without Static Synchronization package com.tutorialspoint; class PrintDemo { public static void printCount() { try { for(int i = 5; i > 0; i–) { Thread.sleep(50); System.out.println(“Counter — ” + i ); } } catch (Exception e) { System.out.println(“Thread interrupted.”); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo( String name) { threadName = name; } public void run() { PrintDemo.printCount(); System.out.println(“Thread ” + threadName + ” exiting.”); } public void start () { System.out.println(“Starting ” + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { ThreadDemo t1 = new ThreadDemo( “Thread – 1 ” ); ThreadDemo t2 = new ThreadDemo( “Thread – 2 ” ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println(“Interrupted”); } } } This produces a different result every time you run this program − Output Starting Thread – 1 Starting Thread – 2 Counter — 5 Counter — 5 Counter — 4 Counter — 4 Counter — 3 Counter — 3 Counter — 2 Counter — 2 Counter — 1 Counter — 1 Thread Thread – 1 exiting. Thread Thread – 2 exiting. Multithreading With Static Synchronization Here is the same example which prints counter value in sequence and every time we run it, it produces the same result. W”ve put synchronized keyword over a method this time so that complete method is locked as per the object during method execution. Example of Multithreading With Static Synchronization package com.tutorialspoint; class PrintDemo { public static synchronized void printCount() { try { for(int i = 5; i > 0; i–) { Thread.sleep(50); System.out.println(“Counter — ” + i ); } } catch (Exception e) { System.out.println(“Thread interrupted.”); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo( String name) { threadName = name; } public void run() { PrintDemo.printCount(); System.out.println(“Thread ” + threadName + ” exiting.”); } public void start () { System.out.println(“Starting ” + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { ThreadDemo t1 = new ThreadDemo( “Thread – 1 ” ); ThreadDemo t2 = new ThreadDemo( “Thread – 2 ” ); t1.start(); t2.start(); // wait for threads to end try { t1.join(); t2.join(); } catch ( Exception e) { System.out.println(“Interrupted”); } } } This produces following result every time you run this program − Output Starting Thread – 1 Starting Thread – 2 Counter — 5 Counter — 4 Counter — 3 Counter — 2 Counter — 1 Thread Thread – 1 exiting. Counter — 5 Counter — 4 Counter — 3 Counter — 2 Counter — 1 Thread Thread – 2 exiting. Print Page Previous Next Advertisements ”;