How to perform multiple tasks by multiple threads (multitasking in multithreading)?


If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example: Program of performing two tasks by two threads

  1. class Simple1 extends Thread{  
  2.  public void run(){  
  3.    System.out.println("task one");  
  4.  }  
  5. }  
  6.   
  7. class Simple2 extends Thread{  
  8.  public void run(){  
  9.    System.out.println("task two");  
  10.  }  
  11. }  
  12.   
  13.  class TestMultitasking3{  
  14.  public static void main(String args[]){  
  15.   Simple1 t1=new Simple1();  
  16.   Simple2 t2=new Simple2();  
  17.   
  18.   t1.start();  
  19.   t2.start();  
  20.  }  
Output:task one
       task two



How to perform single task by multiple threads?

If you have to perform single task by many threads, have only one run() method.For example: Program of performing single task by multiple threads
  1. class TestMultitasking1 extends Thread{  
  2.  public void run(){  
  3.    System.out.println("task one");  
  4.  }  
  5.  public static void main(String args[]){  
  6.   TestMultitasking1 t1=new TestMultitasking1();  
  7.   TestMultitasking1 t2=new TestMultitasking1();  
  8.   TestMultitasking1 t3=new TestMultitasking1();  
  9.   
  10.   t1.start();  
  11.   t2.start();  
  12.   t3.start();  
  13.  }  
  14. }  

Output:task one
       task one
       task one
Program of performing single task by multiple threads
  1. class TestMultitasking2 implements Runnable{  
  2. public void run(){  
  3. System.out.println("task one");  
  4. }  
  5.   
  6. public static void main(String args[]){  
  7. Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of TestMultitasking2 class  
  8. Thread t2 =new Thread(new TestMultitasking2());  
  9.   
  10. t1.start();  
  11. t2.start();  
  12.   
  13.  }  
  14. }  

Output:task one
       task one

Note: Each thread run in a separate callstack.

MultipleThreadsStack

What if we call run() method directly instead start() method?

  • Each thread starts in a separate call stack.
  • Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
  1. class TestCallRun1 extends Thread{  
  2.  public void run(){  
  3.    System.out.println("running...");  
  4.  }  
  5.  public static void main(String args[]){  
  6.   TestCallRun1 t1=new TestCallRun1();  
  7.   t1.run();//fine, but does not start a separate call stack  
  8.  }  
  9. }  

Output:running...
 
MainThreadStack 
 
Problem if you direct call run() method
  1. class TestCallRun2 extends Thread{  
  2.  public void run(){  
  3.   for(int i=1;i<5;i++){  
  4.     try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
  5.     System.out.println(i);  
  6.   }  
  7.  }  
  8.  public static void main(String args[]){  
  9.   TestCallRun2 t1=new TestCallRun2();  
  10.   TestCallRun2 t2=new TestCallRun2();  
  11.    
  12.   t1.run();  
  13.   t2.run();  
  14.  }  
 
Output:1
       2
       3
       4
       5
       1
       2
       3
       4
       5
 
As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.
 
 
 

Can we start a thread twice ?



No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Let's understand it by the example given below:
  1. public class TestThreadTwice1 extends Thread{  
  2.  public void run(){  
  3.    System.out.println("running...");  
  4.  }  
  5.  public static void main(String args[]){  
  6.   TestThreadTwice1 t1=new TestThreadTwice1();  
  7.   t1.start();  
  8.   t1.start();  
  9.  }  
  10. }  
  11.  
  12.  
  13. Output:
     running
           Exception in thread "main" java.lang.IllegalThreadStateException
     

Broadcast receiver runs in which thread, by default?

By default every component of android run on main thread (UI thread) so broadcast receiver by default runs on Main thread.

How many types of memory areas are allocated by JVM?

Many types:

* Class(Method) Area
* Heap
* Stack
* Program Counter Register
* Native Method Stack

What is difference between JDK,JRE and JVM?

JVM

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification.

JVMs are available for many hardware and software platforms (so JVM is platform dependent).

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

Important methods of StringBuffer class

public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.

public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.

public synchronized StringBuffer delete(int startIndex, int endIndex):is used to delete the string from specified startIndex and endIndex.

public synchronized StringBuffer reverse(): is used to reverse the string.

public int capacity(): is used to return the current capacity.

public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.

public char charAt(int index): is used to return the character at the specified position.

public int length(): is used to return the length of the string i.e. total number of characters.

public String substring(int beginIndex): is used to return the substring from the specified beginIndex.

public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.

Java String class methods

The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.

Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.

String s="Sachin";  System.out.println(s.toUpperCase());//SACHIN  System.out.println(s.toLowerCase());//sachin  System.out.println(s);//Sachin(no change in original)  

Output

SACHIN sachin Sachin

Java String trim() method

The string trim() method eliminates white spaces before and after string.

String s="  Sachin  ";  System.out.println(s);//  Sachin    System.out.println(s.trim());//Sachin  
Output
Sachin Sachin

Java String startsWith() and endsWith() method

String s="Sachin";   System.out.println(s.startsWith("Sa"));//true   System.out.println(s.endsWith("n"));//true  
Output
true true

Java String charAt() method

The string charAt() method returns a character at specified index.

String s="Sachin";  System.out.println(s.charAt(0));//S  System.out.println(s.charAt(3));//h  
Output
S h

Java String length() method

The string length() method returns length of the string.

String s="Sachin";  System.out.println(s.length());//6  

Output
6

Java String intern() method

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

String s=new String("Sachin");  String s2=s.intern();  System.out.println(s2);//Sachin  

Output
Sachin

Java String valueOf() method

The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.

int a=10;  String s=String.valueOf(a);  System.out.println(s+10);  

Output:

1010

Java String replace() method

The string replace() method replaces all occurrence of first sequence of character with second sequence of character.

String s1="Java is a programming language. Java is a platform. Java is an Island.";    String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"    System.out.println(replaceString);    

Output:

Kava is a programming language. Kava is a platform. Kava is an Island

Are there any other classes whose objects are immutable?

Yes, classes like Character, Byte, Integer, Float, Double, Long... called Wrapper classes are immutable. Classes like BigInteger, BigDecimal are also immutable.

What is the difference between String and StringBuffer classes?

String class objects are immutable and hence their contents cannot modified whereas StringBuffer class objects are mutable, so they can be modified.

Moreover the methods that directly manipulate data of the objects are not available in String class and such methods are available in StringBuffer class.

Explain the difference between the following two statements

1) String s = "Hello":
2) String s = new String (" Hello");

