on Leave a Comment

Linear Search in Java

Linear search is a searching technique to search an element in array. We can also search element in array using binary search. Linear search is slower than binary search, so it is less used. But in linear search we don't need to sort an array while performing searching. So both searching technique have their own advantages and disadvantages.

In linear search, we traverse an array for searching specific element. If array is found, we note its index number and if item is not found till end, we display that "Element is not found".

Java program for linear search

/*Linear Search in Java*/
import java.util.Scanner;
public class LinearSearch{
 public static void search(int arr[], int item){
  int i, flag = 0;
  for(i = 0; i<arr.length; i++){
   if(arr[i] == item){
    flag = 1;
    System.out.println("Element "+arr[i]+" is found at index "+i);
   }
  }
  if(flag!=1)
   System.out.println("Element "+arr[i]+" is not found");
 }
 public static void main(String[] args){
  Scanner read = new Scanner(System.in);
  int []arr = new int[5];
  System.out.print("Enter Array Element (5 Elements): ");
  for(int i = 0; i<arr.length; i++){
   arr[i] = read.nextInt();
  }
  System.out.print("Enter the element to search: ");
  int item = read.nextInt();
  search(arr, item);
 }
}

Output:

Enter Array Element (5 Elements): 1 2 3 4 5
Enter the element to search: 3
Element 3 is found at index 2




on Leave a Comment

Binary Search in Java

Binary Search is a simple approach to search an element in array. If you are using binary search for searching element in array, then array must be sorted in ascending order. We can sort an array using sorting algorithms or by using Arrays.sort(arr) method. Binary search is faster than linear search. Binary search is also known as Half-Interval algorithm.

In binary search, we compares the given element with the middle element of array. If middle element is equal to given element then index of the middle element is returned. If given element is less than middle element, the algorithm again repeats on the sub-array to the left of the middle element and if the given element is greater than middle element, the algorithm again repeats on the sub-array to the right of the middle element.

Binary Search in Java

class BinarySearch{
	public static void binarySearch(int arr[], int start, int end, int key){
		int mid = (start + end)/2;  
		while( start <= end ){
			if ( arr[mid] < key ){
				start = mid + 1;     
			}
			else if ( arr[mid] == key ){
				System.out.println("Element "+key+" is found at index: " + mid);  
				break;  
			}
			else{
				end = mid - 1;
			}
			mid = (start + end)/2;  
                }  
		if ( start > end ){
			System.out.println("Element is not found!");  
		}  
	}  
	public static void main(String args[]){  
        int arr[] = new int[]{10,20,30,40,50};  
        int key = 40; 
        int end = arr.length-1;  
        binarySearch(arr,0,end,key);     
 }
}

Output:

Element 40 is found at index: 3

Binary Search in Java Using Recursion

class BinarySearch{
	public static int binarySearch(int arr[], int start, int end, int key){  
        if (end>=start){  
            int mid = start + (end - start)/2;  
            if (arr[mid] == key){  
            return mid;  
            }  
            if (arr[mid] > key){  
            return binarySearch(arr, start, mid-1, key);//search in left subarray  
            }
			else{  
            return binarySearch(arr, mid+1, end, key);//search in right subarray  
            }  
        }  
        return -1;  
    }  
    public static void main(String args[]){  
        int arr[] = {10,20,30,40,50};  
        int key = 50;  
        int end=arr.length-1;  
        int result = binarySearch(arr,0,end,key);  
        if (result == -1)  
            System.out.println("Element is not found!");  
        else  
            System.out.println("Element "+key+" is found at index: "+result);  
    }  
}

Output:

Element 50 is found at index: 4

Binary Search in Java Using Arrays.binarySearch()

binarySearch() is a method in Arrays class, so we need to import java.util package.

import java.util.Arrays;  
class BinarySearch{  
    public static void main(String args[]){  
        int arr[] = {10,20,30,40,50};  
        int key = 20;  
        int result = Arrays.binarySearch(arr,key);  
        if (result < 0)  
            System.out.println("Element "+key+" not found!");  
        else  
            System.out.println("Element "+key+" is found at index: "+result);  
    }  
}

Output:

Element 20 is found at index: 1






on Leave a Comment

What is the World Wide Web (WWW)?

The World Wide Web is a repository of information linked together through hyperlinks all over the world. As Internet have many services and World Wide Web is one of them. The World Wide Web supports special document that are formatted in HTML. Tim Berners-Lee, an English scientist, invents WWW in 1989. Berners-Lee developed hyperlinks to link web pages. User can easily access these web pages through WWW repository.

The WWW is distributed client server service, in which a client access web pages by web browser. These webpages is stored on server. The web browser sends requests to the server for specific web page using URL. After receiving the request, the server sends requested web pages and then these web pages is displayed on browser screen, it is a short description. 

on Leave a Comment

Packages in Java

Package is a way of grouping a variety of classes and interfaces together. In java, package is a way to organize set of related classes and interfaces. In simple words, a package is similar to different folders in our computer. We keep images in one folder, songs in other folder and so on. So, we keep set of related documents in one folder. There can be two classes in two different package can have same name as two files having same name in two different folders in our computer.

In java, we have ability to reuse code by extending classes and implementing interfaces. But if we have to reuse the code written in another program without copying the code. This can be achieved by using packages. Java provides a class library for use in our own application called API or Application Programming Interface. This API provides large number of classes grouped into different packages according to their functionality.

