Previous | Home | Next |
In java for searching an element in an array we have a predefined method in the java.util.Arrays class, which searches for the element by using the binary search technique. Its general syntax is given as :
static int binarySearch(type[] arr, valuetobesearched);
For searching the above method takes a sorted array of any data type and the value to be searched as parameters. This method will return an integer value, which will be index of the element if it exists in the array, otherwise, it will give a negative value at which the element can be stored.
Following code snippet will help you understand the concept better :
import java.util.Arrays; Java Tutorialslass sort { public static void main(String args[]) { String[] arr=new String[]{"shashi", "employee", "r4r", "software", "engineer"}; Arrays.sort(arr); for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } int j=Arrays.binarySearch(arr,"r4r"); System.out.println("The element is at"+j); System.out.println("The element is:"+arr[j]); } }
In above program we have stored the value returned by the binarySearch() method in an integer variable i.e j and then we printed the index of the element and its value.
Every Java program has a main method in which a string of array i.e.,String[] args is passed as a parameter, and thus arguments can specified on the command line.i.e. at the runtime. Following code snippet describes how to pass command line arguments in java:
Java Tutorialslass Java Tutorialsmdparameters { public static void main(String[] args) { int num1, num2; int sum;; num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); sum = num1 + num2; System.out.println("You have passed command line arguments :"+args[0]+","+args[1]); System.out.println("The sum of the numbers is given by :"+sum); } }
Previous | Home | Next |