Translate

Thursday, June 9, 2016

Life cycle of a thread

Thread lifecycle-


There are 5 states in a thread life cycle.
1. New
2.Runnable
3.Running
4.Blocked
5.Terminated


1.New

The thread is in new state if you create the instance of Thread class but before invocation of start() method.

2.Runnable

The thread is in runnable state if you invoke the thread but thread scheduler has not selected to it to be the running thread.

3.Running

The thread is in running state if thread scheduler selected it.

4.Blocked

The thread is in blocked state if thread is still alive, but not currently not eligible to run because lack  of some resources.

5.Terminated

The thread is in blocked state if thread completes it's execution.



What is thread?

Thread- 


Thread is a light weight sub process. It is the smallest unit of execution and it execute separately.
Means thread are independent to each other and if any exception occurs in one thread, it does not affect the other threads of the process.
In the diagram p1, p2 & p3 are the sub process(Thread) of process3.   







Defining a thread in java

How to define a thread in java?


There are two ways to define a thread in java.

1.By implementing Runnable interface

2.By extending Thread class

1. By implementing Runnable interface

public class Mythread implements Runnable
{

public void run() {
System.out.print("thread executed");
}
public static void main(String[] args) {
Mythread mt=new Mythread();

Thread t1=new Thread(mt);

t1.start();
         
               System.out.print("main thread executed");
          
}

}


2.By extending Thread class




public class Mythread extends Thread
{

public void run() {
System.out.print("thread executed");
}
public static void main(String[] args) {
Mythread mt=new Mythread();
mt.start();
System.out.print("main thread executed");
}

}

Wednesday, June 8, 2016

Basic question of threading

1- What is Multitasking?



It is the concept of executing several tasks simultaneously.

There are two types of multitasking.

a. Process based Multitasking

b. Thread based Multitasking

2-What is process based multitasking?


Executing several tasks simultaneously where each tasks is a separate independent program(Process) is called process based multitasking. Each program execute in a separate memory block. So process based multitasking is also known as heavy weight multitasking. Process based multitasking is best suitable at OS level.

example- While typing a java program in the editor we can listen audio songs from same system at the same time we can download some files from internet. All tasks will be executed simultaneously and independent of each other.

3-What is thread based multitasking?


Executing several tasks simultaneously where each tasks is a separate independent part of the same process is called as a thread based multitasking and independent part is called as a thread.
Thread based multitasking is best suitable at programmatic level.

The main advantage of multitasking is to reduce response time of system and improve performance.

Main important application area of multi-threading to develop

a. Multimedia graphics
b. Animations
c. Video games 
d. Web server and app server

example-Microsoft worldpad, While typing some text on editor the spell checker program also execute simultaneously.





Tuesday, June 7, 2016

Threading

C Interview Questions

Pattern Programs

Write a program to print a following given pattern


 54321012345
   432101234
     3210123
       21012
         101
           0


            0
          101
        21012
      3210123
    432101234
  54321012345


                    z
                  zyz
                zyxyz
              zyxwxyz
           zyxwvwxyz
             zyxwxyz
               zyxyz
                 zyz
                   z


        5
      545
    54345
  5432345
543212345
  5432345
    54345
      545
        5


Core java Interview Questions

Home


String handling related questions and programs.

Some basic methods of String class.

Method-1 toCharArray()

toCharArray() is a method of string class which is used for convert a string into a Character type array.It returns a character type array.

example-  String s="hello";

char c=s.toCharArray();

o/p {'h','e','l','l','o'};

Method-2 charAt(int i)

charAt() method is used for get the character at the specific index.It returns a character.

example-  String s="hello";

char c=s.charAt(0);

o/p-  h

Method-3 length()

length() method is used for find the total length of string.It returns a integer number

example-  String s="hello";

int length=s.length();

o/p- 5

Method-4 toUpperCase() & toLowerCase()

Both methods are used for changing the case of a string.Both methods return String.

String s="hello";

String s1="HELLO";

s=s.toUpperCase();  // o/p  HELLO

s1=s1.toLowerCase();  // o/p  hello


Method-5 replace(String old, String new)

