Showing posts with label java program. Show all posts
Showing posts with label java program. Show all posts

Wednesday, 2 December 2015

How to convert Byte array to String in Java

In our application sometime there is need of byte array. We can use byte array for encryption purpose . We can convert a string to byte array using string getBytes() method. In byte array string become in decryted format . We can make string from byte array using this syntax.

String str = new String(ByteArray);


package com.javaproficiency;

public class StringToBinary {
public static void main(String[] args) {
String IPCode = "java string is good";
//convert string to byte  array
byte [] bytes = IPCode.getBytes();
System.out.println(" string ="+ IPCode);
System.out.println(" byte array ="+ bytes);
//Convert byte array to string 
String str = new String( bytes );
System.out.println(" str ="+  str);
}

}

Output:

 string =java string is good

 byte array =[B@6c267f18

 str =java string is good

How to check the given number is binary number or not -Java Program

In mathematics and digital electronics, a binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). The base-2 system is a positional notation with a radix of 2. Below we have write a java program for check given number binary or not.

package com.javaproficiency;

public class IsBinary {

public static void main(String[] args) {

IsBinary isBinary = new IsBinary();

System.out.println(" num 101000 is binary = "+ isBinary.isBinary(101000) );
System.out.println(" num 101300 is binary = "+ isBinary.isBinary(101300) );
System.out.println(" num 101900 is binary = "+ isBinary.isBinary(101900) );
System.out.println(" num 10001 is binary = "+ isBinary.isBinary(10001) );


}


public boolean isBinary( int num ){

boolean flag = true;
while (num  > 0) {
int rem = num %10;
if (rem > 1) {
flag = false;
break;
}
num = num/10;
}
return flag;
}


}



Output:

 num 101000 is binary = true
 num 101300 is binary = false
 num 101900 is binary = false
 num 10001 is binary = true


Thursday, 26 November 2015

How to count the number of occurrences of a character in a string in java

Count the number of occurrences of a character in a string is good programming questions . It is ask in colleges and schools mostly. This question also asked in many times in interviews. 

Method 1:

We can count number of occurrences of a character in a string with the help of indexOf() method.

package com.javaproficiency;

public class CountCharOccurance {
public static void main(String[] args) {
String str = "javaproficiencyexamplebyannu";
 
    String findStr = "a";
    int lastIndex = 0;
    int counter = 0;
 
    while (lastIndex != -1) {
 
     lastIndex = str.indexOf(findStr, lastIndex);
 
     if (lastIndex != -1) {
      counter++;
      lastIndex += findStr.length();
 
     }
    }
    System.out.println(counter);
}


}


Output: 

4


Method 2:

In this example we will use charAt() method of string for count number of occurrences of a character in a string .

package com.javaproficiency;

public class CountCharOccurancejava {
public static void main(String[] args) {
String s = "javaproficiencyexamplebyannu";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
   if( s.charAt(i) == 'a' ) {
       counter++;
   } 
}
System.out.println( counter );
}

}


Output:

4


Wednesday, 25 November 2015

How to Check number is prime or not


A number which is divided by one and itself is called prime number. For Example

7 is a prime number and
8 is not a prime number

package com.javaproficiency;

public class PrintPrime {

public static void main(String[] args) {
int i =101;
boolean flag = false;
for(int j=2 ; j <= i/2; j++){
if(i%j==0)
{
flag = true ;
break;
}
}
if(flag){
System.out.println(" number "+ i +" is not prime");
}else{
System.out.println(" number "+ i +" is  prime");
}

}

}


Output :

 number 101 is  prime

Monday, 9 February 2015

Multithreading in Java


What is Multithreading?
Life Cycle of a Thread
thread vs proccess.
Thread Scheduler
Creating Thread
Sleeping a thread
Start a thread twice
Calling run() method
Joining a thread
Naming a thread
Thread Priority
Daemon Thread
Thread Pool
Synchronization
Messaging
Thread Class
Runnable Interface .
IsAlive()
Join()

Sunday, 8 February 2015

Interesting Facts In Exception Handling In java

1. What will Output Of This Program:

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
int j=10/0;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}


}
}

Explanation : when the statement arr[10]=100  encounter to compiler so exception occur and compiler check matching catch block and produce message  according it.

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
 

2. What will Output Of This Program:

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
int j=10/0;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}


}
}

Output:
java.lang.ArithmeticException: / by zero

3. What will Output Of This Program:


package exception_handling;

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
System.out.println("You Are In Catch Block");
} 
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("You Are In Main Method");
}
}


Explanation : when the statement arr[10]=100  encounter to compiler so exception occur . Now compiler ignore remaining  try block and check matching catch block and produce message  according it and continue to flow of program. 

Output:
java.lang.ArrayIndexOutOfBoundsException: 10
You Are In Main Method              

Multiple Catch Block In Exception Handling In java

1.  We can use multiple catch block for exception handling.

Syntax:

try {
}
catch () {
}
catch () {
}
catch () {
}

Example :


public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];

try {
             
arr[10]=100;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

}
}



Output:

java.lang.ArrayIndexOutOfBoundsException: 10

2:     Remember that when we use multiple catch block , use catch block down to top hierarchy. 
   Because in java unreachable code gives error. 

  
  public static void main(String[] args) {
           int i=10;
           int j=0;
           try {
               System.out.println("i/j="+i/j);
        } catch (Exception e) {
            System.out.println(e);
        }
         catch (IndexOutOfBoundsException e) {
                System.out.println(e);
        } 
          
       }

Output:
Unreachable catch block for IndexOutOfBoundsException. It is already handled by the catch block for Exception 

3.  The right way of uses multiple catch block is use first specific catch handle then use  standard catch handle.(i.e. down  to top ).

Example:

public class simple_example {

        public static void main(String[] args) {
           int i=10;
           int j=0;
           try {
               System.out.println("i/j="+i/j);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("index out of bound"+e);
        }
         catch (ArithmeticException e) {
                System.out.println("Arithmetic="+e);
        } 
         catch (Exception e) {
             System.out.println(e);
        } 
           
       }
}

Output:

Arithmetic=java.lang.ArithmeticException: / by zero