In the first statement, assignment operator is used to assign the string literal to the String variable s.  In this case, JVM first of all checks whether the same object is already available in the string constant pool. If it is available, then it creates another reference to it. If the same object is not available then it creates another object with the content "Hello" and stores it into the string constant pool.

In the second statement, new operator is used create the string object. In this case, JVM always creates a new object without looking in the string constant pool.

What is object reference?

Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object.

What are the different way if creating String in Java?

There are 3 way of creating string in Java.
a) We can create a string just by assigning a group of characters to a string type variable.

String s = "hello";

b) We can create an object to String class  by allocating memory using new operator. This is just like creating an object to any class.

String s = new String ("hello");

Here we doing two things. First, we creating object using new operator. Then, we are storing the string: "hello" into the object.

c) The third way of creating the strings is by converting the character arrays into strings. Let us take a character type array: art[  ].

char arr[  ] = { 'c' , 'h' , 'a', 'i' , 'r', 's' } ;

Now create a string object by passing the array name to it, as:
String s = new String (arr) ;

Now the string s contains the string value "chairs" . This means all the characters of the array into the string.

Note

String s = new String (arr, 2, 3);

Here, starting from 2nd character a total of 3 characters are copied into the string s., the 0th character in the array is 'c' and the 2nd character is 'a' . Staring from 'a', a total of three characters implies 'air'. So these three characters are copied into the string s.

Can we call a class as a data type?

Yes, a class is also called user defined data type. This is because a user can create a class.

Is String a class or data type?

String is a class in java.lang package. But in Java, all classes also considered as data types, so we can take String as a data type also.

On which memory, array are created in Java?

Arrays are created on dynamic memory by JVM. There is no question of static memory in Java, every thing (variable, array and object etc) is created on dynamic memory only.

What is the difference between System.out and System.err ?

System.out and System.err both represent the monitor by default and hence can be used to display normal messages and results but System.out is used to display normal messages and results whereas System.err is used to display error messages.

What is the difference between System.exit(0) and System.exit(1) ?

System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the program because of some error encountered in the program.

What is the difference between return and System.exit(0) ?

return statement is used inside a method to come out of it. System.exit(0) is used in a method to come out of the program.