This method is used for replace a existing string with a new String.It returns a string.

String s="hello";

s=s.replace("hello","bye");

o/p bye

Method-5 split(regular expression)


This method is used for split the string according to regular expression and it returns a string type array.

String s="hello, how are you";

String splitarray[]=s.split("[\\S][ ]+");

or

String splitarray[]=s.split(" ");

o/p {"hello,","how","are","you"};



Importance of SCP.

What is SCP?

What is the reason behind of immutability of string object?


SCP stands for String Constant Pool. It is a special memory area.

in our program if a string object is repeatedly required then it is not recommended to create separate object for every requirement because it it creates performance and memory problems.
Instead of creating a separate object for every requirement we have to create only one object and we can reuse the same object for every requirement. So that performance and memory utilization will be improved.
This thing is possible because of SCP, hence the main advantage of SCP is memory utilization and performance will be improved.

But the main problem with SCP is, as several references pointing to the same object, by using one reference if we are trying to change the content then remaining references will be affeacted.
To overcome this problem SUN people implemented string object as immutable i.e. once we create a string object then we can not perform any changes in the existing object, if we are trying to perform any changes with those changes a new object will be created.

Hence SCP is the only reason for immutability of string object.

String s1="hello";

String s2="hello";

s2="bye";


String with equals method and == operator.

What will be the output?


String s1="hello";

String s2="hello";

String s3=new String("hello");

line-1  System.out.print(s1==s2);  // o/p true


line-2  System.out.print(s1==s3);    // o/p false


line-3  System.out.print(s1.equals(s2));    // o/p true


line-4  System.out.print(s1.equals(s3));     // o/p true

Because when we create string object by string literal then string object will get created in String Constant Pool  and if there are we create two object of same content then both reference point to the same object that's why line-1 give o/p true.

If we create string object by new keyword then always a new object will get created and ==  operator only compare references that's why line-2 give o/p false.

If we talk about equals method of object class then equals method also compare only references but string class override the equals method and for string class equals method compare the content of objects that's why line-3 & line-4 give o/p true.



Write a program to check whether a given string is palindrome or not in C.

#include<stdio.h>
#include<conio.h>
main()
{
      char ch[20];

      int a=1,b=0,c,d=0;

      printf("Enter the string=");

      scanf("%s",&ch);

      while(ch[a]!='\0')  // count the length of string
      {
         a++;
      }

      for(c=a-1; c>=0; c--)
      {
         if(ch[c]-ch[b]==0)
         {      
           d=0;
           }
           else
           {
               d=d+1;
               break;
               }
               b++;
               }
               if(d==0)
               {
                       printf("string is palindrome");
                       }
                       else
                       {
                           printf("string is not palindrome");
                           }            
      getch();
      }

Write a program to print a following given pattern.

O/P


Enter number of rows : 5
 54321012345
   432101234
     3210123
       21012
         101
           0

#include<stdio.h>
#include<conio.h>
int main()
{
 int num,r,c,sp;

 printf("Enter number of rows : ");

 scanf("%d",&num);
 
 for(r=0; r<=num; r++)
 {
   for(sp=r; sp>=0; sp--)
      {
       printf(" ");
      }
   for(c=num-r; c>=0; c--)
      {
       printf("%d",c);
      }
   for(c=1; c<=num-r; c++)
       {
       printf("%d",c);
       }

   printf("\n");
 }
 getch();
}

Write a program to print a following given pattern.

O/P


   Enter number of rows : 5
            0
          101
        21012
      3210123
    432101234
  54321012345


#include<stdio.h>
#include<conio.h>

int main()
{

 int num,r,c,sp;

 printf("Enter number of rows : ");

 scanf("%d",&num);

 for(r=0; r<=num; r++)

 {
   for(sp=num-r; sp>=0; sp--)

      {

         printf(" ");
       }

   for(c=r; c>=0; c--)

     {  
        
       printf("%d",c); 

      }

   for(c=1; c<=r; c++)

      { 

        printf("%d",c);

       }
          printf("\n");
 }

 getch();
}

