Java Program for Binary Search

From Wikipedia
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues for the remaining half until it is successful or the remaining half is empty.
This search method uses low and high positions and matches with the middle element. The array must be in sorted order and low and high positions are changed in order to search the given data(mid = (low + high) / 2. If the given value is less than mid-value then high = mid - 1. If the value is greater then mid-value then low = mid + 1 and if the given value is equal to the mid-value then the search result found and printed.
The time complexity of the above algorithm is O(n).

Binary Search with Number

import java.util.*;
public class BinarySearch
{
public static void main(String arg[])
{
int n[]={1,4,6,7,8,9,10,11,14,15,16};
int low, high, mid, p=0, l, i, m, f=0;
l=n.length;
low=0;
high=l;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to search:");
m=sc.nextInt();
while(low<=high)
{

mid=(low+high)/2;
if(m<n[mid])
high=mid-1;
else if(m>n[mid])
low=mid+1;
else if(m==n[mid])
{

f=1;
p=mid+1;
break;

}
}
if(f==1)
{
System.out.println(m+" is located at "+p);
}
else
{
}
}

}

Binary Search with String

import java.io.*;
public class BinarySearchWithSorting
{
public static void main(String args[]) throws IOException
{
String name[] = new String[20];
String s, t;
int i,f=0,j;
int low, high, mid, pos;
System.out.println("Enter 20 Names in array:");
for(i=0;i<20;i++)
{
}
System.out.println("Enter name to Search:");
// Sorting of array
for(i=0;i<19;i++)
{
for(j=0;j<19-i;j++)
{
if(name[j].compareTo(name[j+1])>0)
{
t = name[j];
name[j] = name[j+1];
name[j+1] = t;
}
}
}
System.out.println("Sorted array:");
for(i=0;i<20;i++)
{
System.out.print(name[i] + " ");
}
// Binary Search
high=20;
low=0;
pos=0;
while(low <= high)
{
mid = (low + high) / 2;
if(s.compareTo(name[mid])<0)
{
high = mid - 1;
}
else if(s.compareTo(name[mid])>0)
{
low = mid + 1;
}
else if(s.compareTo(name[mid])==0)
{
pos = mid + 1;
break;
}
}
System.out.println("\n Search result");
System.out.println(s+" is located at " + pos);
}

}

Wrapper class in Java

According to Wikipedia “In object-oriented programming, a wrapper class is a class that encapsulates types, so that those types can be used to create object instances and methods in another class that needs those types. So a primitive wrapper class is a wrapper class that encapsulates hides or wraps data types from the eight primitive data so that these can be used to create instantiated objects with methods in another class or in other classes. The primitive wrapper classes are found in the Java API.”

The primitive data type must be converted to it’s corresponding wrapper class, because the object is necessary to modify the argument or parameter passed into the method.

Collection framework such ArrayList, Vector store only the objects, not primitive data types so it must be converted to its corresponding wrapper class.

It is a process by which we can convert primitive data types into object types.  Every primitive data type has its own wrapper class.
 Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double

All the wrapper class is the subclasses of the abstract number class.

Java data types are primitive by default and sometimes we require to represent as an object so we need to wrap the primitive data type in a class.

class WrapperClassExample
{
public static void main(String[] args)
{
String a = "20";
String b = "30";
int f1, f2, result;
System.out.println("Sum before:"+ a + b); // print 2030 not 50
f1 = Integer.parseInt(a); // convert String to int type
f2 = Integer.parseInt(b); // convert String to int type
result = f1 + f2;
System.out.println("sum after: " + result); // 50
}
}

public class Example {
public static void main(String[] args) {
Integer intEx = 10
Double doubleEx = 8.87
Character charEx = 'C'
System.out.println(intEx);
System.out.println(doubleEx);
System.out.println(charEx);
}
}

Boxing-UnBoxing in Java is used to automatically convert the primitive data types into its corresponding objects.

Sample output
Sum before:2030
sum after: 50

In this program, we try to add a and b it will give 2030 not 50 because “20” and “30” are not integer type. So if need to sum it up then we need to convert String to int type.

Buy some important Computer Books Books
Java: The Complete Reference by Herbert Schildt
Java: A Beginner's Guide, Sixth Edition by Herbert Schildt
DSSSB TGT, PGT COMPUTER SCIENCE GUIDE-CUM-PWB (E) - 1039 by Think Tank of Kiran Prakashan (Author)
UGC NET/JRF/SET Computer Science and Applications: Paper II & III by Chandresh Shah (Author), Saurab Mishra (Author)

Autoboxing and Unboxing in java example

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.
Autoboxing: When primitive data types convert automatically to convert to the wrapper class is know as Autoboxing. For example, byte converts to Byte, int to Integer, double to double, etc.
Auto-Unboxing: When wrapper class converts automatically to the primitive data types is known as Autoboxing. For example Byte to byte, Integer to int, Long to long, Float to float, Double to double, etc.

This feature of java was added in java 5
public class AutBoxingUnBoxing
{
public static void main(String args[])
{
//Converting short (Primitive type) into Short (Wrapper class)
short a=45;  // assign value to short type
//converting short into Short Explicitly
Short b=Short. ValueOf (a);
Short c=a; //autoboxing, no need to convert explicitly
short d=c; // auto-unboxing
System.out.println(a + " " + b + " " + b + " " + d);
}
}

Best Java Books

Core Java: An Integrated Approach, New (Includes All Versions up to Java 8)

Java: A Beginner's Guide by Herbert Schildt

Output:
45 45 45 45
Here 45 assign as a short primitive type and convert it into Wrapper class by valueOf() method that is explicit. But Short c=a is automatically converted primitive to Wrapper (Autoboxing)

·         This feature of java lets developers write cleaner code
·         Automatically convert primitive to the wrapper and vice versa
·         Easier to comprehend and read.

AutoBoxing is very handy when developers are working with java.util.Collection. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type, we can create Collection only of Objects. For Example:

ArrayList<int> alist = new ArrayList<int>(); // not supported

ArrayList<Integer> alist = new ArrayList<Integer>(); // supported

Because ArrayList only works for an object. But by autoboxing, it is directly converted to object.
alist.add(20); //auto Boxing (automatically convert primitive to a collection type)

More related topics

CORE JAVA INTERVIEW QUESTIONS AND ANSWERS

Q.  What is Java?
It is a general-purpose computer programming language which is fast, secure, simple, architecturally neutral, reliable, portable and object-oriented. It is built by Sun Microsystem in 1995 which was initiated by James Gosling.

Q. Write any five features of Java.
Object oriented
Platform Independence
Robust Secure
Automatic memory management

Q. Why java is platform independence?
It is because Java byte-code is not associated with any particular hardware platform. It can be executed on any machine with JVM.

Q. What is an Object?
The object is an instance of a class. It is the name of any person, place, things or entity. It must have and identity, state, and behavior.

Q. What is a class?
It is a blueprint of an object. A class may contain data (variables) and modules (method).

Q. What is OOP’s?
Object-oriented programming (OOP) is a new way of organizing around objects which represent as an instance of a class and it revolves around Abstraction, Encapsulation, Inheritance and Polymorphism.

Q. What is JDK?
It is a collection of various tools that helps in writing and implementing Java program.

Q. What is JVM?
Java Virtual Machine is piece software which interprets java bytecode for a particular
platform or we can say a JVM is a program that behaves like a computer.

Q. What is Bytecode?
When java compiler compiles the java source code, it becomes bytecode. So java bytecode is nothing but java compile code. It is a platform independent code.
Say Hello.java ร  compile ร  Hello.class (Byte Code) ร  Run in JVM

Q. What is UNICODE?
Unicode is a 2 bytes code international encoding set use to with characters and digit or symbol.

Q. Why Java is ‘Write once and Ran anywhere’?
When java source code compile it become bytecode and it run everywhere provided JVM is there. That is why it is called ‘Write once and Ran anywhere’.

Q. What is java Tokens?
Smallest individual units in a program are known as tokens.

Q. What are data types?
To identify the type of data involved in an operation is called Data Types. There are two types od data types (primitive or fundamental types) and (non-primitive or reference types)

Q. What are default values of different primitive types?
byte                 0
short                0
int                    0
long                 0 l
float                 0.0 f
double             0.0 d
boolean           false
char                 null

Q. What is the difference between primitive and nonprimitive (reference) data types in Java?
Primitive Data Type: Primitive means “very basic”. Very basic or Fundamental data types available with java is known Primitive data types. Example are byte, char, int, long, float, double etc.
NonPrimitve Data Type: Non-primitive data types or reference are those which uses primitive data type as a base like an array, enum, class etc.

Q. What is wrapper class?
It is a process by which we can convert primitive data type into object types.  Every primitive data type has wrapper class. All the wrapper class is the sub classes of the abstract number class.

 Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double

Q. What is type casting?
The process of converting one type of data type into another type is called type casting.

Q. What is Coercion?
Coercion is a type conversion where data are promoted. It is also known as type promotion. For example, parsing the Java String "60" to the Integer 60 would be coercion.

Q. Define Abstraction, Encapsulation, Polymorphism, and Inheritance.
Abstraction, Encapsulation, Polymorphism, Inheritance
Abstraction: Abstraction refers to the act of representing essential features without including the background details or explanations.
Polymorphism: It is referred to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles, and triangles. No matter what shape an object is, applying the area method to, it will return the correct results
Encapsulation: The wrapping up of data and methods into a single unit is called Encapsulation.
.Inheritance: It is the process by which objects of one class acquire the properties of objects of anther class. Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of a motorbike. Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chainring, giving them a lower gear ratio.

Q. What are variables? How many types of variable are there in Java?
Variables are places in the memory where we can store data. It has three types. a. Local variable, Instance variable, and Class variable.
Local Variable: It is defined within the method and constructor. These variables visibility remain within the method and constructor.
Instance Variables: Define inside a class. It is available for every instances of the class.
Class variable: when a variable defines with keyword static inside a class is known as the class variable.
All object of the class shares static variables because of only a single copy of these available in the memory.

Q. What is final variable?
When a variable defines with the final keyword then its value can not be change throughout the whole program.
Example
class Circle{
final int pi=3.14;//final variable cannot be change
double a, r;
void area(){
r = 3.5;
a = r*r*pi;
System.out.println("Area="+a)
}
public static void main(String args[]){
Circle obj=new  Circle();
obj.area();
}
}//end of class

Q. Can ‘main’ method be declared final?
Yes, the main method can declare as final.
public class Example
{
public static final void main(String args[])
{
int a=6;
System.out.print((++a)+(a--));

}
}

Java Interview QA

Q. What is static variable?
A static variable is shared by all instances of a class. It is also known as a class variable and it is declared with keyword ‘static’.  Instances (objects) of the same class share a single copy of static variables.
class School
int rollno;
String section;
String name;
static String schoolName ="InspireSkills Edu";
// constructor
School(int r, String s, String n){
rollno = r;
section = s;
name = n;
}
void display ()
{
System.out.println(rollno + " " + section + "   " + name + " " + schoolName);
}
public static void main(String args[])
{
School ob1 = new School(1, "A", "Mukesh");
School ob2 = new School(2, "B", "Aryan");

ob1.display();
ob2.display();
}

Q. What is the static method?
When a method defines with static keyword before a data type is called a static method.
class  Example
{
public static void print()
{
System.out.println(“This is a static method”);
}
}

Q. What is Garbage collection?
When an object is no longer required, java automatically free the memory space is known as Garbage Collection.

Q. What is java package?
A java package is a Java language element used to group related classes under a common name. Packages can be nested inside one another. The main package is java in java language

Q. What is escape sequence?
The combination of characters is preceded by a code extension. It comes with the backslash (\).For example, \n stands for new line; even though it looks two characters, Java treats them as one character with ASCII code of 10. Escape sequence, being a single character, should be put within single quotes.

 Escape Sequences Escape Sequence Description \t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point. \r Insert a carriage return in the text at this point. \f Insert a form feed in the text at this point. \' Insert a single quote character in the text at this point. \" Insert a double quote character in the text at this point. \\ Insert a backslash character in the text at this point.