What is the use of continue statement?

When continue is executed, subsequent statements in the loop are not executed and control of execution goes back to the next repetition of the loop.

Why goto statements are not available in Java?

1) goto statement lead to confusion for a programmer. Especially in large program, if several goto statements are used then the programmer would perplexed while understanding the flow.
2) goto statements make documentation of a program difficult.
3) goto statements are not part of structured programming.
Because of these reasons the goto statement is not supported in java

Note: The goto statement is reserved keyword in Java.

What are the uses of break statement?

The break statement can be used in 3 ways:
1) break is used inside a loop to come out of it.
2) break is used inside the switch block to come out of the switch block.
3) break can be used in nested blocks to go to the end of a block.

Write a program to display stars in a right angle triangle form

What is the difference between >> and >>> ?

Both bitwise right shift operator (>>) and bitwise zero fill right shift operator (>>>) are used to shift the bits towards right.

The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bit.

How are positive and negative numbers represented internally?

Positive numbers are represented in binary using 1's complement notation and negative numbers are represented by using 2's complement notation.

What is the difference between float and double?

float can represent up to 7 digits accurately after decimal point whereas double can represent up to 15 digits accurately after decimal point.

Java program to bubble sort

Java program to bubble sort: This code sorts numbers inputted by user using Bubble sort algorithm.

Java programming code

import java.util.Scanner;
 
class BubbleSort {
  public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Input number of integers to sort");
    n = in.nextInt();
 
    int array[] = new int[n];
 
    System.out.println("Enter " + n + " integers");
 
    for (c = 0; c < n; c++) 
      array[c] = in.nextInt();
 
    for (c = 0; c < ( n - 1 ); c++) {
      for (d = 0; d < n - c - 1; d++) {
        if (array[d] > array[d+1]) /* For descending order use < */
        {
          swap       = array[d];
          array[d]   = array[d+1];
          array[d+1] = swap;
        }
      }
    }
 
    System.out.println("Sorted list of numbers");
 
    for (c = 0; c < n; c++) 
      System.out.println(array[c]);
  }
}
Complexity of bubble sort is O(n2) which makes it a less frequent option for arranging in sorted order when quantity of numbers is high.

Output of program:



You can also use sort method of Arrays class to sort integers in ascending order but remember that sort method uses a variation of Quick sort algorithm.
import java.util.Arrays;
 
class Sort
{
  public static void main(String args[])
  {
    int data[] = { 4, -5, 2, 6, 1 };
 
    Arrays.sort(data);
 
    for (int c: data) 
    {
      System.out.println(c);
    }
  }
}

Java program to multiply two matrices

This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not.

Java programming code

import java.util.Scanner;
 
class MatrixMultiplication
{
   public static void main(String args[])
   {
      int m, n, p, q, sum = 0, c, d, k;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of rows and columns of first matrix");
      m = in.nextInt();
      n = in.nextInt();
 
      int first[][] = new int[m][n];
 
      System.out.println("Enter the elements of first matrix");
 
      for ( c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
            first[c][d] = in.nextInt();
 
      System.out.println("Enter the number of rows and columns of second matrix");
      p = in.nextInt();
      q = in.nextInt();
 
      if ( n != p )
         System.out.println("Matrices with entered orders can't be multiplied with each other.");
      else
      {
         int second[][] = new int[p][q];
         int multiply[][] = new int[m][q];
 
         System.out.println("Enter the elements of second matrix");
 
         for ( c = 0 ; c < p ; c++ )
            for ( d = 0 ; d < q ; d++ )
               second[c][d] = in.nextInt();
 
         for ( c = 0 ; c < m ; c++ )
         {
            for ( d = 0 ; d < q ; d++ )
            {   
               for ( k = 0 ; k < p ; k++ )
               {
                  sum = sum + first[c][k]*second[k][d];
               }
 
               multiply[c][d] = sum;
               sum = 0;
            }
         }
 
         System.out.println("Product of entered matrices:-");
 
         for ( c = 0 ; c < m ; c++ )
         {
            for ( d = 0 ; d < q ; d++ )
               System.out.print(multiply[c][d]+"\t");
 
            System.out.print("\n");
         }
      }
   }
}

Output of program:



This is a basic method of multiplication, there are more efficient algorithms available. Also this approach is not recommended for sparse matrices which contains a large number of elements as zero.