Write a program to print a following given pattern.

    O/P             


                    z
                  zyz
                zyxyz
              zyxwxyz
           zyxwvwxyz
             zyxwxyz
               zyxyz
                 zyz
                   z



#include<stdio.h>
#include<conio.h>
main()
{
      int i=1,j,k,l,m;

      char ch[]={' ','v','w','x','y','z'};

      for(i=1,m=5; i<=5,m>=1; i++,m--)

      {
               for(j=5-i; j>=1; j--)

               printf(" ");

               for(k=5; k>=6-i; k--)

               printf("%c",ch[k]);

               for(l=m+1; l<=5;l++)

               printf("%c",ch[l]);

               printf("\n");

               }
                for(i=5,m=2; i>=1,m<=5; i--,m++)
      {
               for(j=0; j<=5-i; j++)

               printf(" ");

               for(k=5; k>6-i; k--)

               printf("%c",ch[k]);

              for(l=m+1; l<=5;l++)

              printf("%c",ch[l]);

               printf("\n");
               }
               getch();
               }

Write a program to print a following given pattern.


  o/p         

        5
      545
    54345
  5432345
543212345
  5432345
    54345
      545
        5


#include<stdio.h>
#include<conio.h>
main()
{
      int i=1,j,k,l,m;

      for(i=1,m=5; i<=5,m>=1; i++,m--)

      {
               for(j=5-i; j>=1; j--)

               printf(" ");

               for(k=5; k>=6-i; k--)

               printf("%d",k);

               for(l=m+1; l<=5;l++)

               printf("%d",l);

               printf("\n");

               }
                for(i=5,m=2; i>=1,m<=5; i--,m++)

      {
               for(j=0; j<=5-i; j++)

               printf(" ");

               for(k=5; k>6-i; k--)

               printf("%d",k);

              for(l=m+1; l<=5;l++)

              printf("%d",l);

               printf("\n");

               }
               getch();
               }

Write a program to check whether number is palindrome or not in C.

#include<stdio.h>

#include<conio.h>

main()
{
      int n,sum,r,temp;

      sum=0;

      printf("Enter the number which is check palindrome or not=");

      scanf("%d",&n);

      temp=n;

      while(n>0)
      {
                r=n%10;

                sum=(sum*10)+r;

                n=n/10;
                }
                if(temp==sum)
                {
                             printf("the number is palindrome");
                             }
                              else
                             {
                                printf("the number is not palindrome");
                                }
                                getch();
                                }        
               

Write a program to create a deadlock condition using two threads.


Child thread call join method on main thread and main thread call join method on child thread so child thread has to wait until completion of main thread and main thread also has to wait until completion of child thread and this condition is known as deadlock.

  class MyThread extends Thread {

static Thread t1;

public void run()
{

try
{

t1.join();    // call join method on thread t1
}

catch(InterruptedException e)
{

e.printStackTrace();
}

System.out.println("child thread");

}

}

  public class ThreadJoin
  {

 public static void main(String[] args) {

 MyThread.t1=Thread.currentThread();

 MyThread t2=new MyThread();

 t2.start();

 try {

t2.join();

} catch (InterruptedException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}

 System.out.println("deadlock");
}
  }


Write a program to count total number of words in a string using library function and regular expression.



package com.javahelp.stringprog;

import java.util.Scanner;

public class WordCount2 {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String s=sc.nextLine(); // enter the string

String []arr=s.split("[\\S][ ]+");    // \S shows except space

System.out.println(arr.length);
}
}

Write a program to count the frequency of each and every character of a string by using collection classes.

package com.javahelp.stringprog;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class CharFrequencyCount {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);

String s=sc.nextLine();       // enter the string

HashMap<Character, Integer> hm=new HashMap<Character, Integer>();

int count=0;             // variable to store count value

for(int i=0; i<s.length(); i++)
{

                        // check charcter exist in map or not

if(hm.containsKey(s.charAt(i)))          
{
count=hm.get(s.charAt(i))+1; 

// get the value of map and then store it again with increment by 1

hm.put(s.charAt(i), count);
}
else
{
count=1;
                               // new character add in map with count value 1
                              
                               hm.put(s.charAt(i),count);
}
}
                     // to iterate the hashmap convert hashmap into set

                  Set set=hm.entrySet(); 