Advantages of Package in Java

(1) While making a large project, we have many classes and interfaces, so it is required to group set of related classes and interfaces into packages. It provides better organisation and improves efficiency.

(2) We can put two classes of same name in two different package, so it avoids name collision.

(3) Java package provides reusability of code by using different classes and interfaces in different packages.

(4) We can't directly access the code of classes and interfaces, so it provides access protection.

Types of Package in Java

Built-in package

Java already provides many different packages like java.lang.*, java.io.* known as built-in packages.

User defined package

We can also create our own package known as user defined package.

Example of Java Package

package showMe;

public class Show{
 public void disp(){
  System.out.println("Hello");
 }
}

import showMe.Show;

public class Demo{
 public static void main(String[] agrs){
  Show obj = new Show();
  obj.disp();
 }
}

Output:

Hello

In this example, first we create a package namely "showme" using package keyword. We define a class called "Show" and this class containing only one method called "disp". While putting a class to a package, the class must be of public access modifier.

We can create another class called "Demo", this class imports "showMe" using import keyword. In Demo class, we create an object of "Show" class of "showMe" package and called a method called "disp".

To Compile: javac -d . Show.java
Then again, javac Demo.java
To run Demo class: java Demo

Example 2:

We can create a class inside a package while importing another package.

package Package2;
import showMe;

class Example{
 public static void main(String[] args){
 Show obj = new Show();
 obj.disp();
 }
}

In this program, first we write package declaration and then we import another package.

It is important to know that if we write package declaration statement in our program, then it must be the first statement of program.

Example 3:

If you don't want to write import statement, then you can use fully qualified name.

Greatest.java

package Package1;
public class Greatest{
  public void checkGreatest(int a, int b){
    if(a>b)
   System.out.println(a+" is greater than "+b);
 else
   System.out.println(b+" is greater than "+a); 
  }
}

Example.java

class Example{
 public static void main(String[] args){
 Package1.Greatest obj = new Package1.Greatest();
 obj.checkGreatest(10, 20);
 }
}

Output:

20 is greater than 10

Sub package in Java

We can create a package inside another package. For example, java has also sub packages like lang, io, net etc.

Example:

Show.java

package Package1.SubPackage1;
public class Show{
 public void disp(){
  System.out.println("Welcome");
 }
}

Example.java

import Package1.SubPackage1.*;
class Example{
 public static void main(String[] args){
 Show obj = new Show();
 obj.disp();
 }
}

Output:

Welcome








on Leave a Comment

Java Program to Check Whether Two Strings are Anagram or Not

This java program checks whether two strings are anagram or not. Anagram means producing a new word using rearranging of letters of a word, length of letters must be same in both new and previous words. In this java program, user will enter two strings and the code of checking anagram runs and show whether both strings are anagram or not. 

Java Program Check Anagram or Not

Example 1:

In this program, first we check the length of both strings, if length is same then runs the if blocks, otherwise run the else block. In else block, print "Strings are not Anagram". And in the if block, we take first letter of first string and compare it with all letters of second string. If the letter not matches, print "Not Anagram" and exit the program. After checking first letter of first string, check another letter. When all letter string 1 matches with string 2, prints "Strings are Anagram".

import java.util.Scanner;
public class CheckAnagram{
	public static void main(String[] args) {
		String str1, str2;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter First String: ");
		str1 = sc.next();
		System.out.print("Enter Second String: ");
		str2 = sc.next();

		int i, j, found=0;
		if(str1.length() == str2.length()){
			for(i=0; i<str1.length(); i++)
			{
				for(j=0; j<str1.length(); j++){
					if(str1.charAt(i) == str2.charAt(j)){
						found =1;
					}
				}
				if(found==0){
					System.out.println("Strings are not Anagram");
					System.exit(0);
				}		
			}
			System.out.println("Strings are Anagram");	
		}
		else{
			System.out.println("Strings are not Anagram");
		}	
	}
}

Output:

Enter First String: triangle
Enter Second String: integral
Strings are Anagram

Enter First String: alpha
Enter Second String: beta
Strings are not Anagram

Example 2:

In this program, first we check the length of both strings and if length is same if block runs, otherwise else block runs. In else block, print "Strings are not Anagram". And in if block, sort both array and directly compares string 1 with string 2. If both strings matches print "Strings are Anagram", otherwise print "String are not Anagram".

import java.util.Scanner;
import java.util.Arrays;
public class CheckAnagram{
	public static void main(String[] args) {
		String str1, str2;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter First String: ");
		str1 = sc.next();
		System.out.print("Enter Second String: ");
		str2 = sc.next();
        
        char c1[] = str1.toCharArray();
        char c2[] = str2.toCharArray();
        str2 = str2.replaceAll("\\s", "");
        Arrays.sort(c1);
        Arrays.sort(c2);
		if(str1.length() == str2.length()){
			if(Arrays.equals(c1, c2))
				System.out.println("Strings are Anagram");
			else
				System.out.println("Strings are not Anagram");
		}
		else{
			System.out.println("Strings are not Anagram");
		}	
	}
}

Output:

Enter First String: triangle
Enter Second String: integral
Strings are Anagram

Enter First String: alpha
Enter Second String: beta
Strings are not Anagram