Iterator it=set.iterator();
while(it.hasNext())
{

                     // set elements return entry value so typecast with enty
                          Map.Entry entry=(Map.Entry) it.next(); 

System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}

Why String class is immutable in java?



Because of string constant pool. When we create string object by string literal then string object will create in string constant pool and if you create another object by string literal of same content then only reference will get created and that reference point to the older object. So if  we change in one object then changes automatically reflected in another object. That's why string class is immutable in java, means if you change in existing object then new object will get created and the reference start point to the new object.

String s1="hello";

String s2="hello";

System.out.println(s1+" "+s2); // o/p hello hello

s2="bye";

System.out.println(s1+" "+s2); // o/p hello bye




Monday, June 6, 2016

Write a program to count the number of words in a string without using library function.


package com.javahelp.stringprog;

import java.util.Scanner;

public class WordCount {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine(); // enter the string

int count;    // for counting the total word

if(s.charAt(0)==' ')
{
count=-1;
}
else
{
count=0;
}
for(int i=0; i<s.length(); i++)
{

if(i+1<s.length())
{

                //check space on index i and also check i+1 != sapce then increase count 1

                if(s.charAt(i)==' ' && s.charAt(i+1)!=' ')
{
count++;
}
}
}
System.out.println(count+1);
}
}


Write a program to check whether a string is palindrome or not.



package com.javahelp.stringprog;

import java.util.Scanner;

public class StringPalindrome {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine(); // enter the string
int j=s.length()-1;  // assign the length of string to variable
int i=0;
for(; i<s.length(); i++)  
{
if(i<=j)  
{
if(s.charAt(i)==s.charAt(j)) // compare the string character from beginning and from the end
{
j--;
}
else
{
System.out.println("String is not palindrome");
break;
}
}
}
if(i>=j)
{
System.out.println("String is palindrome");
}
}
}



Write a program to print a reverse string.


Common program of interview.


package com.javahelp.stringprog;

import java.util.Scanner;

public class StringReverse {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);

String s=sc.nextLine(); // enter the string

for(int i=s.length()-1; i>=0; i--)
{
System.out.print(s.charAt(i));
}

}

}

Sunday, June 5, 2016

Program to check whether string is anagram or not?

Favorite question of  interviewer.


package com.iacsd.java;

import java.util.Arrays;
import java.util.Scanner;

public class anagram
{

public static void main(String[] args)
{

  Scanner sc =new Scanner(System.in);

    String s1=sc.nextLine(); // enter the first string

    String s2=sc.nextLine(); // enter the second string
 
    if(s1.length() == s2.length()) // compare the length of both string
    {
    char arr1[]=s1.toCharArray(); // convert the string into a character type array

    char arr2[]=s2.toCharArray(); // convert the string into a character type array
 
    Arrays.sort(arr1);  // By calling sort method, we sort the array

    Arrays.sort(arr2);

    boolean check=true; // variable for checking
 
    for(int i=0; i<arr1.length; i++)
    {
    if(arr1[i]!=arr2[i]) // compare the character of both character type array
    {
    check=false;
    }
    }
    if(check==true)
    {
    System.out.println("Both strings are anagram");
    }
    else
    {
    System.out.println("not anagram");
    }
}

}
}


example-
i/p 1 is army

i/p 2 is mary

o/p strings are anagram.

i/p 1 abc

i/p 2 zxc

o/p strings are not anagram.

Program to check whether a number is perfect square or not.

Asked by KPIT , BITWISE.


import java.util.Scanner;

class PerfectSquare
{
public static void main(String [] args)
{
Scanner s=new Scanner(System.in);

int number=s.nextInt();

double d=Math.sqrt(number);    // d for finding square root of number

int j=(int)d;   //  typecast d into intger

if(d-j==0)
{
System.out.println("Yes number is perfect square");
}
else
{
System.out.println(" number is not perfect square");
}
}
}


example-  entered number is 25 then o/p is